+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;
+
+ default:
+ break;
+ }
+ return ( stream->ffmpeg_pkt->flags & PKT_FLAG_KEY );
+}
+
+static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
+{
+ int err;
+ again:
+ if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
+ {
+ // XXX the following conditional is to handle avi files that
+ // use M$ 'packed b-frames' and occasionally have negative
+ // sizes for the null frames these require.
+ if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
+ // eof
+ return 0;
+ }
+ if ( stream->ffmpeg_pkt->size <= 0 )
+ {
+ // M$ "invalid and inefficient" packed b-frames require 'null frames'
+ // following them to preserve the timing (since the packing puts two
+ // or more frames in what looks like one avi frame). The contents and
+ // size of these null frames are ignored by the ff_h263_decode_frame
+ // as long as they're < 20 bytes. We need a positive size so we use
+ // one byte if we're given a zero or negative size. We don't know
+ // if the pkt data points anywhere reasonable so we just stick a
+ // byte of zero in our outbound buf.
+ buf->size = 1;
+ *buf->data = 0;
+ }
+ else
+ {
+ if ( stream->ffmpeg_pkt->size > buf->alloc )
+ {
+ // sometimes we get absurd sizes from ffmpeg
+ if ( stream->ffmpeg_pkt->size >= (1 << 25) )
+ {
+ hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
+ av_free_packet( stream->ffmpeg_pkt );
+ return ffmpeg_read( stream, buf );
+ }
+ // need to expand buffer
+ hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
+ }
+ memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
+ buf->size = stream->ffmpeg_pkt->size;
+ }
+ buf->id = stream->ffmpeg_pkt->stream_index;
+ if ( buf->id == stream->ffmpeg_video_id )
+ {
+ if ( stream->need_keyframe )
+ {
+ // we've just done a seek (generally for scan or live preview) and
+ // want to start at a keyframe. Some ffmpeg codecs seek to a key
+ // frame but most don't. So we spin until we either get a keyframe
+ // or we've looked through 50 video frames without finding one.
+ if ( ! ffmpeg_is_keyframe( stream ) && ++stream->need_keyframe < 50 )
+ {
+ av_free_packet( stream->ffmpeg_pkt );
+ goto again;
+ }
+ stream->need_keyframe = 0;
+ }
+ ++stream->frames;
+ }
+
+ // if we haven't done it already, compute a conversion factor to go
+ // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
+ double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
+ if ( ! tsconv )
+ {
+ AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
+ tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
+ stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
+ }
+
+ buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
+ buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
+ if ( buf->renderOffset >= 0 && buf->start == -1 )
+ {
+ buf->start = buf->renderOffset;
+ }
+
+ /*
+ * Check to see whether this video buffer is on a chapter
+ * boundary, if so mark it as such in the buffer then advance
+ * chapter_end to the end of the next chapter.
+ * If there are no chapters, chapter_end is always initialized to INT64_MAX
+ * (roughly 3 million years at our 90KHz clock rate) so the test
+ * below handles both the chapters & no chapters case.
+ */
+ if ( buf->id == stream->ffmpeg_video_id && buf->start >= stream->chapter_end )
+ {
+ hb_chapter_t *chapter = hb_list_item( stream->title->list_chapter,
+ ++stream->chapter );
+ if( chapter )
+ {
+ stream->chapter_end += chapter->duration;
+ buf->new_chap = stream->chapter + 1;
+ hb_deep_log( 2, "ffmpeg_read starting chapter %i at %"PRId64,
+ buf->new_chap, buf->start);
+ } else {
+ // Must have run out of chapters, stop looking.
+ stream->chapter_end = INT64_MAX;
+ }
+ } else {
+ buf->new_chap = 0;
+ }
+ av_free_packet( stream->ffmpeg_pkt );
+ return 1;
+}
+
+static int ffmpeg_seek( hb_stream_t *stream, float frac )
+{
+ AVFormatContext *ic = stream->ffmpeg_ic;
+ if ( frac > 0. )
+ {
+ int64_t pos = (double)ic->duration * (double)frac;
+ if ( ic->start_time != AV_NOPTS_VALUE && ic->start_time > 0 )
+ {
+ pos += ic->start_time;
+ }
+ av_seek_frame( ic, -1, pos, 0 );
+ stream->need_keyframe = 1;
+ }
+ else
+ {
+ av_seek_frame( ic, -1, 0LL, AVSEEK_FLAG_BACKWARD );
+ }
+ return 1;
+}