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/TrueHD"),
76 st(0x84, A, 0, 0, "SDDS/EAC3"),
77 st(0x85, U, 0, 0, "ATSC Program ID"),
78 st(0x86, A, HB_ACODEC_DCA, 0, "DTS-HD"),
79 st(0x87, A, HB_ACODEC_MPGA, CODEC_ID_EAC3, "EAC3"),
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;
702 if ( d->ts_stream_type[d->ts_number_pids] == 0x84 &&
703 title->reg_desc == STR4_TO_UINT32("HDMV") )
705 // EAC3 audio in bluray has an stype of 0x84
706 // which conflicts with SDDS
707 // To distinguish, Bluray streams have a reg_desc of HDMV
708 d->ts_stream_type[d->ts_number_pids] = 0x87;
714 d->ts_flags = TS_HAS_RAP;
715 // When scanning, title->job == NULL. We don't need to wait for
716 // a PCR when scanning. In fact, it trips us up on the first
717 // preview of every title since we would have to read quite a
718 // lot of data before finding the PCR.
719 if (title->pcr_pid != 0xFFFF && title->job)
721 if ( index_of_pid( d, title->pcr_pid ) < 0 )
723 // BD PCR PID is specified to always be 0x1001
724 d->ts_pids[d->ts_number_pids] = 0x1001;
725 d->ts_stream_kind[d->ts_number_pids] = P;
731 d->hb_stream_type = transport;
733 for ( ii = 0; ii < d->ts_number_pids; ii++ )
735 d->ts_buf[ii] = hb_buffer_init(d->packetsize);
736 d->ts_buf[ii]->size = 0;
742 /***********************************************************************
744 ***********************************************************************
745 * Closes and frees everything
746 **********************************************************************/
747 void hb_stream_close( hb_stream_t ** _d )
749 hb_stream_t *stream = * _d;
751 if ( stream->hb_stream_type == ffmpeg )
753 ffmpeg_close( stream );
754 hb_stream_delete( stream );
759 if ( stream->frames )
761 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
762 stream->errors, (double)stream->errors * 100. /
763 (double)stream->frames );
767 * if the stream was opened for a scan, cache the result, otherwise delete
770 if ( stream->title == NULL )
772 hb_stream_delete_dynamic( stream );
773 if ( stream_state_list == NULL )
775 stream_state_list = hb_list_init();
777 hb_list_add( stream_state_list, stream );
781 hb_stream_delete( stream );
786 /* when the file was first opened we made entries for all the audio elementary
787 * streams we found in it. Streams that were later found during the preview scan
788 * now have an audio codec, type, rate, etc., associated with them. At the end
789 * of the scan we delete all the audio entries that weren't found by the scan
790 * or don't have a format we support. This routine deletes audio entry 'indx'
791 * by setting its PID to an invalid value so no packet will match it. (We can't
792 * move any of the entries since the index of the entry is used as the id
793 * of the media stream for HB. */
794 static void hb_stream_delete_entry(hb_stream_t *stream, int indx)
796 if ( stream->ts_pids[indx] > 0 )
798 stream->ts_pids[indx] = -stream->ts_pids[indx];
802 /***********************************************************************
803 * hb_ps_stream_title_scan
804 ***********************************************************************
806 **********************************************************************/
807 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
809 if ( stream->hb_stream_type == ffmpeg )
810 return ffmpeg_title_scan( stream );
813 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
814 aTitle->type = HB_STREAM_TYPE;
817 // Copy part of the stream path to the title name
818 char *sep = strrchr(stream->path, '/');
820 strcpy(aTitle->name, sep+1);
821 char *dot_term = strrchr(aTitle->name, '.');
825 // Height, width, rate and aspect ratio information is filled in when the previews are built
827 hb_stream_duration(stream, aTitle);
830 hb_chapter_t * chapter;
831 chapter = calloc( sizeof( hb_chapter_t ), 1 );
833 chapter->duration = aTitle->duration;
834 chapter->hours = aTitle->hours;
835 chapter->minutes = aTitle->minutes;
836 chapter->seconds = aTitle->seconds;
837 hb_list_add( aTitle->list_chapter, chapter );
839 // Figure out how many audio streams we really have:
840 // - For transport streams, for each PID listed in the PMT (whether
841 // or not it was an audio stream type) read the bitstream until we
842 // find an packet from that PID containing a PES header and see if
843 // the elementary stream is an audio type.
844 // - For program streams read the first 4MB and take every unique
845 // audio stream we find.
846 if (stream->hb_stream_type == transport)
850 for (i=0; i < stream->ts_number_pids; i++)
852 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
855 hb_list_add( aTitle->list_audio, audio );
859 // make sure we're grabbing the PCR PID
860 if ( index_of_pid( stream, stream->pmt_info.PCR_PID ) < 0 )
862 stream->ts_pids[stream->ts_number_pids] = stream->pmt_info.PCR_PID;
863 stream->ts_stream_kind[stream->ts_number_pids] = P;
864 stream->ts_number_pids++;
867 for (i = 0; i < stream->ts_number_pids; i++)
869 kind_t kind = stream->ts_stream_kind[i];
871 if ( kind == N || kind == U )
873 hb_stream_delete_entry(stream, i);
877 // set the video id, codec & muxer
878 int idx = index_of_video( stream );
881 hb_title_close( &aTitle );
885 aTitle->video_id = stream->ts_pids[idx];
886 aTitle->video_codec = st2codec[stream->ts_stream_type[idx]].codec;
887 aTitle->video_codec_param = st2codec[stream->ts_stream_type[idx]].codec_param;
888 aTitle->demuxer = HB_MPEG2_TS_DEMUXER;
890 if ( ( stream->ts_flags & TS_HAS_PCR ) == 0 )
892 hb_log( "transport stream missing PCRs - using video DTS instead" );
895 if ( stream->ts_IDRs < 1 )
897 hb_log( "transport stream doesn't seem to have video IDR frames" );
898 aTitle->flags |= HBTF_NO_IDR;
903 hb_ps_stream_find_audio_ids(stream, aTitle);
910 * read the next transport stream packet from 'stream'. Return NULL if
911 * we hit eof & a pointer to the sync byte otherwise.
913 static const uint8_t *next_packet( hb_stream_t *stream )
915 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
919 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
928 // lost sync - back up to where we started then try to re-establish.
929 off_t pos = ftello(stream->file_handle) - stream->packetsize;
930 off_t pos2 = align_to_next_packet(stream);
933 hb_log( "next_packet: eof while re-establishing sync @ %"PRId64, pos );
936 ts_warn( stream, "next_packet: sync lost @ %"PRId64", regained after %"PRId64" bytes",
942 * skip to the start of the next PACK header in program stream src_stream.
944 static void skip_to_next_pack( hb_stream_t *src_stream )
946 // scan forward until we find the start of the next pack
947 uint32_t strt_code = -1;
950 flockfile( src_stream->file_handle );
951 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
953 strt_code = ( strt_code << 8 ) | c;
954 if ( strt_code == 0x000001ba )
955 // we found the start of the next pack
958 funlockfile( src_stream->file_handle );
960 // if we didn't terminate on an eof back up so the next read
961 // starts on the pack boundary.
964 fseeko( src_stream->file_handle, -4, SEEK_CUR );
968 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
970 // For mpeg2: look for a gop start or i-frame picture start
971 // for h.264: look for idr nal type or a slice header for an i-frame
972 // for vc1: look for a Sequence header
977 if ( stream->ts_stream_type[0] <= 2 )
979 // This section of the code handles MPEG-1 and MPEG-2 video streams
980 for (i = 13 + adapt_len; i < 188; i++)
982 strid = (strid << 8) | buf[i];
983 if ( ( strid >> 8 ) == 1 )
985 // we found a start code
989 case 0xB8: // group_start_code (GOP header)
990 case 0xB3: // sequence_header code
993 case 0x00: // picture_start_code
994 // picture_header, let's see if it's an I-frame
997 // check if picture_coding_type == 1
998 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
1000 // found an I-frame picture
1008 // didn't find an I-frame
1011 if ( stream->ts_stream_type[0] == 0x1b )
1013 // we have an h.264 stream
1014 for (i = 13 + adapt_len; i < 188; i++)
1016 strid = (strid << 8) | buf[i];
1017 if ( ( strid >> 8 ) == 1 )
1019 // we found a start code - remove the ref_idc from the nal type
1020 uint8_t nal_type = strid & 0x1f;
1021 if ( nal_type == 0x05 )
1022 // h.264 IDR picture start
1026 // didn't find an I-frame
1029 if ( stream->ts_stream_type[0] == 0xea )
1031 // we have an vc1 stream
1032 for (i = 13 + adapt_len; i < 188; i++)
1034 strid = (strid << 8) | buf[i];
1035 if ( strid == 0x10f )
1037 // the ffmpeg vc1 decoder requires a seq hdr code in the first
1042 // didn't find an I-frame
1046 // we don't understand the stream type so just say "yes" otherwise
1047 // we'll discard all the video.
1052 * scan the next MB of 'stream' to find the next start packet for
1053 * the Packetized Elementary Stream associated with TS PID 'pid'.
1055 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
1057 int npack = 300000; // max packets to read
1059 while (--npack >= 0)
1061 const uint8_t *buf = next_packet( stream );
1064 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
1068 // while we're reading the stream, check if it has valid PCRs
1069 // and/or random access points.
1070 uint32_t pack_pid = ( (buf[1] & 0x1f) << 8 ) | buf[2];
1071 if ( pack_pid == stream->pmt_info.PCR_PID )
1073 if ( ( buf[5] & 0x10 ) &&
1074 ( ( ( buf[3] & 0x30 ) == 0x20 ) ||
1075 ( ( buf[3] & 0x30 ) == 0x30 && buf[4] > 6 ) ) )
1077 stream->ts_flags |= TS_HAS_PCR;
1080 if ( buf[5] & 0x40 )
1082 stream->ts_flags |= TS_HAS_RAP;
1086 * The PES header is only in TS packets with 'start' set so we check
1087 * that first then check for the right PID.
1089 if ((buf[1] & 0x40) == 0 || pack_pid != pid )
1091 // not a start packet or not the pid we want
1095 /* skip over the TS hdr to return a pointer to the PES hdr */
1097 switch (buf[3] & 0x30)
1099 case 0x00: // illegal
1100 case 0x20: // fill packet
1103 case 0x30: // adaptation
1106 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
1109 udata += buf[4] + 1;
1112 /* PES hdr has to begin with an mpeg start code */
1113 if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
1119 /* didn't find it */
1123 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
1125 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1126 hb_list_t *list = hb_list_init();
1127 // how many blocks we read while searching for a video PES header
1128 int blksleft = 1024;
1131 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1135 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1136 hb_demux_ps( buf, list, 0 );
1138 while ( ( es = hb_list_item( list, 0 ) ) )
1140 hb_list_rem( list, es );
1141 if ( es->id == 0xe0 )
1143 // this PES contains video - if there's a PTS we're done
1144 // hb_demux_ps left the PTS in buf_es->start.
1145 if ( es->start != ~0 )
1152 hb_buffer_close( &es );
1155 hb_list_empty( &list );
1156 hb_buffer_close(&buf);
1160 /***********************************************************************
1161 * hb_stream_duration
1162 ***********************************************************************
1164 * Finding stream duration is difficult. One issue is that the video file
1165 * may have chunks from several different program fragments (main feature,
1166 * commercials, station id, trailers, etc.) all with their own base pts
1167 * value. We can't find the piece boundaries without reading the entire
1168 * file but if we compute a rate based on time stamps from two different
1169 * pieces the result will be meaningless. The second issue is that the
1170 * data rate of compressed video normally varies by 5-10x over the length
1171 * of the video. This says that we want to compute the rate over relatively
1172 * long segments to get a representative average but long segments increase
1173 * the likelihood that we'll cross a piece boundary.
1175 * What we do is take time stamp samples at several places in the file
1176 * (currently 16) then compute the average rate (i.e., ticks of video per
1177 * byte of the file) for all pairs of samples (N^2 rates computed for N
1178 * samples). Some of those rates will be absurd because the samples came
1179 * from different segments. Some will be way low or high because the
1180 * samples came from a low or high motion part of the segment. But given
1181 * that we're comparing *all* pairs the majority of the computed rates
1182 * should be near the overall average. So we median filter the computed
1183 * rates to pick the most representative value.
1185 **********************************************************************/
1187 uint64_t pos; /* file position of this PTS sample */
1188 uint64_t pts; /* PTS from video stream */
1191 #define NDURSAMPLES 128
1193 // get one (position, timestamp) sampple from a transport or program
1195 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
1197 struct pts_pos pp = { 0, 0 };
1199 if ( stream->hb_stream_type == transport )
1202 fseeko( stream->file_handle, fpos, SEEK_SET );
1203 align_to_next_packet( stream );
1204 int pid = stream->ts_pids[index_of_video(stream)];
1205 buf = hb_ts_stream_getPEStype( stream, pid );
1208 hb_log("hb_sample_pts: couldn't find video packet near %"PRIu64, fpos);
1211 if ( ( buf[7] >> 7 ) != 1 )
1213 hb_log("hb_sample_pts: no PTS in video packet near %"PRIu64, fpos);
1216 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
1217 ( (uint64_t)buf[10] << 22 ) |
1218 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
1219 ( (uint64_t)buf[12] << 7 ) |
1220 ( (uint64_t)buf[13] >> 1 );
1222 if ( isIframe( stream, buf, -4 ) )
1224 if ( stream->ts_IDRs < 255 )
1232 // round address down to nearest dvd sector start
1233 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
1234 fseeko( stream->file_handle, fpos, SEEK_SET );
1235 if ( stream->hb_stream_type == program )
1237 skip_to_next_pack( stream );
1239 pp.pts = hb_ps_stream_getVideoPTS( stream );
1241 pp.pos = ftello(stream->file_handle);
1245 static int dur_compare( const void *a, const void *b )
1247 const double *aval = a, *bval = b;
1248 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
1251 // given an array of (position, time) samples, compute a max-likelihood
1252 // estimate of the average rate by computing the rate between all pairs
1253 // of samples then taking the median of those rates.
1254 static double compute_stream_rate( struct pts_pos *pp, int n )
1257 double rates[NDURSAMPLES * NDURSAMPLES / 8];
1260 // the following nested loops compute the rates between all pairs.
1262 for ( i = 0; i < n-1; ++i )
1264 // Bias the median filter by not including pairs that are "far"
1265 // from one another. This is to handle cases where the file is
1266 // made of roughly equal size pieces where a symmetric choice of
1267 // pairs results in having the same number of intra-piece &
1268 // inter-piece rate estimates. This would mean that the median
1269 // could easily fall in the inter-piece part of the data which
1270 // would give a bogus estimate. The 'ns' index creates an
1271 // asymmetry that favors locality.
1272 int ns = i + ( n >> 3 );
1275 for ( j = i+1; j < ns; ++j )
1277 if ( (uint64_t)(pp[j].pts - pp[i].pts) > 90000LL*3600*6 )
1279 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
1281 *rp = ((double)( pp[j].pts - pp[i].pts )) /
1282 ((double)( pp[j].pos - pp[i].pos ));
1287 // now compute and return the median of all the (n*n/2) rates we computed
1289 int nrates = rp - rates;
1290 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
1291 return rates[nrates >> 1];
1294 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
1296 struct pts_pos ptspos[NDURSAMPLES];
1297 struct pts_pos *pp = ptspos;
1300 fseeko(stream->file_handle, 0, SEEK_END);
1301 uint64_t fsize = ftello(stream->file_handle);
1302 uint64_t fincr = fsize / NDURSAMPLES;
1303 uint64_t fpos = fincr / 2;
1304 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
1306 *pp++ = hb_sample_pts(stream, fpos);
1308 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
1309 inTitle->duration = dur;
1311 inTitle->hours = dur / 3600;
1312 inTitle->minutes = ( dur % 3600 ) / 60;
1313 inTitle->seconds = dur % 60;
1315 rewind(stream->file_handle);
1318 /***********************************************************************
1320 ***********************************************************************
1322 **********************************************************************/
1323 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
1325 if ( src_stream->hb_stream_type == ffmpeg )
1327 return ffmpeg_read( src_stream, b );
1329 if ( src_stream->hb_stream_type == dvd_program )
1331 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
1332 src_stream->file_handle);
1333 return (amt_read > 0);
1335 if ( src_stream->hb_stream_type == program )
1337 // a general program stream has arbitrary sized pack's. we're
1338 // currently positioned at the start of a pack so read up to but
1339 // not including the start of the next, expanding the buffer
1341 uint8_t *cp = b->data;
1342 uint8_t *ep = cp + b->alloc;
1343 uint32_t strt_code = -1;
1346 // consume the first byte of the initial pack so we don't match on
1347 // it in the loop below.
1348 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1353 flockfile( src_stream->file_handle );
1354 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1356 strt_code = ( strt_code << 8 ) | c;
1357 if ( strt_code == 0x000001ba )
1358 // we found the start of the next pack
1362 // need to expand the buffer
1363 int curSize = cp - b->data;
1364 hb_buffer_realloc( b, curSize * 2 );
1365 cp = b->data + curSize;
1366 ep = b->data + b->alloc;
1369 // Non-video streams can emulate start codes, so we need
1370 // to inspect PES packets and skip over their data
1371 // sections to avoid mis-detection of the next pack header.
1372 if ( ( strt_code >> 8 ) == 0x000001 &&
1373 ( strt_code & 0xff ) >= 0xbb )
1376 c = getc_unlocked( src_stream->file_handle );
1380 c = getc_unlocked( src_stream->file_handle );
1384 if ( cp+len+2 > ep )
1386 // need to expand the buffer
1387 int curSize = cp - b->data;
1388 if ( curSize * 2 > curSize+len+2 )
1389 hb_buffer_realloc( b, curSize * 2 );
1391 hb_buffer_realloc( b, curSize + len + 2 );
1392 cp = b->data + curSize;
1393 ep = b->data + b->alloc;
1397 fread( cp, 1, len, src_stream->file_handle );
1401 funlockfile( src_stream->file_handle );
1403 // if we didn't terminate on an eof back up so the next read
1404 // starts on the pack boundary.
1405 b->size = cp - b->data;
1408 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1409 // Only 3 of the 4 bytes read were added to the buffer.
1414 return hb_ts_stream_decode( src_stream, b );
1417 int64_t ffmpeg_initial_timestamp( hb_stream_t * stream )
1419 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id];
1420 if ( s->nb_index_entries < 1 )
1423 return s->index_entries[0].timestamp;
1425 int hb_stream_seek_chapter( hb_stream_t * stream, int chapter_num )
1428 if ( stream->hb_stream_type != ffmpeg )
1430 // currently meaningliess for transport and program streams
1433 if ( !stream || !stream->title ||
1434 chapter_num > hb_list_count( stream->title->list_chapter ) )
1439 int64_t sum_dur = 0;
1440 hb_chapter_t *chapter = NULL;
1442 for ( i = 0; i < chapter_num; ++i)
1444 chapter = hb_list_item( stream->title->list_chapter, i );
1445 sum_dur += chapter->duration;
1447 stream->chapter = chapter_num - 1;
1448 stream->chapter_end = sum_dur;
1450 int64_t pos = ( ( ( sum_dur - chapter->duration ) * AV_TIME_BASE ) / 90000 ) + ffmpeg_initial_timestamp( stream );
1452 hb_deep_log( 2, "Seeking to chapter %d: starts %"PRId64", ends %"PRId64", AV pos %"PRId64,
1453 chapter_num, sum_dur - chapter->duration, sum_dur, pos);
1455 if ( chapter_num > 1 && pos > 0 )
1457 av_seek_frame( stream->ffmpeg_ic, -1, pos, 0);
1461 // ffmpeg has a bug that causes the first PTS after
1462 // av_find_stream_info() is called to be incorrect.
1463 // av_find_stream_info is called whenever opening a file
1464 // with ffmpeg. av_seek_frame clears the condition
1465 // that causes the problem. since hb_stream_seek_chapter
1466 // is called before we start reading, make sure
1467 // we do a seek here.
1468 av_seek_frame( stream->ffmpeg_ic, -1, ffmpeg_initial_timestamp( stream ), AVSEEK_FLAG_BACKWARD );
1473 /***********************************************************************
1475 ***********************************************************************
1476 * Return the number of the chapter that we are currently in. We store
1477 * the chapter number starting from 0, so + 1 for the real chpater num.
1478 **********************************************************************/
1479 int hb_stream_chapter( hb_stream_t * src_stream )
1481 return( src_stream->chapter + 1 );
1484 /***********************************************************************
1486 ***********************************************************************
1488 **********************************************************************/
1489 int hb_stream_seek( hb_stream_t * stream, float f )
1491 if ( stream->hb_stream_type == ffmpeg )
1493 return ffmpeg_seek( stream, f );
1495 off_t stream_size, cur_pos, new_pos;
1496 double pos_ratio = f;
1497 cur_pos = ftello( stream->file_handle );
1498 fseeko( stream->file_handle, 0, SEEK_END );
1499 stream_size = ftello( stream->file_handle );
1500 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1501 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1503 int r = fseeko( stream->file_handle, new_pos, SEEK_SET );
1506 fseeko( stream->file_handle, cur_pos, SEEK_SET );
1510 if ( stream->hb_stream_type == transport )
1512 // We need to drop the current decoder output and move
1513 // forwards to the next transport stream packet.
1514 hb_ts_stream_reset(stream);
1517 if ( stream->ts_IDRs )
1519 // the stream has IDRs so look for one.
1520 stream->need_keyframe = 1;
1525 // we're at the beginning - say we have video sync so that we
1526 // won't drop initial SPS & PPS data on an AVC stream.
1527 stream->need_keyframe = 0;
1530 else if ( stream->hb_stream_type == program )
1532 skip_to_next_pack( stream );
1538 int hb_stream_seek_ts( hb_stream_t * stream, int64_t ts )
1540 if ( stream->hb_stream_type == ffmpeg )
1542 return ffmpeg_seek_ts( stream, ts );
1547 static const char* make_upper( const char* s )
1549 static char name[8];
1551 char *ep = cp + sizeof(name)-1;
1553 while ( *s && cp < ep )
1555 *cp++ = islower(*s)? toupper(*s) : *s;
1562 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1565 * This is a duplicate of code in dvd.c - it should get factored out
1566 * into a common routine. We probably should only be putting the lang
1567 * code or a lang pointer into the audio config & let the common description
1568 * formatting routine in scan.c do all the stuff below.
1570 const char *codec_name;
1573 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1574 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1575 avcodec_find_decoder( cc->codec_id ) )
1577 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1578 if ( !strcmp( codec_name, "LIBFAAD" ) )
1583 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1584 avcodec_find_decoder( audio->config.in.codec_param ) )
1586 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1590 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1591 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1592 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1593 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1594 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1597 snprintf( audio->config.lang.description,
1598 sizeof( audio->config.lang.description ), "%s (%s)",
1599 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1602 if (audio->config.in.codec == HB_ACODEC_FFMPEG)
1604 int layout = audio->config.in.channel_layout;
1605 char *desc = audio->config.lang.description +
1606 strlen( audio->config.lang.description );
1607 sprintf( desc, " (%d.%d ch)",
1608 HB_INPUT_CH_LAYOUT_GET_DISCRETE_FRONT_COUNT(layout) +
1609 HB_INPUT_CH_LAYOUT_GET_DISCRETE_REAR_COUNT(layout),
1610 HB_INPUT_CH_LAYOUT_GET_DISCRETE_LFE_COUNT(layout) );
1613 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1614 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1615 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1616 "%s", lang->iso639_2);
1619 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1622 off_t cur_pos = ftello(stream->file_handle);
1623 hb_audio_t *audio = NULL;
1628 kind = stream->ts_stream_kind[idx];
1630 if ( kind != A && kind != U && kind != N )
1635 stype = stream->ts_stream_type[idx];
1637 fseeko(stream->file_handle, 0, SEEK_SET);
1638 align_to_next_packet(stream);
1640 buf = hb_ts_stream_getPEStype(stream, stream->ts_pids[idx]);
1642 /* check that we found a PES header */
1643 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1645 // 0xbd ("private stream 1") is the normal container for non-ISO
1646 // media - AC3/DCA/PCM/etc.
1647 if ( buf[3] == 0xbd )
1651 // XXX assume unknown stream types are AC-3 (if they're not
1652 // audio we'll find that out during the scan but if they're
1653 // some other type of audio we'll end up ignoring them).
1655 stream->ts_stream_type[idx] = 0x81;
1658 if ( stype == 0x80 &&
1659 stream->pmt_info.reg_desc == STR4_TO_UINT32("HDMV") )
1661 // LPCM audio in bluray have an stype of 0x80
1662 // 0x80 is used for other DigiCipher normally
1663 // To distinguish, Bluray streams have a reg_desc of HDMV
1667 else if ( buf[3] == 0xfd )
1669 // 0xfd indicates an extended stream id (ISO 13818-1(2007)).
1670 // the blu ray consortium apparently forgot to read the portion
1671 // of the MPEG spec that says one PID should map to one media
1672 // stream and multiplexed multiple types of audio into one PID
1673 // using the extended stream identifier of the PES header to
1674 // distinguish them. So we have to check if that's happening and
1675 // if so tell the runtime what esid we want.
1676 if ( st2codec[stype].kind == A && stype == 0x83 &&
1677 stream->ts_format_id[idx] == TS_FORMAT_ID_AC3 )
1679 // This is an interleaved TrueHD/AC-3 stream and the esid of
1681 stream->ts_multiplexed[idx] = 0x76;
1683 stream->ts_stream_type[idx] = 0x81;
1686 if ( st2codec[stype].kind == A && stype == 0x86 )
1688 // This is an interleaved DTS-HD/DTS stream and the esid of
1690 stream->ts_multiplexed[idx] = 0x71;
1692 stream->ts_stream_type[idx] = 0x82;
1695 if ( stype == 0x84 &&
1696 stream->pmt_info.reg_desc == STR4_TO_UINT32("HDMV") )
1698 // EAC3 audio in bluray has an stype of 0x84
1699 // which conflicts with SDDS
1700 // To distinguish, Bluray streams have a reg_desc of HDMV
1702 stream->ts_stream_type[idx] = 0x87;
1706 else if ((buf[3] & 0xe0) == 0xc0)
1708 // 0xC0 - 0xCF are the normal containers for ISO-standard
1709 // media (mpeg2 audio and mpeg4 AAC).
1710 if ( st2codec[stype].kind == U )
1712 // XXX assume unknown stream types are MPEG audio
1714 stream->ts_stream_type[idx] = 0x03;
1725 // if we found an audio stream type & HB has a codec that can decode it
1726 // finish configuring the audio so we'll add it to the title's list.
1727 if ( kind == A && st2codec[stype].codec )
1729 audio = calloc( sizeof( hb_audio_t ), 1 );
1731 stream->ts_stream_kind[idx] = A;
1732 audio->id = stream->ts_pids[idx];
1733 audio->config.in.codec = st2codec[stype].codec;
1734 audio->config.in.codec_param = st2codec[stype].codec_param;
1735 set_audio_description( audio,
1736 lang_for_code( stream->a52_info[idx].lang_code ) );
1737 hb_log("transport stream pid 0x%x (type 0x%x) may be %s audio (id 0x%x)",
1738 stream->ts_pids[idx],
1739 stype, st2codec[stype].name, audio->id);
1746 hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1747 "isn't audio", stream->ts_pids[idx],
1748 stream->ts_stream_type[idx], buf[3]);
1752 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1753 stream->ts_pids[idx],
1754 stream->ts_stream_type[idx]);
1757 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1762 static void add_audio_to_title(hb_title_t *title, int id)
1764 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1770 audio->config.in.codec = HB_ACODEC_MPGA;
1771 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1774 // type 2 is a DVD subtitle stream - just ignore it */
1778 audio->config.in.codec = HB_ACODEC_AC3;
1779 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1782 audio->config.in.codec = HB_ACODEC_LPCM;
1783 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1786 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1791 set_audio_description( audio, lang_for_code( 0 ) );
1792 hb_list_add( title->list_audio, audio );
1795 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1797 off_t cur_pos = ftello(stream->file_handle);
1798 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1799 hb_list_t *list = hb_list_init();
1800 // how many blocks we read while searching for audio streams
1801 int blksleft = 4096;
1802 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1803 // so we use a bitmap to keep track of the ones we've already seen.
1804 // Bit 'i' of smap is set if we've already added the audio for
1805 // audio substream id 'i' to the title's audio list.
1808 // start looking 20% into the file since there's occasionally no
1809 // audio at the beginning (particularly for vobs).
1810 hb_stream_seek(stream, 0.2f);
1812 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1816 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1817 hb_demux_ps( buf, list, 0 );
1819 while ( ( es = hb_list_item( list, 0 ) ) )
1821 hb_list_rem( list, es );
1822 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1824 // this PES contains some kind of audio - get the substream id
1825 // and check if we've seen it already.
1826 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1827 if ( (smap & (1 << ssid)) == 0 )
1829 // we haven't seen this stream before - add it to the
1830 // title's list of audio streams.
1831 smap |= (1 << ssid);
1832 add_audio_to_title(title, es->id);
1835 hb_buffer_close( &es );
1838 hb_list_empty( &list );
1839 hb_buffer_close(&buf);
1840 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1843 /***********************************************************************
1845 ***********************************************************************
1847 **********************************************************************/
1849 static void hb_ts_stream_init(hb_stream_t *stream)
1853 for (i=0; i < kMaxNumberDecodeStreams; i++)
1855 stream->ts_streamcont[i] = -1;
1856 stream-> ts_pids[i] = -1;
1858 stream->ts_packet = malloc( stream->packetsize );
1860 // Find the audio and video pids in the stream
1861 hb_ts_stream_find_pids(stream);
1863 for (i = 0; i < stream->ts_number_pids; i++)
1865 // demuxing buffer for TS to PS conversion
1866 stream->ts_buf[i] = hb_buffer_init(stream->packetsize);
1867 stream->ts_buf[i]->size = 0;
1871 #define MAX_HOLE 208*80
1873 static off_t align_to_next_packet(hb_stream_t *stream)
1875 uint8_t buf[MAX_HOLE];
1877 off_t start = ftello(stream->file_handle);
1880 if ( start >= stream->packetsize ) {
1881 start -= stream->packetsize;
1882 fseeko(stream->file_handle, start, SEEK_SET);
1888 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1890 const uint8_t *bp = buf;
1893 for ( i = sizeof(buf) - 8 * stream->packetsize; --i >= 0; ++bp )
1895 if ( have_ts_sync( bp, stream->packetsize ) )
1902 pos = ( bp - buf ) - stream->packetsize + 188;
1905 fseeko(stream->file_handle, -8 * stream->packetsize, SEEK_CUR);
1906 start = ftello(stream->file_handle);
1913 fseeko(stream->file_handle, start+pos, SEEK_SET);
1914 return start - orig + pos;
1924 static const unsigned int bitmask[] = {
1925 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1926 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1927 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1928 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1930 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1934 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1935 (bb->buf[2] << 8) | bb->buf[3];
1937 memset(bb->buf, 0, bufsize);
1940 static inline int buf_size(bitbuf_t *bb)
1942 return bb->pos >> 3;
1945 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1948 int left = 32 - (bb->pos & 31);
1952 val = (bb->val >> (left - bits)) & bitmask[bits];
1957 val = (bb->val & bitmask[left]) << (bits - left);
1961 int pos = bb->pos >> 3;
1962 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1966 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1974 // extract what useful information we can from the elementary stream
1975 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1976 // Descriptors with info we don't currently use are ignored.
1977 // The descriptor list & descriptor item formats are defined in
1978 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1979 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1980 const uint8_t *dp, uint8_t dlen)
1982 const uint8_t *ep = dp + dlen;
1988 case 5: // Registration descriptor
1989 stream->ts_format_id[esindx] = (dp[2] << 24) | (dp[3] << 16) |
1990 (dp[4] << 8) | dp[5];
1993 case 10: // ISO_639_language descriptor
1994 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1997 case 0x6a: // DVB AC-3 descriptor
1998 stream->ts_stream_type[esindx] = 0x81;
2001 case 0x7a: // DVB EAC-3 descriptor
2002 stream->ts_stream_type[esindx] = 0x87;
2012 static const char *stream_type_name (uint8_t stream_type)
2014 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
2017 int decode_program_map(hb_stream_t* stream)
2020 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
2022 get_bits(&bb, 8); // table_id
2024 unsigned int section_length = get_bits(&bb, 12);
2025 stream->pmt_info.section_length = section_length;
2027 unsigned int program_number = get_bits(&bb, 16);
2028 stream->pmt_info.program_number = program_number;
2030 get_bits(&bb, 5); // version_number
2032 get_bits(&bb, 8); // section_number
2033 get_bits(&bb, 8); // last_section_number
2035 stream->pmt_info.PCR_PID = get_bits(&bb, 13);
2037 int program_info_length = get_bits(&bb, 12);
2038 stream->pmt_info.program_info_length = program_info_length;
2041 for (i = 0; i < program_info_length - 2; )
2044 tag = get_bits(&bb, 8);
2045 len = get_bits(&bb, 8);
2047 if ( i + len > program_info_length )
2051 if (tag == 0x05 && len >= 4)
2053 // registration descriptor
2054 stream->pmt_info.reg_desc = get_bits(&bb, 32);
2059 for ( j = 0; j < len; j++ )
2065 for ( ; i < program_info_length; i++ )
2070 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
2071 int done_reading_stream_types = 0;
2072 while (!done_reading_stream_types)
2074 unsigned char stream_type = get_bits(&bb, 8);
2076 unsigned int elementary_PID = get_bits(&bb, 13);
2078 unsigned int ES_info_length = get_bits(&bb, 12);
2081 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
2082 for (i=0; i < ES_info_length; i++)
2084 ES_info_buf[i] = get_bits(&bb, 8);
2087 if ( index_of_pid( stream, elementary_PID ) < 0 )
2089 // Defined audio stream types are 0x81 for AC-3/A52 audio
2090 // and 0x03 for mpeg audio. But content producers seem to
2091 // use other values (0x04 and 0x06 have both been observed)
2092 // so at this point we say everything that isn't a video
2093 // pid is audio then at the end of hb_stream_title_scan
2094 // we'll figure out which are really audio by looking at
2096 i = stream->ts_number_pids;
2097 if (i < kMaxNumberDecodeStreams)
2099 stream->ts_pids[i] = elementary_PID;
2100 stream->ts_stream_type[i] = stream_type;
2101 if (ES_info_length > 0)
2103 decode_element_descriptors(stream, i, ES_info_buf,
2106 stream->ts_stream_kind[i] = ts_stream_kind(stream, i);
2107 ++stream->ts_number_pids;
2111 cur_pos += 5 /* stream header */ + ES_info_length;
2115 if (cur_pos >= section_length - 4 /* stop before the CRC */)
2116 done_reading_stream_types = 1;
2122 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
2124 // Get adaption header info
2126 int adaption = (buf[3] & 0x30) >> 4;
2129 else if (adaption == 0x2)
2131 else if (adaption == 0x3)
2132 adapt_len = buf[4] + 1;
2133 if (adapt_len > 184)
2136 // Get payload start indicator
2138 start = (buf[1] & 0x40) != 0;
2140 // Get pointer length - only valid in packets with a start flag
2141 int pointer_len = 0;
2145 pointer_len = buf[4 + adapt_len] + 1;
2146 stream->pmt_info.tablepos = 0;
2148 // Get Continuity Counter
2149 int continuity_counter = buf[3] & 0x0f;
2150 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
2152 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
2155 stream->pmt_info.current_continuity_counter = continuity_counter;
2156 stream->pmt_info.reading |= start;
2158 // Add the payload for this packet to the current buffer
2159 int amount_to_copy = 184 - adapt_len - pointer_len;
2160 if (stream->pmt_info.reading && (amount_to_copy > 0))
2162 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
2164 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
2165 stream->pmt_info.tablepos += amount_to_copy;
2167 if (stream->pmt_info.tablepos > 3)
2169 // We have enough to check the section length
2171 length = ((stream->pmt_info.tablebuf[1] << 8) +
2172 stream->pmt_info.tablebuf[2]) & 0xFFF;
2173 if (stream->pmt_info.tablepos > length + 1)
2175 // We just finished a bunch of packets - parse the program map details
2177 if (stream->pmt_info.tablebuf[0] == 0x02)
2178 decode_ok = decode_program_map(stream);
2179 free(stream->pmt_info.tablebuf);
2180 stream->pmt_info.tablebuf = NULL;
2181 stream->pmt_info.tablepos = 0;
2182 stream->pmt_info.reading = 0;
2192 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
2194 unsigned char tablebuf[1024];
2195 unsigned int tablepos = 0;
2200 // Get adaption header info
2202 int adaption = (buf[3] & 0x30) >> 4;
2205 else if (adaption == 0x2)
2207 else if (adaption == 0x3)
2208 adapt_len = buf[4] + 1;
2209 if (adapt_len > 184)
2212 // Get pointer length
2213 int pointer_len = buf[4 + adapt_len] + 1;
2215 // Get payload start indicator
2217 start = (buf[1] & 0x40) != 0;
2222 // Add the payload for this packet to the current buffer
2223 if (reading && (184 - adapt_len) > 0)
2225 if (tablepos + 184 - adapt_len - pointer_len > 1024)
2227 hb_log("decode_PAT - Bad program section length (> 1024)");
2230 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
2231 tablepos += 184 - adapt_len - pointer_len;
2234 if (start && reading)
2236 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
2239 unsigned int pos = 0;
2240 //while (pos < tablepos)
2243 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
2245 unsigned char section_id = get_bits(&bb, 8);
2247 unsigned int section_len = get_bits(&bb, 12);
2248 get_bits(&bb, 16); // transport_id
2250 get_bits(&bb, 5); // version_num
2251 get_bits(&bb, 1); // current_next
2252 get_bits(&bb, 8); // section_num
2253 get_bits(&bb, 8); // last_section
2259 // Program Association Section
2260 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
2261 section_len -= 4; // Ignore the CRC
2263 stream->ts_number_pat_entries = 0;
2264 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
2266 unsigned int pkt_program_num = get_bits(&bb, 16);
2267 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
2269 get_bits(&bb, 3); // Reserved
2270 if (pkt_program_num == 0)
2272 get_bits(&bb, 13); // pkt_network_id
2276 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
2277 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
2280 stream->ts_number_pat_entries++;
2294 pos += 3 + section_len;
2302 static void hb_ts_stream_find_pids(hb_stream_t *stream)
2304 // To be different from every other broadcaster in the world, New Zealand TV
2305 // changes PMTs (and thus video & audio PIDs) when 'programs' change. Since
2306 // we may have the tail of the previous program at the beginning of this
2307 // file, take our PMT from the middle of the file.
2308 fseeko(stream->file_handle, 0, SEEK_END);
2309 uint64_t fsize = ftello(stream->file_handle);
2310 fseeko(stream->file_handle, fsize >> 1, SEEK_SET);
2311 align_to_next_packet(stream);
2313 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
2314 // to find the program map PID and then decode that to get the list of audio and video PIDs
2318 const uint8_t *buf = next_packet( stream );
2322 hb_log("hb_ts_stream_find_pids - end of file");
2327 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
2329 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
2331 decode_PAT(buf, stream);
2336 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
2338 // There are some streams where the PAT table has multiple entries as if their are
2339 // multiple programs in the same transport stream, and yet there's actually only one
2340 // program really in the stream. This seems to be true for transport streams that
2341 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
2342 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
2343 // but the EyeTV is only recording a single (selected) program number and not rewriting the
2344 // PAT info on export to match what's actually on the stream.
2345 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
2346 // on the first pat entry for which we find a matching program map PID. The ideal solution would
2347 // be to build a title choice popup from the PAT program number details and then select from
2348 // their - but right now the API's not capable of that.
2349 if (stream->pat_info[pat_index].program_number != 0 &&
2350 pid == stream->pat_info[pat_index].program_map_PID)
2352 if (build_program_map(buf, stream) > 0)
2356 // Keep going until we have a complete set of PIDs
2357 if ( index_of_video( stream ) >= 0 )
2361 hb_log("hb_ts_stream_find_pids - found the following PIDS");
2362 hb_log(" Video PIDS : ");
2364 for (i=0; i < stream->ts_number_pids; i++)
2366 if ( stream->ts_stream_kind[i] == V )
2368 hb_log( " 0x%x type %s (0x%x)",
2370 stream_type_name(stream->ts_stream_type[i]),
2371 stream->ts_stream_type[i]);
2374 hb_log(" Audio PIDS : ");
2375 for (i = 0; i < stream->ts_number_pids; i++)
2377 if ( stream->ts_stream_kind[i] != V )
2379 hb_log( " 0x%x type %s (0x%x)",
2381 stream_type_name(stream->ts_stream_type[i]),
2382 stream->ts_stream_type[i] );
2388 static void fwrite64( hb_stream_t *stream, void *buf, int len )
2392 int pos = stream->fwrite_buf->size;
2393 if ( pos + len > stream->fwrite_buf->alloc )
2395 int size = MAX(stream->fwrite_buf->alloc * 2, pos + len);
2396 hb_buffer_realloc(stream->fwrite_buf, size);
2398 memcpy( &(stream->fwrite_buf->data[pos]), buf, len );
2399 stream->fwrite_buf->size += len;
2403 // convert a PES PTS or DTS to an int64
2404 static int64_t pes_timestamp( const uint8_t *pes )
2406 int64_t ts = ( (uint64_t)(pes[0] & 0xe ) << 29 );
2407 ts |= ( pes[1] << 22 ) | ( ( pes[2] >> 1 ) << 15 ) |
2408 ( pes[3] << 7 ) | ( pes[4] >> 1 );
2412 static void generate_output_data(hb_stream_t *stream, int curstream)
2414 hb_buffer_t *buf = stream->fwrite_buf;
2415 uint8_t *tdat = stream->ts_buf[curstream]->data;
2417 buf->id = stream->ts_pids[curstream];
2418 switch (stream->ts_stream_kind[curstream])
2421 buf->type = AUDIO_BUF;
2425 buf->type = VIDEO_BUF;
2429 buf->type = OTHER_BUF;
2433 // check if this packet was referenced to an older pcr and if that
2434 // pcr was significantly different than the one we're using now.
2435 // (the reason for the uint cast on the pcr difference is that the
2436 // difference is significant if it advanced by more than 200ms or if
2437 // it went backwards by any amount. The negative numbers look like huge
2438 // unsigned ints so the cast allows both conditions to be checked at once.
2439 int bufpcr = stream->ts_buf[curstream]->cur;
2440 int curpcr = stream->ts_pcr_out;
2441 if ( bufpcr && bufpcr < curpcr &&
2442 (uint64_t)(stream->ts_pcrhist[curpcr & 3] - stream->ts_pcrhist[bufpcr & 3]) > 200*90LL )
2444 // we've sent up a new pcr but have a packet referenced to an
2445 // old pcr and the difference was enough to trigger a discontinuity
2446 // correction. smash the timestamps or we'll mess up the correction.
2448 buf->renderOffset = -1;
2452 if ( stream->ts_pcr_out != stream->ts_pcr_in )
2454 // we have a new pcr
2455 stream->ts_pcr_out = stream->ts_pcr_in;
2456 buf->stop = stream->ts_pcr;
2457 stream->ts_pcrhist[stream->ts_pcr_out & 3] = stream->ts_pcr;
2464 // put the PTS & possible DTS into 'start' & 'renderOffset' then strip
2465 // off the PES header.
2466 if ( tdat[7] & 0xc0 )
2468 buf->start = pes_timestamp( tdat + 9 );
2469 buf->renderOffset = ( tdat[7] & 0x40 )? pes_timestamp( tdat + 14 ) :
2475 buf->renderOffset = -1;
2478 int hlen = tdat[8] + 9;
2480 fwrite64( stream, tdat + hlen, stream->ts_pos[curstream] - hlen );
2482 stream->ts_pos[curstream] = 0;
2483 stream->ts_buf[curstream]->size = 0;
2486 static void hb_ts_stream_append_pkt(hb_stream_t *stream, int idx, const uint8_t *buf, int len)
2488 if (stream->ts_pos[idx] + len > stream->ts_buf[idx]->alloc)
2492 size = MAX(stream->ts_buf[idx]->alloc * 2, stream->ts_pos[idx] + len);
2493 hb_buffer_realloc(stream->ts_buf[idx], size);
2495 memcpy(stream->ts_buf[idx]->data + stream->ts_pos[idx], buf, len);
2496 stream->ts_pos[idx] += len;
2497 stream->ts_buf[idx]->size += len;
2500 /***********************************************************************
2501 * hb_ts_stream_decode
2502 ***********************************************************************
2504 **********************************************************************/
2505 int hb_ts_decode_pkt( hb_stream_t *stream, const uint8_t * pkt, hb_buffer_t *obuf )
2508 * stash the output buffer pointer in our stream so we don't have to
2509 * pass it & its original value to everything we call.
2512 stream->fwrite_buf = obuf;
2514 int video_index = index_of_video(stream);
2518 /* This next section validates the packet */
2520 // Get pid and use it to find stream state.
2521 int pid = ((pkt[1] & 0x1F) << 8) | pkt[2];
2522 if ( ( curstream = index_of_pid( stream, pid ) ) < 0 )
2528 int errorbit = (pkt[1] & 0x80) != 0;
2531 ts_err( stream, curstream, "packet error bit set");
2535 // Get adaption header info
2536 int adaption = (pkt[3] & 0x30) >> 4;
2540 ts_err( stream, curstream, "adaptation code 0");
2543 else if (adaption == 0x2)
2545 else if (adaption == 0x3)
2547 adapt_len = pkt[4] + 1;
2548 if (adapt_len > 184)
2550 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2555 if ( adapt_len > 0 )
2557 if ( pkt[5] & 0x40 )
2559 // found a random access point
2561 // if there's an adaptation header & PCR_flag is set
2562 // get the PCR (Program Clock Reference)
2563 if ( adapt_len > 7 && ( pkt[5] & 0x10 ) != 0 )
2565 stream->ts_pcr = ( (uint64_t)pkt[6] << (33 - 8) ) |
2566 ( (uint64_t)pkt[7] << (33 - 16) ) |
2567 ( (uint64_t)pkt[8] << (33 - 24) ) |
2568 ( (uint64_t)pkt[9] << (33 - 32) ) |
2570 ++stream->ts_pcr_in;
2571 stream->ts_found_pcr = 1;
2572 stream->ts_flags |= TS_HAS_PCR;
2576 // If we don't have a PCR yet but the stream has PCRs just loop
2577 // so we don't process anything until we have a clock reference.
2578 // Unfortunately the HD Home Run appears to null out the PCR so if
2579 // we didn't detect a PCR during scan keep going and we'll use
2580 // the video stream DTS for the PCR.
2582 if ( !stream->ts_found_pcr && ( stream->ts_flags & TS_HAS_PCR ) )
2588 // Continuity only increments for adaption values of 0x3 or 0x01
2589 // and is not checked for start packets.
2591 int start = (pkt[1] & 0x40) != 0;
2593 if ( (adaption & 0x01) != 0 )
2595 int continuity = (pkt[3] & 0xF);
2596 if ( continuity == stream->ts_streamcont[curstream] )
2598 // Spliced transport streams can have duplicate
2599 // continuity counts at the splice boundary.
2600 // Test to see if the packet is really a duplicate
2601 // by comparing packet summaries to see if they
2605 summary[0] = adaption;
2606 summary[1] = adapt_len;
2607 if (adapt_len + 4 + 6 + 9 <= 188)
2609 memcpy(&summary[2], pkt+4+adapt_len+9, 6);
2613 memset(&summary[2], 0, 6);
2615 if ( memcmp( summary, stream->ts_pkt_summary[curstream], 8 ) == 0 )
2617 // we got a duplicate packet (usually used to introduce
2618 // a PCR when one is needed). The only thing that can
2619 // change in the dup is the PCR which we grabbed above
2620 // so ignore the rest.
2624 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2625 !stream->ts_skipbad[curstream] &&
2626 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2628 ts_err( stream, curstream, "continuity error: got %d expected %d",
2630 (stream->ts_streamcont[curstream] + 1) & 0xf );
2631 stream->ts_streamcont[curstream] = continuity;
2634 stream->ts_streamcont[curstream] = continuity;
2636 // Save a summary of this packet for later duplicate
2637 // testing. The summary includes some header information
2638 // and payload bytes. Should be enough to detect
2640 stream->ts_pkt_summary[curstream][0] = adaption;
2641 stream->ts_pkt_summary[curstream][1] = adapt_len;
2642 if (adapt_len + 4 + 6 + 9 <= 188)
2644 memcpy(&stream->ts_pkt_summary[curstream][2],
2645 pkt+4+adapt_len+9, 6);
2649 memset(&stream->ts_pkt_summary[curstream][2], 0, 6);
2653 /* If we get here the packet is valid - process its data */
2657 // Found a random access point (now we can start a frame/audio packet..)
2659 if ( stream->need_keyframe )
2661 // we're looking for the first video frame because we're
2662 // doing random access during 'scan'
2663 if ( curstream != video_index || !isIframe( stream, pkt, adapt_len ) )
2665 // not the video stream or didn't find an I frame
2666 // but we'll only wait 255 video frames for an I frame.
2667 if ( curstream != video_index || ++stream->need_keyframe )
2672 stream->need_keyframe = 0;
2675 // If we were skipping a bad packet, start fresh on this new PES packet..
2676 if (stream->ts_skipbad[curstream] == 1)
2678 stream->ts_skipbad[curstream] = 0;
2681 if ( curstream == video_index )
2685 // if we don't have a pcr yet use the dts from this frame
2686 if ( !stream->ts_found_pcr )
2688 // PES must begin with an mpeg start code & contain
2690 const uint8_t *pes = pkt + adapt_len + 4;
2691 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2692 ( pes[7] >> 6 ) == 0 )
2696 // if we have a dts use it otherwise use the pts
2697 stream->ts_pcr = pes_timestamp( pes + ( pes[7] & 0x40?14:9 ) );
2698 ++stream->ts_pcr_in;
2702 // if this is a multiplexed stream make sure this is the
2703 // substream we want.
2704 if ( stream->ts_multiplexed[curstream] )
2706 // PES must begin with an mpeg start code & contain
2708 const uint8_t *pes = pkt + adapt_len + 4;
2709 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2712 stream->ts_skipbad[curstream] = 1;
2715 // the last byte of the header is the extension id. see if
2716 // it's the one we want.
2717 if ( pes[pes[8]+8] != stream->ts_multiplexed[curstream] )
2719 stream->ts_skipbad[curstream] = 1;
2724 // If we have some data already on this stream, turn it into
2725 // a program stream packet. Then add the payload for this
2726 // packet to the current pid's buffer.
2727 if ( stream->ts_pos[curstream] )
2729 // we have to ship the old packet before updating the pcr
2730 // since the packet we've been accumulating is referenced
2732 generate_output_data(stream, curstream);
2734 // remember the pcr that was in effect when we started
2736 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2737 hb_ts_stream_append_pkt(stream, curstream, pkt + 4 + adapt_len,
2741 // remember the pcr that was in effect when we started this packet.
2742 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2745 // Add the payload for this packet to the current buffer
2746 if (!stream->ts_skipbad[curstream] && (184 - adapt_len) > 0)
2748 hb_ts_stream_append_pkt(stream, curstream, pkt + 4 + adapt_len,
2750 // see if we've hit the end of this PES packet
2751 const uint8_t *pes = stream->ts_buf[curstream]->data;
2752 int len = ( pes[4] << 8 ) + pes[5] + 6;
2753 if ( len > 6 && stream->ts_pos[curstream] == len &&
2754 pes[0] == 0x00 && pes[1] == 0x00 && pes[2] == 0x01 )
2756 generate_output_data(stream, curstream);
2763 static int hb_ts_stream_decode( hb_stream_t *stream, hb_buffer_t *obuf )
2765 // spin until we get a packet of data from some stream or hit eof
2768 const uint8_t *buf = next_packet(stream);
2771 // end of file - we didn't finish filling our ps write buffer
2772 // so just discard the remainder (the partial buffer is useless)
2773 hb_log("hb_ts_stream_decode - eof");
2777 if (hb_ts_decode_pkt( stream, buf, obuf ))
2785 static void hb_ts_stream_reset(hb_stream_t *stream)
2789 for (i=0; i < kMaxNumberDecodeStreams; i++)
2791 stream->ts_pos[i] = 0;
2792 stream->ts_skipbad[i] = 1;
2793 stream->ts_streamcont[i] = -1;
2796 stream->need_keyframe = 0;
2798 stream->ts_found_pcr = 0;
2799 stream->ts_pcr_out = 0;
2800 stream->ts_pcr_in = 0;
2805 stream->last_error_frame = -10000;
2806 stream->last_error_count = 0;
2808 align_to_next_packet(stream);
2811 // ------------------------------------------------------------------
2812 // Support for reading media files via the ffmpeg libraries.
2814 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2816 // add a codec to the context here so it will be there when we
2817 // read the first packet.
2818 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2819 context->workaround_bugs = FF_BUG_AUTODETECT;
2820 context->error_recognition = 1;
2821 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2822 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2823 hb_avcodec_open( context, codec );
2826 // The ffmpeg stream reader / parser shares a lot of state with the
2827 // decoder via a codec context kept in the AVStream of the reader's
2828 // AVFormatContext. Since decoding is done in a different thread we
2829 // have to somehow pass this codec context to the decoder and we have
2830 // to do it before the first packet is read (so we can't put the info
2831 // in the buf we'll send downstream). Decoders don't have any way to
2832 // get to the stream directly (they're not passed the title or job
2833 // pointers during a scan) so this is a back door for the decoder to
2834 // get the codec context. We just stick the stream pointer in the next
2835 // slot an array of pointers maintained as a circular list then return
2836 // the index into the list combined with the ffmpeg stream index as the
2837 // codec_param that will be passed to the decoder init routine. We make
2838 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2839 // so that we don't have to do a complicated allocator or worry about
2840 // deleting entries on close.
2842 // Entries can only be added to this list during a scan and are never
2843 // deleted so the list access doesn't require locking.
2844 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2845 static int ffmpeg_stream_cur; // where we put the last stream pointer
2846 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2847 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2849 // add a stream to the list & return the appropriate codec_param to access it
2850 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2852 if ( !ffmpeg_streams )
2854 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2857 // the title scan adds all the ffmpeg media streams at once so we
2858 // only add a new entry to our stream list if the stream is different
2860 int slot = ffmpeg_stream_cur;
2861 if ( ffmpeg_streams[slot] != stream )
2863 // new stream - put it in the next slot of the stream list
2864 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2865 ffmpeg_streams[slot] = stream;
2868 ffmpeg_add_codec( stream, stream_index );
2870 return ( stream_index << ffmpeg_sl_bits ) | slot;
2873 // we're about to open 'title' to convert it - remap the stream associated
2874 // with the video & audio codec params of the title to refer to 'stream'
2875 // (the original scan stream was closed and no longer exists).
2876 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2878 // all the video & audio came from the same stream so remapping
2879 // the video's stream slot takes care of everything.
2880 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2881 ffmpeg_streams[slot] = stream;
2883 // add codecs for all the streams used by the title
2884 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2888 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2890 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2892 ffmpeg_add_codec( stream,
2893 audio->config.in.codec_param >> ffmpeg_sl_bits );
2898 void *hb_ffmpeg_context( int codec_param )
2900 if ( ffmpeg_streams == NULL )
2903 int slot = codec_param & (ffmpeg_sl_size - 1);
2904 int stream_index = codec_param >> ffmpeg_sl_bits;
2905 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2908 void *hb_ffmpeg_avstream( int codec_param )
2910 if ( ffmpeg_streams == NULL )
2913 int slot = codec_param & (ffmpeg_sl_size - 1);
2914 int stream_index = codec_param >> ffmpeg_sl_bits;
2915 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2918 static AVFormatContext *ffmpeg_deferred_close;
2920 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2922 if ( ffmpeg_deferred_close )
2924 av_close_input_file( ffmpeg_deferred_close );
2925 ffmpeg_deferred_close = NULL;
2927 AVFormatContext *ic;
2929 av_log_set_level( AV_LOG_ERROR );
2930 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2934 if ( hb_av_find_stream_info( ic ) < 0 )
2937 stream->ffmpeg_ic = ic;
2938 stream->hb_stream_type = ffmpeg;
2939 stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2940 av_init_packet( stream->ffmpeg_pkt );
2941 stream->chapter_end = INT64_MAX;
2945 // we're opening for read. scan passed out codec params that
2946 // indexed its stream so we need to remap them so they point
2948 ffmpeg_remap_stream( stream, title );
2949 av_log_set_level( AV_LOG_ERROR );
2953 // we're opening for scan. let ffmpeg put some info into the
2954 // log about what we've got.
2955 av_log_set_level( AV_LOG_INFO );
2956 dump_format( ic, 0, stream->path, 0 );
2957 av_log_set_level( AV_LOG_ERROR );
2959 // accept this file if it has at least one video stream we can decode
2961 for (i = 0; i < ic->nb_streams; ++i )
2963 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2968 if ( i >= ic->nb_streams )
2974 av_close_input_file( ic );
2978 static void ffmpeg_close( hb_stream_t *d )
2980 // XXX since we're sharing the CodecContext with the downstream
2981 // decoder proc we can't close the stream. We need to reference count
2982 // this so we can close it when both are done with their instance but
2983 // for now just defer the close until the next stream open or close.
2984 if ( ffmpeg_deferred_close )
2986 av_close_input_file( ffmpeg_deferred_close );
2988 ffmpeg_deferred_close = d->ffmpeg_ic;
2989 if ( d->ffmpeg_pkt != NULL )
2991 free( d->ffmpeg_pkt );
2992 d->ffmpeg_pkt = NULL;
2996 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2998 AVStream *st = stream->ffmpeg_ic->streams[id];
2999 AVCodecContext *codec = st->codec;
3002 // scan will ignore any audio without a bitrate. Since we've already
3003 // typed the audio in order to determine its codec we set up the audio
3005 layout = hb_ff_layout_xlat( codec->channel_layout, codec->channels );
3008 // Unsupported layout
3011 if ( codec->bit_rate || codec->sample_rate )
3013 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
3016 if ( codec->codec_id == CODEC_ID_AC3 )
3018 audio->config.in.codec = HB_ACODEC_AC3;
3020 else if ( codec->codec_id == CODEC_ID_DTS )
3022 audio->config.in.codec = HB_ACODEC_DCA;
3026 audio->config.in.codec = HB_ACODEC_FFMPEG;
3027 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
3029 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
3030 audio->config.in.samplerate = codec->sample_rate;
3031 audio->config.in.channel_layout = layout;
3034 set_audio_description( audio, lang_for_code2( st->language ) );
3036 hb_list_add( title->list_audio, audio );
3042 * MkvVobSubtitlePrivateData = ( Line )*
3043 * Line = FieldName ':' ' ' FieldValue '\n'
3045 * FieldValue = [^\n]+
3047 * The line of interest is:
3048 * PaletteLine = "palette" ':' ' ' RRGGBB ( ',' ' ' RRGGBB )*
3050 * More information on the format at:
3051 * http://www.matroska.org/technical/specs/subtitles/images.html
3053 static int ffmpeg_parse_vobsub_extradata_mkv( AVCodecContext *codec, hb_subtitle_t *subtitle )
3055 // lines = (string) codec->extradata;
3056 char *lines = malloc( codec->extradata_size + 1 );
3057 if ( lines == NULL )
3059 memcpy( lines, codec->extradata, codec->extradata_size );
3060 lines[codec->extradata_size] = '\0';
3064 int gotDimensions = 0;
3066 char *curLine, *curLine_parserData;
3067 for ( curLine = strtok_r( lines, "\n", &curLine_parserData );
3069 curLine = strtok_r( NULL, "\n", &curLine_parserData ) )
3073 int numElementsRead = sscanf(curLine, "palette: "
3074 "%06x, %06x, %06x, %06x, "
3075 "%06x, %06x, %06x, %06x, "
3076 "%06x, %06x, %06x, %06x, "
3077 "%06x, %06x, %06x, %06x",
3078 &rgb[0], &rgb[1], &rgb[2], &rgb[3],
3079 &rgb[4], &rgb[5], &rgb[6], &rgb[7],
3080 &rgb[8], &rgb[9], &rgb[10], &rgb[11],
3081 &rgb[12], &rgb[13], &rgb[14], &rgb[15]);
3083 if (numElementsRead == 16) {
3089 int numElementsRead = sscanf(curLine, "size: %dx%d",
3090 &subtitle->width, &subtitle->height);
3092 if (numElementsRead == 2) {
3096 if (gotPalette && gotDimensions)
3100 if (subtitle->width == 0 || subtitle->height == 0)
3102 subtitle->width = 720;
3103 subtitle->height = 480;
3111 for (i=0; i<16; i++)
3112 subtitle->palette[i] = hb_rgb2yuv(rgb[i]);
3122 * Format: 8-bit {0,Y,Cb,Cr} x 16
3124 static int ffmpeg_parse_vobsub_extradata_mp4( AVCodecContext *codec, hb_subtitle_t *subtitle )
3126 if ( codec->extradata_size != 4*16 )
3130 for ( i=0, j=0; i<16; i++, j+=4 )
3132 subtitle->palette[i] =
3133 codec->extradata[j+1] << 16 | // Y
3134 codec->extradata[j+2] << 8 | // Cb
3135 codec->extradata[j+3] << 0; // Cr
3137 if (codec->width <= 0 || codec->height <= 0)
3139 subtitle->width = 720;
3140 subtitle->height = 480;
3144 subtitle->width = codec->width;
3145 subtitle->height = codec->height;
3151 * Parses the 'subtitle->palette' information from the specific VOB subtitle track's private data.
3152 * Returns 0 if successful or 1 if parsing failed or was incomplete.
3154 static int ffmpeg_parse_vobsub_extradata( AVCodecContext *codec, hb_subtitle_t *subtitle )
3156 // XXX: Better if we actually chose the correct parser based on the input container
3158 ffmpeg_parse_vobsub_extradata_mkv( codec, subtitle ) &&
3159 ffmpeg_parse_vobsub_extradata_mp4( codec, subtitle );
3162 static void add_ffmpeg_subtitle( hb_title_t *title, hb_stream_t *stream, int id )
3164 AVStream *st = stream->ffmpeg_ic->streams[id];
3165 AVCodecContext *codec = st->codec;
3167 hb_subtitle_t *subtitle = calloc( 1, sizeof(*subtitle) );
3171 switch ( codec->codec_id )
3173 case CODEC_ID_DVD_SUBTITLE:
3174 subtitle->format = PICTURESUB;
3175 subtitle->source = VOBSUB;
3176 subtitle->config.dest = RENDERSUB; // By default render (burn-in) the VOBSUB.
3177 if ( ffmpeg_parse_vobsub_extradata( codec, subtitle ) )
3178 hb_log( "add_ffmpeg_subtitle: malformed extradata for VOB subtitle track; "
3179 "subtitle colors likely to be wrong" );
3182 subtitle->format = TEXTSUB;
3183 subtitle->source = UTF8SUB;
3184 subtitle->config.dest = PASSTHRUSUB;
3186 case CODEC_ID_MOV_TEXT: // TX3G
3187 subtitle->format = TEXTSUB;
3188 subtitle->source = TX3GSUB;
3189 subtitle->config.dest = PASSTHRUSUB;
3192 subtitle->format = TEXTSUB;
3193 subtitle->source = SSASUB;
3194 subtitle->config.dest = PASSTHRUSUB;
3197 hb_log( "add_ffmpeg_subtitle: unknown subtitle stream type: 0x%x", (int) codec->codec_id );
3202 iso639_lang_t *language = lang_for_code2( st->language );
3203 strcpy( subtitle->lang, language->eng_name );
3204 strncpy( subtitle->iso639_2, language->iso639_2, 4 );
3206 // Copy the extradata for the subtitle track
3207 subtitle->extradata = malloc( codec->extradata_size );
3208 memcpy( subtitle->extradata, codec->extradata, codec->extradata_size );
3209 subtitle->extradata_size = codec->extradata_size;
3211 hb_list_add(title->list_subtitle, subtitle);
3214 static char *get_ffmpeg_metadata_value( AVMetadata *m, char *key )
3216 AVMetadataTag *tag = NULL;
3217 while ( (tag = av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX)) )
3219 if ( !strcmp( key, tag->key ) )
3227 static void add_ffmpeg_attachment( hb_title_t *title, hb_stream_t *stream, int id )
3229 AVStream *st = stream->ffmpeg_ic->streams[id];
3230 AVCodecContext *codec = st->codec;
3232 enum attachtype type;
3233 switch ( codec->codec_id )
3236 type = FONT_TTF_ATTACH;
3239 // Ignore unrecognized attachment type
3243 hb_attachment_t *attachment = calloc( 1, sizeof(*attachment) );
3245 // Copy the attachment name and data
3246 attachment->type = type;
3247 attachment->name = strdup( get_ffmpeg_metadata_value( st->metadata, "filename" ) );
3248 attachment->data = malloc( codec->extradata_size );
3249 memcpy( attachment->data, codec->extradata, codec->extradata_size );
3250 attachment->size = codec->extradata_size;
3252 hb_list_add(title->list_attachment, attachment);
3255 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
3257 AVFormatContext *ic = stream->ffmpeg_ic;
3259 // 'Barebones Title'
3260 hb_title_t *title = hb_title_init( stream->path, 0 );
3261 title->type = HB_STREAM_TYPE;
3264 // Copy part of the stream path to the title name
3265 char *sep = strrchr(stream->path, '/');
3267 strcpy(title->name, sep+1);
3268 char *dot_term = strrchr(title->name, '.');
3272 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
3273 title->duration = dur;
3275 title->hours = dur / 3600;
3276 title->minutes = ( dur % 3600 ) / 60;
3277 title->seconds = dur % 60;
3279 // set the title to decode the first video stream in the file
3280 title->demuxer = HB_NULL_DEMUXER;
3281 title->video_codec = 0;
3283 for (i = 0; i < ic->nb_streams; ++i )
3285 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
3286 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
3287 title->video_codec == 0 )
3289 AVCodecContext *context = ic->streams[i]->codec;
3290 if ( context->pix_fmt != PIX_FMT_YUV420P &&
3291 !sws_isSupportedInput( context->pix_fmt ) )
3293 hb_log( "ffmpeg_title_scan: Unsupported color space" );
3296 title->video_id = i;
3297 stream->ffmpeg_video_id = i;
3299 // We have to use the 'internal' avcodec decoder because
3300 // it needs to share the codec context from this video
3301 // stream. The parser internal to av_read_frame
3302 // passes a bunch of state info to the decoder via the context.
3303 title->video_codec = WORK_DECAVCODECVI;
3304 title->video_codec_param = ffmpeg_codec_param( stream, i );
3306 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
3307 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
3309 add_ffmpeg_audio( title, stream, i );
3311 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_SUBTITLE )
3313 add_ffmpeg_subtitle( title, stream, i );
3315 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_ATTACHMENT )
3317 add_ffmpeg_attachment( title, stream, i );
3321 title->container_name = strdup( ic->iformat->name );
3322 title->data_rate = ic->bit_rate;
3324 hb_deep_log( 2, "Found ffmpeg %d chapters, container=%s", ic->nb_chapters, ic->iformat->name );
3326 if( ic->nb_chapters != 0 )
3329 uint64_t duration_sum = 0;
3330 for( i = 0; i < ic->nb_chapters; i++ )
3331 if( ( m = ic->chapters[i] ) != NULL )
3333 hb_chapter_t * chapter;
3334 chapter = calloc( sizeof( hb_chapter_t ), 1 );
3335 chapter->index = i+1;
3336 chapter->duration = ( m->end / ( (double) m->time_base.num * m->time_base.den ) ) * 90000 - duration_sum;
3337 duration_sum += chapter->duration;
3338 chapter->hours = chapter->duration / 90000 / 3600;
3339 chapter->minutes = ( ( chapter->duration / 90000 ) % 3600 ) / 60;
3340 chapter->seconds = ( chapter->duration / 90000 ) % 60;
3341 strcpy( chapter->title, m->title );
3342 hb_deep_log( 2, "Added chapter %i, name='%s', dur=%"PRIu64", (%02i:%02i:%02i)",
3343 chapter->index, chapter->title,
3344 chapter->duration, chapter->hours,
3345 chapter->minutes, chapter->seconds );
3346 hb_list_add( title->list_chapter, chapter );
3351 * Fill the metadata.
3353 decmetadata( title );
3355 if( hb_list_count( title->list_chapter ) == 0 )
3357 // Need at least one chapter
3358 hb_chapter_t * chapter;
3359 chapter = calloc( sizeof( hb_chapter_t ), 1 );
3361 chapter->duration = title->duration;
3362 chapter->hours = title->hours;
3363 chapter->minutes = title->minutes;
3364 chapter->seconds = title->seconds;
3365 hb_list_add( title->list_chapter, chapter );
3371 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
3373 if ( pts == AV_NOPTS_VALUE )
3375 return (int64_t)( (double)pts * conv_factor );
3378 static int ffmpeg_is_keyframe( hb_stream_t *stream )
3382 switch ( stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->codec_id )
3385 // XXX the VC1 codec doesn't mark key frames so to get previews
3386 // we do it ourselves here. The decoder gets messed up if it
3387 // doesn't get a SEQ header first so we consider that to be a key frame.
3388 pkt = stream->ffmpeg_pkt->data;
3389 if ( !pkt[0] && !pkt[1] && pkt[2] == 1 && pkt[3] == 0x0f )
3395 // XXX the ffmpeg WMV3 codec doesn't mark key frames.
3396 // Only M$ could make I-frame detection this complicated: there
3397 // are two to four bits of unused junk ahead of the frame type
3398 // so we have to look at the sequence header to find out how much
3399 // to skip. Then there are three different ways of coding the type
3400 // depending on whether it's main or advanced profile then whether
3401 // there are bframes or not so we have to look at the sequence
3402 // header to get that.
3403 pkt = stream->ffmpeg_pkt->data;
3404 uint8_t *seqhdr = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->extradata;
3406 if ( ( seqhdr[3] & 0x02 ) == 0 )
3409 if ( ( seqhdr[3] & 0x80 ) == 0 )
3410 // no RANGEREDUCTION
3412 if ( seqhdr[3] & 0x70 )
3413 // stream has b-frames
3414 return ( ( pkt[0] >> pshift ) & 0x3 ) == 0x01;
3416 return ( ( pkt[0] >> pshift ) & 0x2 ) == 0;
3421 return ( stream->ffmpeg_pkt->flags & PKT_FLAG_KEY );
3424 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
3428 if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
3430 // XXX the following conditional is to handle avi files that
3431 // use M$ 'packed b-frames' and occasionally have negative
3432 // sizes for the null frames these require.
3433 if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
3437 if ( stream->ffmpeg_pkt->size <= 0 )
3439 // M$ "invalid and inefficient" packed b-frames require 'null frames'
3440 // following them to preserve the timing (since the packing puts two
3441 // or more frames in what looks like one avi frame). The contents and
3442 // size of these null frames are ignored by the ff_h263_decode_frame
3443 // as long as they're < 20 bytes. We need a positive size so we use
3444 // one byte if we're given a zero or negative size. We don't know
3445 // if the pkt data points anywhere reasonable so we just stick a
3446 // byte of zero in our outbound buf.
3452 if ( stream->ffmpeg_pkt->size > buf->alloc )
3454 // sometimes we get absurd sizes from ffmpeg
3455 if ( stream->ffmpeg_pkt->size >= (1 << 25) )
3457 hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
3458 av_free_packet( stream->ffmpeg_pkt );
3459 return ffmpeg_read( stream, buf );
3461 // need to expand buffer
3462 hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
3464 memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
3465 buf->size = stream->ffmpeg_pkt->size;
3467 buf->id = stream->ffmpeg_pkt->stream_index;
3468 if ( buf->id == stream->ffmpeg_video_id )
3470 if ( stream->need_keyframe )
3472 // we've just done a seek (generally for scan or live preview) and
3473 // want to start at a keyframe. Some ffmpeg codecs seek to a key
3474 // frame but most don't. So we spin until we either get a keyframe
3475 // or we've looked through 50 video frames without finding one.
3476 if ( ! ffmpeg_is_keyframe( stream ) && ++stream->need_keyframe < 50 )
3478 av_free_packet( stream->ffmpeg_pkt );
3481 stream->need_keyframe = 0;
3486 // if we haven't done it already, compute a conversion factor to go
3487 // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
3488 double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
3491 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
3492 tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
3493 stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
3496 buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
3497 buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
3498 if ( buf->renderOffset >= 0 && buf->start == -1 )
3500 buf->start = buf->renderOffset;
3502 else if ( buf->renderOffset == -1 && buf->start >= 0 )
3504 buf->renderOffset = buf->start;
3508 * Fill out buf->stop for subtitle packets
3510 * libavcodec's MKV demuxer stores the duration of UTF-8 subtitles (CODEC_ID_TEXT)
3511 * in the 'convergence_duration' field for some reason.
3513 * Other subtitles' durations are stored in the 'duration' field.
3515 * VOB subtitles (CODEC_ID_DVD_SUBTITLE) do not have their duration stored in
3516 * either field. This is not a problem because the VOB decoder can extract this
3517 * information from the packet payload itself.
3519 * SSA subtitles (CODEC_ID_SSA) do not have their duration stored in
3520 * either field. This is not a problem because the SSA decoder can extract this
3521 * information from the packet payload itself.
3523 enum CodecID ffmpeg_pkt_codec = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index]->codec->codec_id;
3524 if ( ffmpeg_pkt_codec == CODEC_ID_TEXT ) {
3525 int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->convergence_duration;
3526 int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
3527 buf->stop = buf->start + buf_duration;
3529 if ( ffmpeg_pkt_codec == CODEC_ID_MOV_TEXT ) {
3530 int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->duration;
3531 int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
3532 buf->stop = buf->start + buf_duration;
3536 * Check to see whether this video buffer is on a chapter
3537 * boundary, if so mark it as such in the buffer then advance
3538 * chapter_end to the end of the next chapter.
3539 * If there are no chapters, chapter_end is always initialized to INT64_MAX
3540 * (roughly 3 million years at our 90KHz clock rate) so the test
3541 * below handles both the chapters & no chapters case.
3543 if ( buf->id == stream->ffmpeg_video_id && buf->start >= stream->chapter_end )
3545 hb_chapter_t *chapter = hb_list_item( stream->title->list_chapter,
3546 stream->chapter+1 );
3550 stream->chapter_end += chapter->duration;
3551 buf->new_chap = stream->chapter + 1;
3552 hb_deep_log( 2, "ffmpeg_read starting chapter %i at %"PRId64,
3553 buf->new_chap, buf->start);
3555 // Must have run out of chapters, stop looking.
3556 stream->chapter_end = INT64_MAX;
3561 av_free_packet( stream->ffmpeg_pkt );
3565 static int ffmpeg_seek( hb_stream_t *stream, float frac )
3567 AVFormatContext *ic = stream->ffmpeg_ic;
3570 int64_t pos = (double)ic->duration * (double)frac;
3571 if ( ic->start_time != AV_NOPTS_VALUE && ic->start_time > 0 )
3573 pos += ic->start_time;
3575 av_seek_frame( ic, -1, pos, 0 );
3576 stream->need_keyframe = 1;
3580 av_seek_frame( ic, -1, 0LL, AVSEEK_FLAG_BACKWARD );
3585 // Assumes that we are always seeking forward
3586 static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts )
3588 AVFormatContext *ic = stream->ffmpeg_ic;
3591 pos = ts * AV_TIME_BASE / 90000 + ffmpeg_initial_timestamp( stream );
3592 stream->need_keyframe = 1;
3593 // Seek to the nearest timestamp before that requested where
3594 // there is an I-frame
3595 return av_seek_frame( ic, -1, pos, AVSEEK_FLAG_BACKWARD );