2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2009 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Author: Dan Dennedy <dan@dennedy.org>
6 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <framework/mlt_producer.h>
25 #include <framework/mlt_frame.h>
26 #include <framework/mlt_profile.h>
27 #include <framework/mlt_log.h>
28 #include <framework/mlt_deque.h>
29 #include <framework/mlt_factory.h>
30 #include <framework/mlt_cache.h>
32 // ffmpeg Header files
33 #include <libavformat/avformat.h>
35 # include <libswscale/swscale.h>
37 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
38 # include "audioconvert.h"
41 # include <libavcodec/vdpau.h>
43 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
44 # include <libavutil/pixdesc.h>
47 // System header files
53 #if LIBAVUTIL_VERSION_INT < (50<<16)
54 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
55 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
58 #if LIBAVCODEC_VERSION_MAJOR > 52
59 #include <libavutil/opt.h>
60 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
61 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
62 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
64 #include <libavcodec/opt.h>
67 #define POSITION_INITIAL (-2)
68 #define POSITION_INVALID (-1)
70 #define MAX_AUDIO_STREAMS (10)
71 #define MAX_VDPAU_SURFACES (10)
73 void avformat_lock( );
74 void avformat_unlock( );
76 struct producer_avformat_s
79 AVFormatContext *dummy_context;
80 AVFormatContext *audio_format;
81 AVFormatContext *video_format;
82 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
83 AVCodecContext *video_codec;
85 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
86 mlt_position audio_expected;
87 mlt_position video_expected;
97 int16_t *audio_buffer[ MAX_AUDIO_STREAMS ];
98 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
99 int16_t *decode_buffer[ MAX_AUDIO_STREAMS ];
100 int audio_used[ MAX_AUDIO_STREAMS ];
102 int audio_max_stream;
106 unsigned int invalid_pts_counter;
107 double resample_factor;
108 mlt_cache image_cache;
110 pthread_mutex_t video_mutex;
111 pthread_mutex_t audio_mutex;
116 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
127 typedef struct producer_avformat_s *producer_avformat;
129 // Forward references.
130 static int producer_open( producer_avformat self, mlt_profile profile, char *file );
131 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
132 static void producer_avformat_close( producer_avformat );
133 static void producer_close( mlt_producer parent );
134 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
135 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
136 static void apply_properties( void *obj, mlt_properties properties, int flags );
137 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
143 /** Constructor for libavformat.
146 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
150 // Report information about available demuxers and codecs as YAML Tiny
151 if ( file && strstr( file, "f-list" ) )
153 fprintf( stderr, "---\nformats:\n" );
154 AVInputFormat *format = NULL;
155 while ( ( format = av_iformat_next( format ) ) )
156 fprintf( stderr, " - %s\n", format->name );
157 fprintf( stderr, "...\n" );
160 if ( file && strstr( file, "acodec-list" ) )
162 fprintf( stderr, "---\naudio_codecs:\n" );
163 AVCodec *codec = NULL;
164 while ( ( codec = av_codec_next( codec ) ) )
165 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
166 fprintf( stderr, " - %s\n", codec->name );
167 fprintf( stderr, "...\n" );
170 if ( file && strstr( file, "vcodec-list" ) )
172 fprintf( stderr, "---\nvideo_codecs:\n" );
173 AVCodec *codec = NULL;
174 while ( ( codec = av_codec_next( codec ) ) )
175 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
176 fprintf( stderr, " - %s\n", codec->name );
177 fprintf( stderr, "...\n" );
181 // Check that we have a non-NULL argument
184 // Construct the producer
185 mlt_producer producer = calloc( 1, sizeof( struct mlt_producer_s ) );
186 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
189 if ( mlt_producer_init( producer, self ) == 0 )
191 self->parent = producer;
193 // Get the properties
194 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
196 // Set the resource property (required for all producers)
197 mlt_properties_set( properties, "resource", file );
199 // Register transport implementation with the producer
200 producer->close = (mlt_destructor) producer_close;
202 // Register our get_frame implementation
203 producer->get_frame = producer_get_frame;
205 if ( strcmp( service, "avformat-novalidate" ) )
208 if ( producer_open( self, profile, file ) != 0 )
211 mlt_producer_close( producer );
216 // Close the file to release resources for large playlists - reopen later as needed
218 if ( self->dummy_context )
219 av_close_input_file( self->dummy_context );
220 self->dummy_context = NULL;
221 if ( self->audio_format )
222 av_close_input_file( self->audio_format );
223 self->audio_format = NULL;
224 if ( self->video_format )
225 av_close_input_file( self->video_format );
226 self->video_format = NULL;
229 // Default the user-selectable indices from the auto-detected indices
230 mlt_properties_set_int( properties, "audio_index", self->audio_index );
231 mlt_properties_set_int( properties, "video_index", self->video_index );
234 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
236 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
242 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
244 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
252 /** Find the default streams.
255 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
259 AVMetadataTag *tag = NULL;
261 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
263 // Allow for multiple audio and video streams in the file and select first of each (if available)
264 for( i = 0; i < context->nb_streams; i++ )
266 // Get the codec context
267 AVStream *stream = context->streams[ i ];
268 if ( ! stream ) continue;
269 AVCodecContext *codec_context = stream->codec;
270 if ( ! codec_context ) continue;
271 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
272 if ( ! codec ) continue;
274 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
276 // Determine the type and obtain the first index of each type
277 switch( codec_context->codec_type )
279 case CODEC_TYPE_VIDEO:
280 if ( *video_index < 0 )
282 mlt_properties_set( meta_media, key, "video" );
283 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
284 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
285 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
286 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
287 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
288 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
290 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
293 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
294 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
295 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
297 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
298 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
299 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
300 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
301 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
302 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
303 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
304 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
305 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
306 switch ( codec_context->colorspace )
308 case AVCOL_SPC_SMPTE240M:
309 mlt_properties_set_int( meta_media, key, 240 );
311 case AVCOL_SPC_BT470BG:
312 case AVCOL_SPC_SMPTE170M:
313 mlt_properties_set_int( meta_media, key, 601 );
315 case AVCOL_SPC_BT709:
316 mlt_properties_set_int( meta_media, key, 709 );
319 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
320 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
325 case CODEC_TYPE_AUDIO:
326 if ( *audio_index < 0 )
328 mlt_properties_set( meta_media, key, "audio" );
329 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
330 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
331 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
333 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
334 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
335 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
336 mlt_properties_set_int( meta_media, key, codec_context->channels );
341 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
342 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
343 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
344 mlt_properties_set( meta_media, key, codec->name );
345 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
346 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
347 mlt_properties_set( meta_media, key, codec->long_name );
349 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
350 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
351 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
352 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
353 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
354 // mlt_properties_set_int( meta_media, key, codec_context->profile );
355 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
356 // mlt_properties_set_int( meta_media, key, codec_context->level );
359 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
360 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
362 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
364 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
365 mlt_properties_set( meta_media, key, tag->value );
370 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
371 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
373 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
375 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
376 mlt_properties_set( meta_media, key, tag->value );
380 if ( context->title && strcmp( context->title, "" ) )
381 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
382 if ( context->author && strcmp( context->author, "" ) )
383 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
384 if ( context->copyright && strcmp( context->copyright, "" ) )
385 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
386 if ( context->comment )
387 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
388 if ( context->album )
389 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
391 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
392 if ( context->track )
393 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
399 static inline int dv_is_pal( AVPacket *pkt )
401 return pkt->data[3] & 0x80;
404 static int dv_is_wide( AVPacket *pkt )
406 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
408 for ( ; i < pkt->size; i += 5 /* packet size */ )
410 if ( pkt->data[ i ] == 0x61 )
412 uint8_t x = pkt->data[ i + 2 ] & 0x7;
413 return ( x == 2 ) || ( x == 7 );
419 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
421 double aspect_ratio = 1.0;
423 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
427 if ( dv_is_pal( pkt ) )
429 if ( dv_is_wide( pkt ) )
431 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
432 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
436 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
437 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
442 if ( dv_is_wide( pkt ) )
444 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
445 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
449 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
450 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
457 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
458 stream->sample_aspect_ratio;
460 codec_context->sample_aspect_ratio;
462 // Override FFmpeg's notion of DV aspect ratios, which are
463 // based upon a width of 704. Since we do not have a normaliser
464 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
465 // we just coerce the values to facilitate a passive behaviour through
466 // the rescale normaliser when using equivalent producers and consumers.
467 // = display_aspect / (width * height)
468 if ( ar.num == 10 && ar.den == 11 )
471 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
472 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
474 else if ( ar.num == 59 && ar.den == 54 )
477 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
478 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
480 else if ( ar.num == 40 && ar.den == 33 )
483 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
484 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
486 else if ( ar.num == 118 && ar.den == 81 )
489 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
490 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
496 AVRational codec_sar = codec_context->sample_aspect_ratio;
497 AVRational stream_sar =
498 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
499 stream->sample_aspect_ratio;
503 if ( codec_sar.num > 0 )
505 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
506 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
508 else if ( stream_sar.num > 0 )
510 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
511 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
515 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
516 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
519 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
520 aspect_ratio = av_q2d( ar );
521 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
529 static int producer_open( producer_avformat self, mlt_profile profile, char *file )
531 // Return an error code (0 == no error)
534 // Context for avformat
535 AVFormatContext *context = NULL;
537 // Get the properties
538 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
540 // We will treat everything with the producer fps
541 double fps = mlt_profile_fps( profile );
544 pthread_mutex_init( &self->audio_mutex, NULL );
545 pthread_mutex_init( &self->video_mutex, NULL );
546 pthread_mutex_lock( &self->audio_mutex );
547 pthread_mutex_lock( &self->video_mutex );
549 // If "MRL", then create AVInputFormat
550 AVInputFormat *format = NULL;
551 AVFormatParameters *params = NULL;
552 char *standard = NULL;
553 char *mrl = strchr( file, ':' );
555 // AV option (0 = both, 1 = video, 2 = audio)
558 // Only if there is not a protocol specification that avformat can handle
559 if ( mrl && !url_exist( file ) )
561 // 'file' becomes format abbreviation
565 format = av_find_input_format( file );
567 // Eat the format designator
573 params = calloc( sizeof( AVFormatParameters ), 1 );
575 // These are required by video4linux (defaults)
577 params->height = 480;
578 params->time_base= (AVRational){1,25};
579 params->channels = 2;
580 params->sample_rate = 48000;
584 mrl = strchr( file, '?' );
588 char *name = strdup( ++mrl );
589 char *value = strchr( name, ':' );
594 char *t = strchr( value, '&' );
597 if ( !strcmp( name, "frame_rate" ) )
598 params->time_base.den = atoi( value );
599 else if ( !strcmp( name, "frame_rate_base" ) )
600 params->time_base.num = atoi( value );
601 else if ( !strcmp( name, "sample_rate" ) )
602 params->sample_rate = atoi( value );
603 else if ( !strcmp( name, "channel" ) )
604 params->channel = atoi( value );
605 else if ( !strcmp( name, "channels" ) )
606 params->channels = atoi( value );
607 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
608 else if ( !strcmp( name, "pix_fmt" ) )
609 params->pix_fmt = av_get_pix_fmt( value );
611 else if ( !strcmp( name, "width" ) )
612 params->width = atoi( value );
613 else if ( !strcmp( name, "height" ) )
614 params->height = atoi( value );
615 else if ( !strcmp( name, "standard" ) )
617 standard = strdup( value );
618 params->standard = standard;
620 else if ( !strcmp( name, "av" ) )
624 mrl = strchr( mrl, '&' );
628 // Now attempt to open the file
629 error = av_open_input_file( &context, file, format, 0, params ) < 0;
631 // Cleanup AVFormatParameters
635 // If successful, then try to get additional info
638 // Get the stream info
639 error = av_find_stream_info( context ) < 0;
641 // Continue if no error
644 // We will default to the first audio and video streams found
645 int audio_index = -1;
646 int video_index = -1;
648 // Find default audio and video streams
649 find_default_streams( properties, context, &audio_index, &video_index );
651 // Now set properties where we can (use default unknowns if required)
652 if ( context->duration != AV_NOPTS_VALUE )
654 // This isn't going to be accurate for all formats
655 // Workaround some clips whose estimated duration cause problems:
656 // http://www.kdenlive.org/mantis/view.php?id=2003
658 if ( mlt_properties_get( properties, "adjust_length" ) )
659 adjust = mlt_properties_get_int( properties, "adjust_length" );
660 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + adjust );
661 if ( mlt_properties_get_position( properties, "force_length" ) > 0 )
662 frames = mlt_properties_get_position( properties, "force_length" );
663 mlt_properties_set_position( properties, "out", frames - 1 );
664 mlt_properties_set_position( properties, "length", frames );
667 if ( context->start_time != AV_NOPTS_VALUE )
668 self->start_time = context->start_time;
670 // Check if we're seekable
671 // avdevices are typically AVFMT_NOFILE and not seekable
672 self->seekable = !format || !( format->flags & AVFMT_NOFILE );
675 // protocols can indicate if they support seeking
676 URLContext *uc = url_fileno( context->pb );
678 self->seekable = !uc->is_streamed;
680 if ( self->seekable )
682 self->seekable = av_seek_frame( context, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
683 mlt_properties_set_int( properties, "seekable", self->seekable );
684 self->dummy_context = context;
685 av_open_input_file( &context, file, NULL, 0, NULL );
686 av_find_stream_info( context );
689 // Store selected audio and video indexes on properties
690 self->audio_index = audio_index;
691 self->video_index = video_index;
692 self->first_pts = -1;
693 self->last_position = POSITION_INITIAL;
695 // Fetch the width, height and aspect ratio
696 if ( video_index != -1 )
698 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
699 mlt_properties_set_int( properties, "width", codec_context->width );
700 mlt_properties_set_int( properties, "height", codec_context->height );
702 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
704 // Fetch the first frame of DV so we can read it directly
709 ret = av_read_frame( context, &pkt );
710 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
712 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, &pkt );
719 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, NULL );
722 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
723 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
725 sws_freeContext( context );
731 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
732 if ( av == 0 && audio_index != -1 && video_index != -1 )
734 // We'll use the open one as our video_format
735 self->video_format = context;
737 // And open again for our audio context
738 av_open_input_file( &context, file, NULL, 0, NULL );
739 av_find_stream_info( context );
742 self->audio_format = context;
744 else if ( av != 2 && video_index != -1 )
746 // We only have a video context
747 self->video_format = context;
749 else if ( audio_index != -1 )
751 // We only have an audio context
752 self->audio_format = context;
756 // Something has gone wrong
762 // Unlock the service
763 pthread_mutex_unlock( &self->audio_mutex );
764 pthread_mutex_unlock( &self->video_mutex );
769 void reopen_video( producer_avformat self, mlt_producer producer, mlt_properties properties )
771 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
772 pthread_mutex_lock( &self->audio_mutex );
774 if ( self->video_codec )
777 avcodec_close( self->video_codec );
780 self->video_codec = NULL;
781 if ( self->dummy_context )
782 av_close_input_file( self->dummy_context );
783 self->dummy_context = NULL;
784 if ( self->video_format )
785 av_close_input_file( self->video_format );
786 self->video_format = NULL;
788 int audio_index = self->audio_index;
789 int video_index = self->video_index;
791 mlt_events_block( properties, producer );
792 pthread_mutex_unlock( &self->audio_mutex );
793 pthread_mutex_unlock( &self->video_mutex );
794 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
795 mlt_properties_get( properties, "resource" ) );
796 pthread_mutex_lock( &self->video_mutex );
797 pthread_mutex_lock( &self->audio_mutex );
798 if ( self->dummy_context )
800 av_close_input_file( self->dummy_context );
801 self->dummy_context = NULL;
803 mlt_events_unblock( properties, producer );
804 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
806 self->audio_index = audio_index;
807 if ( self->video_format && video_index > -1 )
809 self->video_index = video_index;
810 video_codec_init( self, video_index, properties );
813 pthread_mutex_unlock( &self->audio_mutex );
814 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
817 /** Convert a frame position to a time code.
820 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
822 return ( double )position / mlt_producer_get_fps( producer );
825 // Collect information about all audio streams
827 static void get_audio_streams_info( producer_avformat self )
829 // Fetch the audio format context
830 AVFormatContext *context = self->audio_format;
834 i < context->nb_streams;
837 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
839 AVCodecContext *codec_context = context->streams[i]->codec;
840 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
842 // If we don't have a codec and we can't initialise it, we can't do much more...
844 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
846 self->audio_streams++;
847 self->audio_max_stream = i;
848 self->total_channels += codec_context->channels;
849 if ( codec_context->channels > self->max_channel )
850 self->max_channel = codec_context->channels;
851 if ( codec_context->sample_rate > self->max_frequency )
852 self->max_frequency = codec_context->sample_rate;
853 avcodec_close( codec_context );
858 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
859 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
861 // Other audio-specific initializations
862 self->resample_factor = 1.0;
865 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
867 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
870 int brightness, contrast, saturation;
872 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
873 &brightness, &contrast, &saturation ) != -1 )
875 // Don't change these from defaults unless explicitly told to.
876 if ( use_full_range >= 0 )
877 full_range = use_full_range;
878 switch ( colorspace )
884 coefficients = sws_getCoefficients( SWS_CS_ITU601 );
887 coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
890 coefficients = sws_getCoefficients( SWS_CS_ITU709 );
893 sws_setColorspaceDetails( context, coefficients, full_range, coefficients, full_range,
894 brightness, contrast, saturation );
899 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
900 mlt_image_format *format, int width, int height, int colorspace )
904 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
907 flags |= SWS_CPU_CAPS_MMX;
910 flags |= SWS_CPU_CAPS_MMX2;
913 if ( pix_fmt == PIX_FMT_RGB32 )
915 *format = mlt_image_rgb24a;
916 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
917 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
919 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
920 set_luma_transfer( context, colorspace, full_range );
921 sws_scale( context, frame->data, frame->linesize, 0, height,
922 output.data, output.linesize);
923 sws_freeContext( context );
925 else if ( *format == mlt_image_yuv420p )
927 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
928 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
930 output.data[0] = buffer;
931 output.data[1] = buffer + width * height;
932 output.data[2] = buffer + ( 5 * width * height ) / 4;
933 output.linesize[0] = width;
934 output.linesize[1] = width >> 1;
935 output.linesize[2] = width >> 1;
936 set_luma_transfer( context, colorspace, full_range );
937 sws_scale( context, frame->data, frame->linesize, 0, height,
938 output.data, output.linesize);
939 sws_freeContext( context );
941 else if ( *format == mlt_image_rgb24 )
943 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
944 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
946 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
947 set_luma_transfer( context, colorspace, full_range );
948 sws_scale( context, frame->data, frame->linesize, 0, height,
949 output.data, output.linesize);
950 sws_freeContext( context );
952 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
954 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
955 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
957 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
958 set_luma_transfer( context, colorspace, full_range );
959 sws_scale( context, frame->data, frame->linesize, 0, height,
960 output.data, output.linesize);
961 sws_freeContext( context );
965 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
966 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
968 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
969 set_luma_transfer( context, colorspace, full_range );
970 sws_scale( context, frame->data, frame->linesize, 0, height,
971 output.data, output.linesize);
972 sws_freeContext( context );
975 if ( *format == mlt_image_yuv420p )
978 pict.data[0] = buffer;
979 pict.data[1] = buffer + width * height;
980 pict.data[2] = buffer + ( 5 * width * height ) / 4;
981 pict.linesize[0] = width;
982 pict.linesize[1] = width >> 1;
983 pict.linesize[2] = width >> 1;
984 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
986 else if ( *format == mlt_image_rgb24 )
989 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
990 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
992 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
995 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
996 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1001 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1002 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1007 /** Allocate the image buffer and set it on the frame.
1010 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1014 if ( codec_context->width == 0 || codec_context->height == 0 )
1017 *width = codec_context->width;
1018 *height = codec_context->height;
1020 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
1021 size = *width * ( *height + 1 ) * 4;
1023 size = mlt_image_format_size( *format, *width, *height, NULL );
1025 // Construct the output image
1026 *buffer = mlt_pool_alloc( size );
1028 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1035 /** Get an image from a frame.
1038 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1041 producer_avformat self = mlt_frame_pop_service( frame );
1042 mlt_producer producer = self->parent;
1044 // Get the properties from the frame
1045 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1047 // Obtain the frame number of this frame
1048 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1050 // Get the producer properties
1051 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1053 pthread_mutex_lock( &self->video_mutex );
1055 // Fetch the video format context
1056 AVFormatContext *context = self->video_format;
1058 // Get the video stream
1059 AVStream *stream = context->streams[ self->video_index ];
1061 // Get codec context
1062 AVCodecContext *codec_context = stream->codec;
1064 // Get the image cache
1065 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1066 self->image_cache = mlt_cache_init();
1067 if ( self->image_cache )
1069 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1070 *buffer = mlt_cache_item_data( item, (int*) format );
1073 // Set the resolution
1074 *width = codec_context->width;
1075 *height = codec_context->height;
1077 // Workaround 1088 encodings missing cropping info.
1078 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1082 int size = mlt_image_format_size( *format, *width, *height, NULL );
1083 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1084 mlt_frame_set_image( frame, *buffer, size, NULL );
1085 // self->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1086 self->got_picture = 1;
1088 goto exit_get_image;
1097 // Special case pause handling flag
1100 // Special case ffwd handling
1103 // We may want to use the source fps if available
1104 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1105 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1106 double fps = mlt_producer_get_fps( producer );
1108 // This is the physical frame position in the source
1109 int req_position = ( int )( position / fps * source_fps + 0.5 );
1111 // Determines if we have to decode all frames in a sequence
1112 // Temporary hack to improve intra frame only
1113 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1114 strcmp( codec_context->codec->name, "dvvideo" ) &&
1115 strcmp( codec_context->codec->name, "huffyuv" ) &&
1116 strcmp( codec_context->codec->name, "mjpeg" ) &&
1117 strcmp( codec_context->codec->name, "rawvideo" );
1119 int last_position = self->last_position;
1121 // Turn on usage of new seek API and PTS for seeking
1122 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1123 if ( mlt_properties_get( properties, "new_seek" ) )
1124 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1126 // Seek if necessary
1127 if ( position != self->video_expected || last_position < 0 )
1129 if ( self->av_frame && position + 1 == self->video_expected )
1131 // We're paused - use last image
1134 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1136 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1137 ignore = ( int )( ( position - self->video_expected ) / fps * source_fps );
1138 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1140 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || last_position < 0 ) )
1142 if ( use_new_seek && last_position == POSITION_INITIAL )
1144 // find first key frame
1148 while ( ret >= 0 && toscan-- > 0 )
1150 ret = av_read_frame( context, &pkt );
1151 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1153 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "first_pts %lld dts %lld pts_dts_delta %d\n", pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1154 self->first_pts = pkt.pts;
1157 av_free_packet( &pkt );
1160 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1163 // Calculate the timestamp for the requested frame
1167 timestamp = ( req_position - 0.1 / source_fps ) /
1168 ( av_q2d( stream->time_base ) * source_fps );
1169 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
1170 if ( self->first_pts > 0 )
1171 timestamp += self->first_pts;
1172 else if ( context->start_time != AV_NOPTS_VALUE )
1173 timestamp += context->start_time;
1177 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1178 if ( context->start_time != AV_NOPTS_VALUE )
1179 timestamp += context->start_time;
1182 timestamp -= AV_TIME_BASE;
1183 if ( timestamp < 0 )
1185 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
1186 timestamp, position, self->video_expected, last_position );
1188 // Seek to the timestamp
1191 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1192 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1194 else if ( req_position > 0 || last_position <= 0 )
1196 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1200 // Re-open video stream when rewinding to beginning from somewhere else.
1201 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1202 // not reliably seeking to the first frame across formats.
1203 reopen_video( self, producer, properties );
1204 context = self->video_format;
1205 stream = context->streams[ self->video_index ];
1206 codec_context = stream->codec;
1209 // Remove the cached info relating to the previous position
1210 self->current_position = POSITION_INVALID;
1211 self->last_position = POSITION_INVALID;
1212 av_freep( &self->av_frame );
1216 // flush any pictures still in decode buffer
1217 avcodec_flush_buffers( codec_context );
1222 // Duplicate the last image if necessary
1223 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture && self->seekable
1225 || self->current_position == req_position
1226 || ( !use_new_seek && self->current_position > req_position ) ) )
1229 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1231 // Workaround 1088 encodings missing cropping info.
1232 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1235 if ( self->vdpau && self->vdpau->buffer )
1238 picture.data[0] = self->vdpau->buffer;
1239 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1240 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1241 picture.linesize[0] = codec_context->width;
1242 picture.linesize[1] = codec_context->width / 2;
1243 picture.linesize[2] = codec_context->width / 2;
1244 convert_image( (AVFrame*) &picture, *buffer,
1245 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1249 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1250 format, *width, *height, self->colorspace );
1253 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1258 int int_position = 0;
1259 int decode_errors = 0;
1260 int got_picture = 0;
1262 av_init_packet( &pkt );
1264 // Construct an AVFrame for YUV422 conversion
1265 if ( !self->av_frame )
1266 self->av_frame = avcodec_alloc_frame( );
1268 while( ret >= 0 && !got_picture )
1271 ret = av_read_frame( context, &pkt );
1273 // We only deal with video from the selected video_index
1274 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1276 // Determine time code of the packet
1279 int64_t pts = pkt.pts;
1280 if ( self->first_pts > 0 )
1281 pts -= self->first_pts;
1282 else if ( context->start_time != AV_NOPTS_VALUE )
1283 pts -= context->start_time;
1284 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1285 if ( pkt.pts == AV_NOPTS_VALUE )
1287 self->invalid_pts_counter++;
1288 if ( self->invalid_pts_counter > 20 )
1290 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1291 mlt_properties_set_int( properties, "new_seek", 0 );
1292 int_position = req_position;
1298 self->invalid_pts_counter = 0;
1300 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1301 pkt.pts, req_position, self->current_position, int_position );
1305 if ( self->seekable && pkt.dts != AV_NOPTS_VALUE )
1307 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1308 if ( context->start_time != AV_NOPTS_VALUE )
1309 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1310 last_position = self->last_position;
1311 if ( int_position == last_position )
1312 int_position = last_position + 1;
1316 int_position = req_position;
1318 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1319 pkt.dts, req_position, self->current_position, int_position );
1320 // Make a dumb assumption on streams that contain wild timestamps
1321 if ( abs( req_position - int_position ) > 999 )
1323 int_position = req_position;
1324 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1327 self->last_position = int_position;
1330 if ( must_decode || int_position >= req_position )
1333 if ( g_vdpau && self->vdpau )
1335 if ( g_vdpau->producer != self )
1337 vdpau_decoder_close();
1338 vdpau_decoder_init( self );
1341 self->vdpau->is_decoded = 0;
1344 codec_context->reordered_opaque = pkt.pts;
1345 if ( int_position >= req_position )
1346 codec_context->skip_loop_filter = AVDISCARD_NONE;
1347 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1348 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1350 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1352 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1355 if ( ++decode_errors <= 10 )
1368 // Determine time code of the packet
1369 int64_t pts = self->av_frame->reordered_opaque;
1370 if ( self->first_pts > 0 )
1371 pts -= self->first_pts;
1372 else if ( context->start_time != AV_NOPTS_VALUE )
1373 pts -= context->start_time;
1374 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1375 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1378 if ( int_position < req_position )
1383 else if ( int_position >= req_position )
1386 codec_context->skip_loop_filter = AVDISCARD_NONE;
1388 else if ( ignore -- )
1393 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1396 // Now handle the picture if we have one
1399 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1401 // Workaround 1088 encodings missing cropping info.
1402 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1407 if ( self->vdpau->is_decoded )
1409 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1411 uint32_t pitches[3];
1412 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1414 if ( !self->vdpau->buffer )
1415 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1416 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1417 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1418 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1419 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1420 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1421 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1423 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1424 if ( status == VDP_STATUS_OK )
1426 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1427 format, *width, *height, self->colorspace );
1431 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1432 self->vdpau->is_decoded = 0;
1437 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1443 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1444 format, *width, *height, self->colorspace );
1445 self->top_field_first |= self->av_frame->top_field_first;
1446 self->current_position = int_position;
1447 self->got_picture = 1;
1455 av_free_packet( &pkt );
1459 if ( self->got_picture && image_size > 0 && self->image_cache )
1461 // Copy buffer to image cache
1462 uint8_t *image = mlt_pool_alloc( image_size );
1463 memcpy( image, *buffer, image_size );
1464 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1467 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1468 self->video_expected = position + 1;
1472 pthread_mutex_unlock( &self->video_mutex );
1474 // Set the progressive flag
1475 if ( mlt_properties_get( properties, "force_progressive" ) )
1476 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1477 else if ( self->av_frame )
1478 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1480 // Set the field order property for this frame
1481 if ( mlt_properties_get( properties, "force_tff" ) )
1482 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1484 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1486 // Set immutable properties of the selected track's (or overridden) source attributes.
1487 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1488 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1489 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1490 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1492 return !self->got_picture;
1495 /** Process properties as AVOptions and apply to AV context obj
1498 static void apply_properties( void *obj, mlt_properties properties, int flags )
1501 int count = mlt_properties_count( properties );
1502 for ( i = 0; i < count; i++ )
1504 const char *opt_name = mlt_properties_get_name( properties, i );
1505 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1506 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1509 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1510 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1511 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1512 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1514 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1520 /** Initialize the video codec context.
1523 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1525 // Initialise the codec if necessary
1526 if ( !self->video_codec )
1528 // Get the video stream
1529 AVStream *stream = self->video_format->streams[ index ];
1531 // Get codec context
1532 AVCodecContext *codec_context = stream->codec;
1535 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1537 if ( codec_context->codec_id == CODEC_ID_H264 )
1539 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1541 if ( vdpau_init( self ) )
1543 self->video_codec = codec_context;
1544 if ( !vdpau_decoder_init( self ) )
1545 vdpau_decoder_close();
1549 codec = avcodec_find_decoder( codec_context->codec_id );
1553 // Initialise multi-threading
1554 int thread_count = mlt_properties_get_int( properties, "threads" );
1555 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1556 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1557 if ( thread_count > 1 )
1558 codec_context->thread_count = thread_count;
1560 // If we don't have a codec and we can't initialise it, we can't do much more...
1562 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1564 // Now store the codec with its destructor
1565 self->video_codec = codec_context;
1569 // Remember that we can't use this later
1570 self->video_index = -1;
1576 // Process properties as AVOptions
1577 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1579 // Reset some image properties
1580 mlt_properties_set_int( properties, "width", self->video_codec->width );
1581 mlt_properties_set_int( properties, "height", self->video_codec->height );
1582 // For DV, we'll just use the saved aspect ratio
1583 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1584 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1586 // Determine the fps first from the codec
1587 double source_fps = (double) self->video_codec->time_base.den /
1588 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1590 if ( mlt_properties_get( properties, "force_fps" ) )
1592 source_fps = mlt_properties_get_double( properties, "force_fps" );
1593 stream->time_base = av_d2q( source_fps, 1024 );
1594 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1595 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1599 // If the muxer reports a frame rate different than the codec
1600 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1601 double muxer_fps = av_q2d( stream->avg_frame_rate );
1602 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1603 muxer_fps = av_q2d( stream->r_frame_rate );
1605 double muxer_fps = av_q2d( stream->r_frame_rate );
1607 // Choose the lesser - the wrong tends to be off by some multiple of 10
1608 source_fps = FFMIN( source_fps, muxer_fps );
1609 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1611 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1612 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1614 else if ( muxer_fps > 0 )
1616 AVRational frame_rate = stream->r_frame_rate;
1617 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1618 // avg_frame_rate gives some approximate value that does not well match the media.
1619 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1620 // results in some very choppy output, but some value slightly different works
1622 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1623 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1624 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1626 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1627 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1631 source_fps = mlt_producer_get_fps( self->parent );
1632 AVRational frame_rate = av_d2q( source_fps, 255 );
1633 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1634 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1638 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1639 if ( source_fps > 0 )
1640 mlt_properties_set_double( properties, "source_fps", source_fps );
1642 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1644 // Set the YUV colorspace from override or detect
1645 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1646 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1647 if ( ! self->colorspace )
1649 switch ( self->video_codec->colorspace )
1651 case AVCOL_SPC_SMPTE240M:
1652 self->colorspace = 240;
1654 case AVCOL_SPC_BT470BG:
1655 case AVCOL_SPC_SMPTE170M:
1656 self->colorspace = 601;
1658 case AVCOL_SPC_BT709:
1659 self->colorspace = 709;
1662 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1663 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1668 // Let apps get chosen colorspace
1669 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1671 return self->video_codec && self->video_index > -1;
1674 /** Set up video handling.
1677 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1680 mlt_producer producer = self->parent;
1682 // Get the properties
1683 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1685 // Fetch the video format context
1686 AVFormatContext *context = self->video_format;
1688 // Get the video_index
1689 int index = mlt_properties_get_int( properties, "video_index" );
1691 // Reopen the file if necessary
1692 if ( !context && index > -1 )
1694 mlt_events_block( properties, producer );
1695 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1696 mlt_properties_get( properties, "resource" ) );
1697 context = self->video_format;
1698 if ( self->dummy_context )
1700 av_close_input_file( self->dummy_context );
1701 self->dummy_context = NULL;
1703 mlt_events_unblock( properties, producer );
1704 if ( self->audio_format && !self->audio_streams )
1705 get_audio_streams_info( self );
1707 // Process properties as AVOptions
1709 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1712 // Exception handling for video_index
1713 if ( context && index >= (int) context->nb_streams )
1715 // Get the last video stream
1716 for ( index = context->nb_streams - 1;
1717 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1719 mlt_properties_set_int( properties, "video_index", index );
1721 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1723 // Invalidate the video stream
1725 mlt_properties_set_int( properties, "video_index", index );
1728 // Update the video properties if the index changed
1729 if ( index != self->video_index )
1731 // Reset the video properties if the index changed
1732 self->video_index = index;
1733 if ( self->video_codec )
1736 avcodec_close( self->video_codec );
1739 self->video_codec = NULL;
1742 // Get the frame properties
1743 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1746 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1748 // Set the frame properties
1749 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1750 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1751 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1753 // Set the width and height
1754 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1755 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1756 // real_width and real_height are deprecated in favor of meta.media.width and .height
1757 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1758 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1759 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1760 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1761 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1762 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1764 // Workaround 1088 encodings missing cropping info.
1765 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1767 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1768 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1771 // Add our image operation
1772 mlt_frame_push_service( frame, self );
1773 mlt_frame_push_get_image( frame, producer_get_image );
1777 // If something failed, use test card image
1778 mlt_properties_set_int( frame_properties, "test_image", 1 );
1782 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1786 // Seek if necessary
1787 if ( position != self->audio_expected )
1789 if ( position + 1 == self->audio_expected )
1791 // We're paused - silence required
1794 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1796 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1797 *ignore = position - self->audio_expected;
1799 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1801 AVFormatContext *context = self->audio_format;
1802 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1803 if ( context->start_time != AV_NOPTS_VALUE )
1804 timestamp += context->start_time;
1805 if ( timestamp < 0 )
1808 // Set to the real timecode
1809 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1812 // Clear the usage in the audio buffer
1813 int i = MAX_AUDIO_STREAMS + 1;
1815 self->audio_used[i - 1] = 0;
1821 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1823 // Fetch the audio_format
1824 AVFormatContext *context = self->audio_format;
1826 // Get the current stream index
1827 int index = pkt.stream_index;
1829 // Get codec context
1830 AVCodecContext *codec_context = self->audio_codec[ index ];
1832 // Obtain the resample context if it exists (not always needed)
1833 ReSampleContext *resample = self->audio_resample[ index ];
1835 // Obtain the audio buffers
1836 int16_t *audio_buffer = self->audio_buffer[ index ];
1837 int16_t *decode_buffer = self->decode_buffer[ index ];
1839 int audio_used = self->audio_used[ index ];
1840 uint8_t *ptr = pkt.data;
1844 while ( ptr && ret >= 0 && len > 0 )
1846 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1849 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1850 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, &pkt );
1851 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1852 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1854 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1858 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
1862 pkt.size = len -= ret;
1863 pkt.data = ptr += ret;
1865 // If decoded successfully
1866 if ( data_size > 0 )
1868 // Figure out how many samples will be needed after resampling
1869 int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1870 int samples_needed = self->resample_factor * convert_samples + 1;
1872 // Resize audio buffer to prevent overflow
1873 if ( audio_used * channels + samples_needed > self->audio_buffer_size[ index ] )
1875 self->audio_buffer_size[ index ] *= 2;
1876 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] * sizeof(int16_t) );
1880 // Copy to audio buffer while resampling
1881 int16_t *source = decode_buffer;
1882 int16_t *dest = &audio_buffer[ audio_used * channels ];
1883 audio_used += audio_resample( resample, dest, source, convert_samples );
1887 // Straight copy to audio buffer
1888 memcpy( &audio_buffer[ audio_used * codec_context->channels ], decode_buffer, data_size );
1889 audio_used += convert_samples;
1893 while ( *ignore && audio_used > samples )
1896 audio_used -= samples;
1897 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) ],
1898 audio_used * sizeof( int16_t ) );
1903 // If we're behind, ignore this packet
1906 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
1907 int req_position = ( int )( timecode * fps + 0.5 );
1908 int int_position = ( int )( current_pts * fps + 0.5 );
1909 if ( context->start_time != AV_NOPTS_VALUE )
1910 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1912 if ( self->seekable && *ignore == 0 )
1914 if ( int_position < req_position )
1915 // We are behind, so skip some
1917 else if ( int_position > req_position + 2 )
1918 // We are ahead, so seek backwards some more
1919 seek_audio( self, req_position, timecode - 1.0, ignore );
1923 self->audio_used[ index ] = audio_used;
1928 /** Get the audio from a frame.
1930 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1933 producer_avformat self = mlt_frame_pop_audio( frame );
1935 pthread_mutex_lock( &self->audio_mutex );
1937 // Obtain the frame number of this frame
1938 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1940 // Calculate the real time code
1941 double real_timecode = producer_time_of_frame( self->parent, position );
1943 // Get the producer fps
1944 double fps = mlt_producer_get_fps( self->parent );
1946 // Number of frames to ignore (for ffwd)
1949 // Flag for paused (silence)
1950 int paused = seek_audio( self, position, real_timecode, &ignore );
1952 // Fetch the audio_format
1953 AVFormatContext *context = self->audio_format;
1955 // Determine the tracks to use
1956 int index = self->audio_index;
1957 int index_max = self->audio_index + 1;
1958 if ( self->audio_index == INT_MAX )
1961 index_max = context->nb_streams;
1962 *channels = self->total_channels;
1963 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
1964 *frequency = FFMAX( self->max_frequency, *frequency );
1967 // Initialize the resamplers and buffers
1968 for ( ; index < index_max; index++ )
1970 // Get codec context
1971 AVCodecContext *codec_context = self->audio_codec[ index ];
1973 if ( codec_context && !self->audio_buffer[ index ] )
1975 // Check for resample and create if necessary
1976 if ( codec_context->channels <= 2 )
1978 // Determine by how much resampling will increase number of samples
1979 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
1980 resample_factor *= (double) *frequency / codec_context->sample_rate;
1981 if ( resample_factor > self->resample_factor )
1982 self->resample_factor = resample_factor;
1984 // Create the resampler
1985 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1986 self->audio_resample[ index ] = av_audio_resample_init(
1987 self->audio_index == INT_MAX ? codec_context->channels : *channels,
1988 codec_context->channels, *frequency, codec_context->sample_rate,
1989 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1991 self->audio_resample[ index ] = audio_resample_init(
1992 self->audio_index == INT_MAX ? codec_context->channels : *channels,
1993 codec_context->channels, *frequency, codec_context->sample_rate );
1998 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2001 // Check for audio buffer and create if necessary
2002 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
2003 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] * sizeof( int16_t ) );
2005 // Check for decoder buffer and create if necessary
2006 self->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
2010 // Get the audio if required
2017 av_init_packet( &pkt );
2019 // If not resampling, give consumer more than requested.
2020 // It requested number samples based on requested frame rate.
2021 // Do not clean this up with a samples *= ...!
2022 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2023 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2025 while ( ret >= 0 && !got_audio )
2027 // Check if the buffer already contains the samples required
2028 if ( self->audio_index != INT_MAX && self->audio_used[ self->audio_index ] >= *samples && ignore == 0 )
2035 ret = av_read_frame( context, &pkt );
2037 // We only deal with audio from the selected audio index
2038 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == self->audio_index ||
2039 ( self->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2041 int channels2 = self->audio_index == INT_MAX ? self->audio_codec[pkt.stream_index]->channels : *channels;
2042 ret = decode_audio( self, &ignore, pkt, channels2, *samples, real_timecode, fps );
2044 av_free_packet( &pkt );
2046 if ( self->audio_index == INT_MAX && ret >= 0 )
2048 // Determine if there is enough audio for all streams
2050 for ( index = 0; index < context->nb_streams; index++ )
2052 if ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples )
2058 // Allocate and set the frame's audio buffer
2059 int size = *samples * *channels * sizeof(int16_t);
2060 *buffer = mlt_pool_alloc( size );
2061 *format = mlt_audio_s16;
2062 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2064 // Interleave tracks if audio_index=all
2065 if ( self->audio_index == INT_MAX )
2067 int16_t *dest = *buffer;
2069 for ( i = 0; i < *samples; i++ )
2071 for ( index = 0; index < index_max; index++ )
2072 if ( self->audio_codec[ index ] )
2074 int current_channels = self->audio_codec[ index ]->channels;
2075 int16_t *src = self->audio_buffer[ index ] + i * current_channels;
2076 memcpy( dest, src, current_channels * sizeof(int16_t) );
2077 dest += current_channels;
2080 for ( index = 0; index < index_max; index++ )
2081 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2083 int current_channels = self->audio_codec[ index ]->channels;
2084 int16_t *src = self->audio_buffer[ index ] + *samples * current_channels;
2085 self->audio_used[index] -= *samples;
2086 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof(int16_t) );
2089 // Copy a single track to the output buffer
2092 index = self->audio_index;
2094 // Now handle the audio if we have enough
2095 if ( self->audio_used[ index ] > 0 )
2097 int16_t *src = self->audio_buffer[ index ];
2098 *samples = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2099 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
2100 self->audio_used[ index ] -= *samples;
2101 memmove( src, &src[ *samples * *channels ], self->audio_used[ index ] * *channels * sizeof(int16_t) );
2105 // Otherwise fill with silence
2106 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
2108 if ( !self->audio_resample[ index ] )
2110 // TODO: uncomment and remove following line when full multi-channel support is ready
2111 // *channels = codec_context->channels;
2112 *frequency = self->audio_codec[ index ]->sample_rate;
2118 // Get silence and don't touch the context
2119 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2122 // Regardless of speed (other than paused), we expect to get the next frame
2124 self->audio_expected = position + 1;
2126 pthread_mutex_unlock( &self->audio_mutex );
2131 /** Initialize the audio codec context.
2134 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2136 // Initialise the codec if necessary
2137 if ( !self->audio_codec[ index ] )
2139 // Get codec context
2140 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2143 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2145 // If we don't have a codec and we can't initialise it, we can't do much more...
2147 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2149 // Now store the codec with its destructor
2150 if ( self->audio_codec[ index ] )
2151 avcodec_close( self->audio_codec[ index ] );
2152 self->audio_codec[ index ] = codec_context;
2156 // Remember that we can't use self later
2157 self->audio_index = -1;
2161 // Process properties as AVOptions
2162 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2164 return self->audio_codec[ index ] && self->audio_index > -1;
2167 /** Set up audio handling.
2170 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2173 mlt_producer producer = self->parent;
2175 // Get the properties
2176 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2178 // Fetch the audio format context
2179 AVFormatContext *context = self->audio_format;
2181 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2183 // Get the audio_index
2184 int index = mlt_properties_get_int( properties, "audio_index" );
2186 // Handle all audio tracks
2187 if ( self->audio_index > -1 &&
2188 mlt_properties_get( properties, "audio_index" ) &&
2189 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2192 // Reopen the file if necessary
2193 if ( !context && self->audio_index > -1 && index > -1 )
2195 mlt_events_block( properties, producer );
2196 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2197 mlt_properties_get( properties, "resource" ) );
2198 context = self->audio_format;
2199 if ( self->dummy_context )
2201 av_close_input_file( self->dummy_context );
2202 self->dummy_context = NULL;
2204 mlt_events_unblock( properties, producer );
2205 if ( self->audio_format )
2206 get_audio_streams_info( self );
2209 // Exception handling for audio_index
2210 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2212 for ( index = context->nb_streams - 1;
2213 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2215 mlt_properties_set_int( properties, "audio_index", index );
2217 if ( context && index > -1 && index < INT_MAX &&
2218 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2220 index = self->audio_index;
2221 mlt_properties_set_int( properties, "audio_index", index );
2224 // Update the audio properties if the index changed
2225 if ( context && index > -1 && index != self->audio_index )
2227 if ( self->audio_codec[ self->audio_index ] )
2230 avcodec_close( self->audio_codec[ self->audio_index ] );
2233 self->audio_codec[ self->audio_index ] = NULL;
2235 if ( self->audio_index != -1 )
2236 self->audio_index = index;
2241 if ( context && index == INT_MAX )
2243 mlt_properties_set_int( frame_properties, "frequency", self->max_frequency );
2244 mlt_properties_set_int( frame_properties, "channels", self->total_channels );
2245 for ( index = 0; index < context->nb_streams; index++ )
2247 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2248 audio_codec_init( self, index, properties );
2251 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2253 // Set the frame properties
2254 if ( index < INT_MAX )
2256 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2257 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2260 if ( context && index > -1 )
2262 // Add our audio operation
2263 mlt_frame_push_audio( frame, self );
2264 mlt_frame_push_audio( frame, producer_get_audio );
2268 /** Our get frame implementation.
2271 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2273 // Access the private data
2274 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2275 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2276 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2281 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2282 producer->child = self;
2283 self->parent = producer;
2284 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2285 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2288 // Create an empty frame
2289 *frame = mlt_frame_init( service);
2293 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2297 mlt_cache_item_close( cache_item );
2301 // Update timecode on the frame we're creating
2302 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2304 // Set the position of this producer
2305 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2308 producer_set_up_video( self, *frame );
2311 producer_set_up_audio( self, *frame );
2313 // Calculate the next timecode
2314 mlt_producer_prepare_next( producer );
2319 static void producer_avformat_close( producer_avformat self )
2321 mlt_log_debug( NULL, "producer_avformat_close\n" );
2323 av_free( self->av_frame );
2326 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2328 if ( self->audio_resample[i] )
2329 audio_resample_close( self->audio_resample[i] );
2330 mlt_pool_release( self->audio_buffer[i] );
2331 av_free( self->decode_buffer[i] );
2332 if ( self->audio_codec[i] )
2333 avcodec_close( self->audio_codec[i] );
2335 if ( self->video_codec )
2336 avcodec_close( self->video_codec );
2337 if ( self->dummy_context )
2338 av_close_input_file( self->dummy_context );
2339 if ( self->audio_format )
2340 av_close_input_file( self->audio_format );
2341 if ( self->video_format )
2342 av_close_input_file( self->video_format );
2345 vdpau_producer_close( self );
2347 if ( self->image_cache )
2348 mlt_cache_close( self->image_cache );
2349 pthread_mutex_destroy( &self->audio_mutex );
2350 pthread_mutex_destroy( &self->video_mutex );
2354 static void producer_close( mlt_producer parent )
2357 parent->close = NULL;
2358 mlt_producer_close( parent );