+ stream->need_keyframe = 0;
+
+ stream->ts_found_pcr = 0;
+ stream->ts_pcr_out = 0;
+ stream->ts_pcr_in = 0;
+ stream->ts_pcr = 0;
+
+ stream->frames = 0;
+ stream->errors = 0;
+ stream->last_error_frame = -10000;
+ stream->last_error_count = 0;
+
+ align_to_next_packet(stream);
+}
+
+// ------------------------------------------------------------------
+// Support for reading media files via the ffmpeg libraries.
+
+static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
+{
+ // add a codec to the context here so it will be there when we
+ // read the first packet.
+ AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
+ context->workaround_bugs = FF_BUG_AUTODETECT;
+ context->error_recognition = 1;
+ context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
+ AVCodec *codec = avcodec_find_decoder( context->codec_id );
+ hb_avcodec_open( context, codec );
+}
+
+// The ffmpeg stream reader / parser shares a lot of state with the
+// decoder via a codec context kept in the AVStream of the reader's
+// AVFormatContext. Since decoding is done in a different thread we
+// have to somehow pass this codec context to the decoder and we have
+// to do it before the first packet is read (so we can't put the info
+// in the buf we'll send downstream). Decoders don't have any way to
+// get to the stream directly (they're not passed the title or job
+// pointers during a scan) so this is a back door for the decoder to
+// get the codec context. We just stick the stream pointer in the next
+// slot an array of pointers maintained as a circular list then return
+// the index into the list combined with the ffmpeg stream index as the
+// codec_param that will be passed to the decoder init routine. We make
+// the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
+// so that we don't have to do a complicated allocator or worry about
+// deleting entries on close.
+//
+// Entries can only be added to this list during a scan and are never
+// deleted so the list access doesn't require locking.
+static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
+static int ffmpeg_stream_cur; // where we put the last stream pointer
+#define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
+#define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
+
+// add a stream to the list & return the appropriate codec_param to access it
+static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
+{
+ if ( !ffmpeg_streams )
+ {
+ ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
+ }
+
+ // the title scan adds all the ffmpeg media streams at once so we
+ // only add a new entry to our stream list if the stream is different
+ // than last time.
+ int slot = ffmpeg_stream_cur;
+ if ( ffmpeg_streams[slot] != stream )
+ {
+ // new stream - put it in the next slot of the stream list
+ slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
+ ffmpeg_streams[slot] = stream;
+ }
+
+ ffmpeg_add_codec( stream, stream_index );
+
+ return ( stream_index << ffmpeg_sl_bits ) | slot;
+}
+
+// we're about to open 'title' to convert it - remap the stream associated
+// with the video & audio codec params of the title to refer to 'stream'
+// (the original scan stream was closed and no longer exists).
+static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
+{
+ // all the video & audio came from the same stream so remapping
+ // the video's stream slot takes care of everything.
+ int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
+ ffmpeg_streams[slot] = stream;
+
+ // add codecs for all the streams used by the title
+ ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
+
+ int i;
+ hb_audio_t *audio;
+ for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
+ {
+ if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
+ {
+ ffmpeg_add_codec( stream,
+ audio->config.in.codec_param >> ffmpeg_sl_bits );
+ }
+ }
+}
+
+void *hb_ffmpeg_context( int codec_param )
+{
+ int slot = codec_param & (ffmpeg_sl_size - 1);
+ int stream_index = codec_param >> ffmpeg_sl_bits;
+ return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
+}
+
+void *hb_ffmpeg_avstream( int codec_param )
+{
+ int slot = codec_param & (ffmpeg_sl_size - 1);
+ int stream_index = codec_param >> ffmpeg_sl_bits;
+ return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
+}
+
+static AVFormatContext *ffmpeg_deferred_close;
+
+static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
+{
+ if ( ffmpeg_deferred_close )
+ {
+ av_close_input_file( ffmpeg_deferred_close );
+ ffmpeg_deferred_close = NULL;
+ }
+ AVFormatContext *ic;
+
+ av_log_set_level( AV_LOG_ERROR );
+ if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
+ {
+ return 0;
+ }
+ if ( av_find_stream_info( ic ) < 0 )
+ goto fail;
+
+ stream->ffmpeg_ic = ic;
+ stream->hb_stream_type = ffmpeg;
+ stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
+ av_init_packet( stream->ffmpeg_pkt );
+ stream->chapter_end = INT64_MAX;
+
+ if ( title )
+ {
+ // we're opening for read. scan passed out codec params that
+ // indexed its stream so we need to remap them so they point
+ // to this stream.
+ ffmpeg_remap_stream( stream, title );
+ av_log_set_level( AV_LOG_ERROR );
+ }
+ else
+ {
+ // we're opening for scan. let ffmpeg put some info into the
+ // log about what we've got.
+ av_log_set_level( AV_LOG_INFO );
+ dump_format( ic, 0, stream->path, 0 );
+ av_log_set_level( AV_LOG_ERROR );
+
+ // accept this file if it has at least one video stream we can decode
+ int i;
+ for (i = 0; i < ic->nb_streams; ++i )
+ {
+ if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
+ {
+ break;
+ }
+ }
+ if ( i >= ic->nb_streams )
+ goto fail;
+ }
+ return 1;
+
+ fail:
+ av_close_input_file( ic );
+ return 0;
+}
+
+static void ffmpeg_close( hb_stream_t *d )
+{
+ // XXX since we're sharing the CodecContext with the downstream
+ // decoder proc we can't close the stream. We need to reference count
+ // this so we can close it when both are done with their instance but
+ // for now just defer the close until the next stream open or close.
+ if ( ffmpeg_deferred_close )
+ {
+ av_close_input_file( ffmpeg_deferred_close );
+ }
+ ffmpeg_deferred_close = d->ffmpeg_ic;
+ if ( d->ffmpeg_pkt != NULL )
+ {
+ free( d->ffmpeg_pkt );
+ d->ffmpeg_pkt = NULL;
+ }
+}
+
+static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
+{
+ AVStream *st = stream->ffmpeg_ic->streams[id];
+ AVCodecContext *codec = st->codec;
+
+ // scan will ignore any audio without a bitrate. Since we've already
+ // typed the audio in order to determine its codec we set up the audio
+ // paramters here.
+ if ( codec->bit_rate || codec->sample_rate )
+ {
+ static const int chan2layout[] = {
+ HB_INPUT_CH_LAYOUT_MONO, // We should allow no audio really.
+ HB_INPUT_CH_LAYOUT_MONO,
+ HB_INPUT_CH_LAYOUT_STEREO,
+ HB_INPUT_CH_LAYOUT_2F1R,
+ HB_INPUT_CH_LAYOUT_2F2R,
+ HB_INPUT_CH_LAYOUT_3F2R,
+ HB_INPUT_CH_LAYOUT_4F2R,
+ HB_INPUT_CH_LAYOUT_STEREO,
+ HB_INPUT_CH_LAYOUT_STEREO,
+ };
+
+ hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
+
+ audio->id = id;
+ if ( codec->codec_id == CODEC_ID_AC3 )
+ {
+ audio->config.in.codec = HB_ACODEC_AC3;
+ }
+ else if ( codec->codec_id == CODEC_ID_DTS )
+ {
+ audio->config.in.codec = HB_ACODEC_DCA;
+ }
+ else
+ {
+ audio->config.in.codec = HB_ACODEC_FFMPEG;
+ audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
+
+ audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
+ audio->config.in.samplerate = codec->sample_rate;
+ audio->config.in.channel_layout = chan2layout[codec->channels & 7];
+ }
+
+ set_audio_description( audio, lang_for_code2( st->language ) );
+
+ hb_list_add( title->list_audio, audio );
+ }
+}
+
+static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
+{
+ AVFormatContext *ic = stream->ffmpeg_ic;
+
+ // 'Barebones Title'
+ hb_title_t *title = hb_title_init( stream->path, 0 );
+ title->index = 1;
+
+ // Copy part of the stream path to the title name
+ char *sep = strrchr(stream->path, '/');
+ if (sep)
+ strcpy(title->name, sep+1);
+ char *dot_term = strrchr(title->name, '.');
+ if (dot_term)
+ *dot_term = '\0';
+
+ uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
+ title->duration = dur;
+ dur /= 90000;
+ title->hours = dur / 3600;
+ title->minutes = ( dur % 3600 ) / 60;
+ title->seconds = dur % 60;
+
+ // set the title to decode the first video stream in the file
+ title->demuxer = HB_NULL_DEMUXER;
+ title->video_codec = 0;
+ int i;
+ for (i = 0; i < ic->nb_streams; ++i )
+ {
+ if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
+ avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
+ title->video_codec == 0 )
+ {
+ title->video_id = i;
+ stream->ffmpeg_video_id = i;
+
+ // We have to use the 'internal' avcodec decoder because
+ // it needs to share the codec context from this video
+ // stream. The parser internal to av_read_frame
+ // passes a bunch of state info to the decoder via the context.
+ title->video_codec = WORK_DECAVCODECVI;
+ title->video_codec_param = ffmpeg_codec_param( stream, i );
+ }
+ else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
+ avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
+ {
+ add_ffmpeg_audio( title, stream, i );
+ }
+ }
+
+ title->container_name = strdup( ic->iformat->name );
+ title->data_rate = ic->bit_rate;
+
+ hb_deep_log( 2, "Found ffmpeg %d chapters, container=%s", ic->nb_chapters, ic->iformat->name );
+
+ if( ic->nb_chapters != 0 )
+ {
+ AVChapter *m;
+ uint64_t duration_sum = 0;
+ for( i = 0; i < ic->nb_chapters; i++ )
+ if( ( m = ic->chapters[i] ) != NULL )
+ {
+ hb_chapter_t * chapter;
+ chapter = calloc( sizeof( hb_chapter_t ), 1 );
+ chapter->index = i+1;
+ chapter->duration = ( m->end / ( (double) m->time_base.num * m->time_base.den ) ) * 90000 - duration_sum;
+ duration_sum += chapter->duration;
+ chapter->hours = chapter->duration / 90000 / 3600;
+ chapter->minutes = ( ( chapter->duration / 90000 ) % 3600 ) / 60;
+ chapter->seconds = ( chapter->duration / 90000 ) % 60;
+ strcpy( chapter->title, m->title );
+ hb_deep_log( 2, "Added chapter %i, name='%s', dur=%"PRIu64", (%02i:%02i:%02i)",
+ chapter->index, chapter->title,
+ chapter->duration, chapter->hours,
+ chapter->minutes, chapter->seconds );
+ hb_list_add( title->list_chapter, chapter );
+ }
+ }
+
+ /*
+ * Fill the metadata.
+ */
+ decmetadata( title );
+
+ if( hb_list_count( title->list_chapter ) == 0 )
+ {
+ // Need at least one chapter
+ hb_chapter_t * chapter;
+ chapter = calloc( sizeof( hb_chapter_t ), 1 );
+ chapter->index = 1;
+ chapter->duration = title->duration;
+ chapter->hours = title->hours;
+ chapter->minutes = title->minutes;
+ chapter->seconds = title->seconds;
+ hb_list_add( title->list_chapter, chapter );
+ }
+
+ return title;
+}
+
+static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
+{
+ if ( pts == AV_NOPTS_VALUE )
+ return -1;
+ return (int64_t)( (double)pts * conv_factor );
+}
+
+static int ffmpeg_is_keyframe( hb_stream_t *stream )
+{
+ uint8_t *pkt;
+
+ switch ( stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->codec_id )
+ {
+ case CODEC_ID_VC1:
+ // XXX the VC1 codec doesn't mark key frames so to get previews
+ // we do it ourselves here. The decoder gets messed up if it
+ // doesn't get a SEQ header first so we consider that to be a key frame.
+ pkt = stream->ffmpeg_pkt->data;
+ if ( pkt[0] && pkt[1] && pkt[2] == 1 && pkt[3] == 0x0f )
+ return 1;
+
+ return 0;
+
+ case CODEC_ID_WMV3:
+ // XXX the ffmpeg WMV3 codec doesn't mark key frames.
+ // Only M$ could make I-frame detection this complicated: there
+ // are two to four bits of unused junk ahead of the frame type
+ // so we have to look at the sequence header to find out how much
+ // to skip. Then there are three different ways of coding the type
+ // depending on whether it's main or advanced profile then whether
+ // there are bframes or not so we have to look at the sequence
+ // header to get that.
+ pkt = stream->ffmpeg_pkt->data;
+ uint8_t *seqhdr = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->extradata;
+ int pshift = 2;
+ if ( ( seqhdr[3] & 0x02 ) == 0 )
+ // no FINTERPFLAG
+ ++pshift;
+ if ( ( seqhdr[3] & 0x80 ) == 0 )
+ // no RANGEREDUCTION
+ ++pshift;
+ if ( seqhdr[3] & 0x70 )
+ // stream has b-frames
+ return ( ( pkt[0] >> pshift ) & 0x3 ) == 0x01;
+
+ return ( ( pkt[0] >> pshift ) & 0x2 ) == 0;