+/** Initialize the video codec context.
+ */
+
+static int video_codec_init( producer_avformat this, int index, mlt_properties properties )
+{
+ // Initialise the codec if necessary
+ if ( !this->video_codec )
+ {
+ // Get the video stream
+ AVStream *stream = this->video_format->streams[ index ];
+
+ // Get codec context
+ AVCodecContext *codec_context = stream->codec;
+
+ // Find the codec
+ AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
+
+ // Initialise multi-threading
+ int thread_count = mlt_properties_get_int( properties, "threads" );
+ if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
+ thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
+ if ( thread_count > 1 )
+ {
+ avcodec_thread_init( codec_context, thread_count );
+ codec_context->thread_count = thread_count;
+ }
+
+ // If we don't have a codec and we can't initialise it, we can't do much more...
+ avformat_lock( );
+ if ( codec && avcodec_open( codec_context, codec ) >= 0 )
+ {
+ // Now store the codec with its destructor
+ producer_codec_close( this->video_codec );
+ this->video_codec = codec_context;
+ }
+ else
+ {
+ // Remember that we can't use this later
+ this->video_index = -1;
+ }
+ avformat_unlock( );
+
+ // Process properties as AVOptions
+ apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
+
+ // Reset some image properties
+ mlt_properties_set_int( properties, "width", this->video_codec->width );
+ mlt_properties_set_int( properties, "height", this->video_codec->height );
+ mlt_properties_set_double( properties, "aspect_ratio", get_aspect_ratio( stream, this->video_codec, NULL ) );
+
+ // Determine the fps first from the codec
+ double source_fps = (double) this->video_codec->time_base.den /
+ ( this->video_codec->time_base.num == 0 ? 1 : this->video_codec->time_base.num );
+
+ if ( mlt_properties_get( properties, "force_fps" ) )
+ {
+ source_fps = mlt_properties_get_double( properties, "force_fps" );
+ stream->time_base = av_d2q( source_fps, 255 );
+ }
+ else
+ {
+ // If the muxer reports a frame rate different than the codec
+ double muxer_fps = av_q2d( stream->r_frame_rate );
+ // Choose the lesser - the wrong tends to be off by some multiple of 10
+ source_fps = FFMIN( source_fps, muxer_fps );
+ }
+
+ // We'll use fps if it's available
+ if ( source_fps > 0 )
+ mlt_properties_set_double( properties, "source_fps", source_fps );
+ else
+ mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( &this->parent ) );
+ }
+ return this->video_codec && this->video_index > -1;
+}
+