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>
34 #include <libavcodec/opt.h>
36 # include <libswscale/swscale.h>
38 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
39 # include "audioconvert.h"
42 #include <libavcodec/vdpau.h>
45 // System header files
51 #if LIBAVUTIL_VERSION_INT < (50<<16)
52 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
53 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
56 #define POSITION_INITIAL (-2)
57 #define POSITION_INVALID (-1)
59 #define MAX_AUDIO_STREAMS (10)
60 #define MAX_VDPAU_SURFACES (10)
62 void avformat_lock( );
63 void avformat_unlock( );
65 struct producer_avformat_s
68 AVFormatContext *dummy_context;
69 AVFormatContext *audio_format;
70 AVFormatContext *video_format;
71 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
72 AVCodecContext *video_codec;
74 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
75 mlt_position audio_expected;
76 mlt_position video_expected;
86 int16_t *audio_buffer[ MAX_AUDIO_STREAMS ];
87 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
88 int16_t *decode_buffer[ MAX_AUDIO_STREAMS ];
89 int audio_used[ MAX_AUDIO_STREAMS ];
95 unsigned int invalid_pts_counter;
96 double resample_factor;
97 mlt_cache image_cache;
103 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
114 typedef struct producer_avformat_s *producer_avformat;
116 // Forward references.
117 static int producer_open( producer_avformat this, mlt_profile profile, char *file );
118 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
119 static void producer_avformat_close( producer_avformat );
120 static void producer_close( mlt_producer parent );
121 static void producer_set_up_video( producer_avformat this, mlt_frame frame );
127 /** Constructor for libavformat.
130 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
134 // Report information about available demuxers and codecs as YAML Tiny
135 if ( file && strstr( file, "f-list" ) )
137 fprintf( stderr, "---\nformats:\n" );
138 AVInputFormat *format = NULL;
139 while ( ( format = av_iformat_next( format ) ) )
140 fprintf( stderr, " - %s\n", format->name );
141 fprintf( stderr, "...\n" );
144 if ( file && strstr( file, "acodec-list" ) )
146 fprintf( stderr, "---\naudio_codecs:\n" );
147 AVCodec *codec = NULL;
148 while ( ( codec = av_codec_next( codec ) ) )
149 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
150 fprintf( stderr, " - %s\n", codec->name );
151 fprintf( stderr, "...\n" );
154 if ( file && strstr( file, "vcodec-list" ) )
156 fprintf( stderr, "---\nvideo_codecs:\n" );
157 AVCodec *codec = NULL;
158 while ( ( codec = av_codec_next( codec ) ) )
159 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
160 fprintf( stderr, " - %s\n", codec->name );
161 fprintf( stderr, "...\n" );
165 // Check that we have a non-NULL argument
168 // Construct the producer
169 mlt_producer producer = calloc( 1, sizeof( struct mlt_producer_s ) );
170 producer_avformat this = calloc( 1, sizeof( struct producer_avformat_s ) );
173 if ( mlt_producer_init( producer, this ) == 0 )
175 this->parent = producer;
177 // Get the properties
178 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
180 // Set the resource property (required for all producers)
181 mlt_properties_set( properties, "resource", file );
183 // Register transport implementation with the producer
184 producer->close = (mlt_destructor) producer_close;
186 // Register our get_frame implementation
187 producer->get_frame = producer_get_frame;
189 if ( strcmp( service, "avformat-novalidate" ) )
192 if ( producer_open( this, profile, file ) != 0 )
195 mlt_producer_close( producer );
200 // Close the file to release resources for large playlists - reopen later as needed
202 if ( this->dummy_context )
203 av_close_input_file( this->dummy_context );
204 this->dummy_context = NULL;
205 if ( this->audio_format )
206 av_close_input_file( this->audio_format );
207 this->audio_format = NULL;
208 if ( this->video_format )
209 av_close_input_file( this->video_format );
210 this->video_format = NULL;
213 // Default the user-selectable indices from the auto-detected indices
214 mlt_properties_set_int( properties, "audio_index", this->audio_index );
215 mlt_properties_set_int( properties, "video_index", this->video_index );
218 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
220 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
226 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
228 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
236 /** Find the default streams.
239 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
244 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
246 // Allow for multiple audio and video streams in the file and select first of each (if available)
247 for( i = 0; i < context->nb_streams; i++ )
249 // Get the codec context
250 AVStream *stream = context->streams[ i ];
251 if ( ! stream ) continue;
252 AVCodecContext *codec_context = stream->codec;
253 if ( ! codec_context ) continue;
254 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
255 if ( ! codec ) continue;
257 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
259 // Determine the type and obtain the first index of each type
260 switch( codec_context->codec_type )
262 case CODEC_TYPE_VIDEO:
263 if ( *video_index < 0 )
265 mlt_properties_set( meta_media, key, "video" );
266 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
267 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
268 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
269 if (ffmpeg_fps == 0) ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
270 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
272 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
275 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
276 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
277 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
279 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
280 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
281 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
282 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
283 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
284 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
285 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
286 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
287 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
288 switch ( codec_context->colorspace )
290 case AVCOL_SPC_SMPTE240M:
291 mlt_properties_set_int( meta_media, key, 240 );
293 case AVCOL_SPC_BT470BG:
294 case AVCOL_SPC_SMPTE170M:
295 mlt_properties_set_int( meta_media, key, 601 );
297 case AVCOL_SPC_BT709:
298 mlt_properties_set_int( meta_media, key, 709 );
301 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
302 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
307 case CODEC_TYPE_AUDIO:
308 if ( *audio_index < 0 )
310 mlt_properties_set( meta_media, key, "audio" );
311 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
312 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
313 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
315 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
316 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
317 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
318 mlt_properties_set_int( meta_media, key, codec_context->channels );
323 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
324 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
325 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
326 mlt_properties_set( meta_media, key, codec->name );
327 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
328 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
329 mlt_properties_set( meta_media, key, codec->long_name );
331 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
332 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
333 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
334 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
335 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
336 // mlt_properties_set_int( meta_media, key, codec_context->profile );
337 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
338 // mlt_properties_set_int( meta_media, key, codec_context->level );
344 static inline int dv_is_pal( AVPacket *pkt )
346 return pkt->data[3] & 0x80;
349 static int dv_is_wide( AVPacket *pkt )
351 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
353 for ( ; i < pkt->size; i += 5 /* packet size */ )
355 if ( pkt->data[ i ] == 0x61 )
357 uint8_t x = pkt->data[ i + 2 ] & 0x7;
358 return ( x == 2 ) || ( x == 7 );
364 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
366 double aspect_ratio = 1.0;
368 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
372 if ( dv_is_pal( pkt ) )
374 if ( dv_is_wide( pkt ) )
376 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
377 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
381 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
382 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
387 if ( dv_is_wide( pkt ) )
389 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
390 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
394 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
395 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
402 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
403 stream->sample_aspect_ratio;
405 codec_context->sample_aspect_ratio;
407 // Override FFmpeg's notion of DV aspect ratios, which are
408 // based upon a width of 704. Since we do not have a normaliser
409 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
410 // we just coerce the values to facilitate a passive behaviour through
411 // the rescale normaliser when using equivalent producers and consumers.
412 // = display_aspect / (width * height)
413 if ( ar.num == 10 && ar.den == 11 )
416 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
417 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
419 else if ( ar.num == 59 && ar.den == 54 )
422 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
423 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
425 else if ( ar.num == 40 && ar.den == 33 )
428 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
429 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
431 else if ( ar.num == 118 && ar.den == 81 )
434 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
435 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
441 AVRational codec_sar = codec_context->sample_aspect_ratio;
442 AVRational stream_sar =
443 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
444 stream->sample_aspect_ratio;
448 if ( codec_sar.num > 0 )
450 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
451 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
453 else if ( stream_sar.num > 0 )
455 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
456 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
460 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
461 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
464 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
465 aspect_ratio = av_q2d( ar );
466 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
474 static int producer_open( producer_avformat this, mlt_profile profile, char *file )
476 // Return an error code (0 == no error)
479 // Context for avformat
480 AVFormatContext *context = NULL;
482 // Get the properties
483 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this->parent );
485 // We will treat everything with the producer fps
486 double fps = mlt_profile_fps( profile );
488 // Lock the mutex now
491 // If "MRL", then create AVInputFormat
492 AVInputFormat *format = NULL;
493 AVFormatParameters *params = NULL;
494 char *standard = NULL;
495 char *mrl = strchr( file, ':' );
497 // AV option (0 = both, 1 = video, 2 = audio)
500 // Only if there is not a protocol specification that avformat can handle
501 if ( mrl && !url_exist( file ) )
503 // 'file' becomes format abbreviation
507 format = av_find_input_format( file );
509 // Eat the format designator
515 params = calloc( sizeof( AVFormatParameters ), 1 );
517 // These are required by video4linux (defaults)
519 params->height = 480;
520 params->time_base= (AVRational){1,25};
521 // params->device = file;
522 params->channels = 2;
523 params->sample_rate = 48000;
527 mrl = strchr( file, '?' );
531 char *name = strdup( ++mrl );
532 char *value = strchr( name, ':' );
537 char *t = strchr( value, '&' );
540 if ( !strcmp( name, "frame_rate" ) )
541 params->time_base.den = atoi( value );
542 else if ( !strcmp( name, "frame_rate_base" ) )
543 params->time_base.num = atoi( value );
544 else if ( !strcmp( name, "sample_rate" ) )
545 params->sample_rate = atoi( value );
546 else if ( !strcmp( name, "channels" ) )
547 params->channels = atoi( value );
548 else if ( !strcmp( name, "width" ) )
549 params->width = atoi( value );
550 else if ( !strcmp( name, "height" ) )
551 params->height = atoi( value );
552 else if ( !strcmp( name, "standard" ) )
554 standard = strdup( value );
555 params->standard = standard;
557 else if ( !strcmp( name, "av" ) )
561 mrl = strchr( mrl, '&' );
565 // Now attempt to open the file
566 error = av_open_input_file( &context, file, format, 0, params ) < 0;
568 // Cleanup AVFormatParameters
572 // If successful, then try to get additional info
575 // Get the stream info
576 error = av_find_stream_info( context ) < 0;
578 // Continue if no error
581 // We will default to the first audio and video streams found
582 int audio_index = -1;
583 int video_index = -1;
585 // Now set properties where we can (use default unknowns if required)
586 if ( context->duration != AV_NOPTS_VALUE )
588 // This isn't going to be accurate for all formats
589 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps - 1 );
590 mlt_properties_set_position( properties, "out", frames - 1 );
591 mlt_properties_set_position( properties, "length", frames );
594 // Find default audio and video streams
595 find_default_streams( properties, context, &audio_index, &video_index );
597 if ( context->start_time != AV_NOPTS_VALUE )
598 this->start_time = context->start_time;
600 // Check if we're seekable (something funny about mpeg here :-/)
601 if ( strncmp( file, "pipe:", 5 ) &&
602 strncmp( file, "/dev/", 5 ) &&
603 strncmp( file, "http:", 5 ) &&
604 strncmp( file, "udp:", 4 ) &&
605 strncmp( file, "tcp:", 4 ) &&
606 strncmp( file, "rtsp:", 5 ) &&
607 strncmp( file, "rtp:", 4 ) )
609 this->seekable = av_seek_frame( context, -1, this->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
610 mlt_properties_set_int( properties, "seekable", this->seekable );
611 this->dummy_context = context;
612 av_open_input_file( &context, file, NULL, 0, NULL );
613 av_find_stream_info( context );
616 // Store selected audio and video indexes on properties
617 this->audio_index = audio_index;
618 this->video_index = video_index;
619 this->first_pts = -1;
620 this->last_position = POSITION_INITIAL;
622 // Fetch the width, height and aspect ratio
623 if ( video_index != -1 )
625 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
626 mlt_properties_set_int( properties, "width", codec_context->width );
627 mlt_properties_set_int( properties, "height", codec_context->height );
629 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
631 // Fetch the first frame of DV so we can read it directly
636 ret = av_read_frame( context, &pkt );
637 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
639 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, &pkt );
646 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, NULL );
649 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
650 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
652 sws_freeContext( context );
659 if ( context->title )
660 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
661 if ( context->author )
662 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
663 if ( context->copyright )
664 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
665 if ( context->comment )
666 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
667 if ( context->album )
668 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
670 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
671 if ( context->track )
672 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
674 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
675 if ( av == 0 && audio_index != -1 && video_index != -1 )
677 // We'll use the open one as our video_format
678 this->video_format = context;
680 // And open again for our audio context
681 av_open_input_file( &context, file, NULL, 0, NULL );
682 av_find_stream_info( context );
685 this->audio_format = context;
687 else if ( av != 2 && video_index != -1 )
689 // We only have a video context
690 this->video_format = context;
692 else if ( audio_index != -1 )
694 // We only have an audio context
695 this->audio_format = context;
699 // Something has gone wrong
705 // Unlock the mutex now
711 /** Convert a frame position to a time code.
714 static double producer_time_of_frame( mlt_producer this, mlt_position position )
716 return ( double )position / mlt_producer_get_fps( this );
719 // Collect information about all audio streams
721 static void get_audio_streams_info( producer_avformat this )
723 // Fetch the audio format context
724 AVFormatContext *context = this->audio_format;
728 i < context->nb_streams;
731 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
733 AVCodecContext *codec_context = context->streams[i]->codec;
734 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
736 // If we don't have a codec and we can't initialise it, we can't do much more...
738 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
740 this->audio_streams++;
741 this->audio_max_stream = i;
742 this->total_channels += codec_context->channels;
743 if ( codec_context->channels > this->max_channel )
744 this->max_channel = codec_context->channels;
745 if ( codec_context->sample_rate > this->max_frequency )
746 this->max_frequency = codec_context->sample_rate;
747 avcodec_close( codec_context );
752 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
753 this->audio_streams, this->audio_max_stream, this->total_channels, this->max_channel );
755 // Other audio-specific initializations
756 this->resample_factor = 1.0;
759 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
761 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
764 int brightness, contrast, saturation;
766 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
767 &brightness, &contrast, &saturation ) != -1 )
769 // Don't change these from defaults unless explicitly told to.
770 if ( use_full_range >= 0 )
771 full_range = use_full_range;
772 switch ( colorspace )
778 coefficients = sws_getCoefficients( SWS_CS_ITU601 );
781 coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
784 coefficients = sws_getCoefficients( SWS_CS_ITU709 );
787 sws_setColorspaceDetails( context, coefficients, full_range, coefficients, full_range,
788 brightness, contrast, saturation );
793 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
794 mlt_image_format *format, int width, int height, int colorspace )
798 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
801 flags |= SWS_CPU_CAPS_MMX;
804 flags |= SWS_CPU_CAPS_MMX2;
807 if ( pix_fmt == PIX_FMT_RGB32 )
809 *format = mlt_image_rgb24a;
810 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
811 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
813 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
814 set_luma_transfer( context, colorspace, full_range );
815 sws_scale( context, frame->data, frame->linesize, 0, height,
816 output.data, output.linesize);
817 sws_freeContext( context );
819 else if ( *format == mlt_image_yuv420p )
821 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
822 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
824 output.data[0] = buffer;
825 output.data[1] = buffer + width * height;
826 output.data[2] = buffer + ( 5 * width * height ) / 4;
827 output.linesize[0] = width;
828 output.linesize[1] = width >> 1;
829 output.linesize[2] = width >> 1;
830 set_luma_transfer( context, colorspace, full_range );
831 sws_scale( context, frame->data, frame->linesize, 0, height,
832 output.data, output.linesize);
833 sws_freeContext( context );
835 else if ( *format == mlt_image_rgb24 )
837 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
838 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
840 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
841 set_luma_transfer( context, colorspace, full_range );
842 sws_scale( context, frame->data, frame->linesize, 0, height,
843 output.data, output.linesize);
844 sws_freeContext( context );
846 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
848 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
849 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
851 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
852 set_luma_transfer( context, colorspace, full_range );
853 sws_scale( context, frame->data, frame->linesize, 0, height,
854 output.data, output.linesize);
855 sws_freeContext( context );
859 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
860 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
862 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
863 set_luma_transfer( context, colorspace, full_range );
864 sws_scale( context, frame->data, frame->linesize, 0, height,
865 output.data, output.linesize);
866 sws_freeContext( context );
869 if ( *format == mlt_image_yuv420p )
872 pict.data[0] = buffer;
873 pict.data[1] = buffer + width * height;
874 pict.data[2] = buffer + ( 5 * width * height ) / 4;
875 pict.linesize[0] = width;
876 pict.linesize[1] = width >> 1;
877 pict.linesize[2] = width >> 1;
878 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
880 else if ( *format == mlt_image_rgb24 )
883 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
884 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
886 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
889 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
890 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
895 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
896 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
901 /** Allocate the image buffer and set it on the frame.
904 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
908 if ( codec_context->width == 0 || codec_context->height == 0 )
911 *width = codec_context->width;
912 *height = codec_context->height;
914 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
915 size = *width * ( *height + 1 ) * 4;
916 else switch ( *format )
918 case mlt_image_yuv420p:
919 size = *width * 3 * ( *height + 1 ) / 2;
921 case mlt_image_rgb24:
922 size = *width * ( *height + 1 ) * 3;
924 case mlt_image_rgb24a:
925 case mlt_image_opengl:
926 size = *width * ( *height + 1 ) * 4;
929 *format = mlt_image_yuv422;
930 size = *width * ( *height + 1 ) * 2;
934 // Construct the output image
935 *buffer = mlt_pool_alloc( size );
937 mlt_properties_set_data( frame_properties, "image", *buffer, size, mlt_pool_release, NULL );
944 /** Get an image from a frame.
947 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
950 producer_avformat this = mlt_frame_pop_service( frame );
951 mlt_service_lock( MLT_PRODUCER_SERVICE(this->parent) );
952 mlt_producer producer = this->parent;
954 // Get the properties from the frame
955 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
957 // Obtain the frame number of this frame
958 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
960 // Get the producer properties
961 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
963 // Fetch the video format context
964 AVFormatContext *context = this->video_format;
966 // Get the video stream
967 AVStream *stream = context->streams[ this->video_index ];
970 AVCodecContext *codec_context = stream->codec;
972 // Get the image cache
973 if ( ! this->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
974 this->image_cache = mlt_cache_init();
975 if ( this->image_cache )
977 mlt_cache_item item = mlt_cache_get( this->image_cache, (void*) position );
978 *buffer = mlt_cache_item_data( item, (int*) format );
981 // Set the resolution
982 *width = codec_context->width;
983 *height = codec_context->height;
985 // Workaround 1088 encodings missing cropping info.
986 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
993 case mlt_image_yuv420p:
994 size = *width * 3 * ( *height + 1 ) / 2;
996 case mlt_image_rgb24:
997 size = *width * ( *height + 1 ) * 3;
999 case mlt_image_rgb24a:
1000 case mlt_image_opengl:
1001 size = *width * ( *height + 1 ) * 4;
1004 *format = mlt_image_yuv422;
1005 size = *width * ( *height + 1 ) * 2;
1008 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1009 mlt_properties_set_data( frame_properties, "image", *buffer, size, NULL, NULL );
1010 // this->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1011 this->got_picture = 1;
1013 goto exit_get_image;
1024 // Special case pause handling flag
1027 // Special case ffwd handling
1030 // We may want to use the source fps if available
1031 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1032 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1033 double fps = mlt_producer_get_fps( producer );
1035 // This is the physical frame position in the source
1036 int req_position = ( int )( position / fps * source_fps + 0.5 );
1038 // Determines if we have to decode all frames in a sequence
1039 // Temporary hack to improve intra frame only
1040 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1041 strcmp( codec_context->codec->name, "dvvideo" ) &&
1042 strcmp( codec_context->codec->name, "huffyuv" ) &&
1043 strcmp( codec_context->codec->name, "mjpeg" ) &&
1044 strcmp( codec_context->codec->name, "rawvideo" );
1046 int last_position = this->last_position;
1048 // Turn on usage of new seek API and PTS for seeking
1049 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1050 if ( mlt_properties_get( properties, "new_seek" ) )
1051 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1053 // Seek if necessary
1054 if ( position != this->video_expected || last_position < 0 )
1056 if ( this->av_frame && position + 1 == this->video_expected )
1058 // We're paused - use last image
1061 else if ( !this->seekable && position > this->video_expected && ( position - this->video_expected ) < 250 )
1063 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1064 ignore = ( int )( ( position - this->video_expected ) / fps * source_fps );
1065 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1067 else if ( this->seekable && ( position < this->video_expected || position - this->video_expected >= 12 || last_position < 0 ) )
1069 if ( use_new_seek && last_position == POSITION_INITIAL )
1071 // find first key frame
1075 while ( ret >= 0 && toscan-- > 0 )
1077 ret = av_read_frame( context, &pkt );
1078 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == this->video_index )
1080 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) );
1081 this->first_pts = pkt.pts;
1084 av_free_packet( &pkt );
1087 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1090 // Calculate the timestamp for the requested frame
1094 timestamp = ( req_position - 0.1 / source_fps ) /
1095 ( av_q2d( stream->time_base ) * source_fps );
1096 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
1097 if ( this->first_pts > 0 )
1098 timestamp += this->first_pts;
1099 else if ( context->start_time != AV_NOPTS_VALUE )
1100 timestamp += context->start_time;
1104 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1105 if ( context->start_time != AV_NOPTS_VALUE )
1106 timestamp += context->start_time;
1109 timestamp -= AV_TIME_BASE;
1110 if ( timestamp < 0 )
1112 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
1113 timestamp, position, this->video_expected, last_position );
1115 // Seek to the timestamp
1118 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1119 av_seek_frame( context, this->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1121 else if ( timestamp > 0 || last_position <= 0 )
1123 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1127 // Re-open video stream when rewinding to beginning from somewhere else.
1128 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1129 // not reliably seeking to the first frame across formats.
1130 if ( this->video_codec )
1131 avcodec_close( this->video_codec );
1132 this->video_codec = NULL;
1133 if ( this->dummy_context )
1134 av_close_input_file( this->dummy_context );
1135 this->dummy_context = NULL;
1136 if ( this->video_format )
1137 av_close_input_file( this->video_format );
1138 this->video_format = NULL;
1140 producer_set_up_video( this, frame );
1141 if ( this->video_index < 0 )
1144 context = this->video_format;
1145 stream = context->streams[ this->video_index ];
1146 codec_context = stream->codec;
1149 // Remove the cached info relating to the previous position
1150 this->current_position = POSITION_INVALID;
1151 this->last_position = POSITION_INVALID;
1152 av_freep( &this->av_frame );
1156 // flush any pictures still in decode buffer
1157 avcodec_flush_buffers( codec_context );
1162 // Duplicate the last image if necessary
1163 if ( this->av_frame && this->av_frame->linesize[0] && this->got_picture && this->seekable
1165 || this->current_position == req_position
1166 || ( !use_new_seek && this->current_position > req_position ) ) )
1169 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1171 // Workaround 1088 encodings missing cropping info.
1172 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1175 if ( this->vdpau && this->vdpau->buffer )
1178 picture.data[0] = this->vdpau->buffer;
1179 picture.data[2] = this->vdpau->buffer + codec_context->width * codec_context->height;
1180 picture.data[1] = this->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1181 picture.linesize[0] = codec_context->width;
1182 picture.linesize[1] = codec_context->width / 2;
1183 picture.linesize[2] = codec_context->width / 2;
1184 convert_image( (AVFrame*) &picture, *buffer,
1185 PIX_FMT_YUV420P, format, *width, *height, this->colorspace );
1189 convert_image( this->av_frame, *buffer, codec_context->pix_fmt,
1190 format, *width, *height, this->colorspace );
1193 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1198 int int_position = 0;
1199 int decode_errors = 0;
1200 int got_picture = 0;
1202 av_init_packet( &pkt );
1204 // Construct an AVFrame for YUV422 conversion
1205 if ( !this->av_frame )
1206 this->av_frame = avcodec_alloc_frame( );
1208 while( ret >= 0 && !got_picture )
1211 ret = av_read_frame( context, &pkt );
1213 // We only deal with video from the selected video_index
1214 if ( ret >= 0 && pkt.stream_index == this->video_index && pkt.size > 0 )
1216 // Determine time code of the packet
1219 int64_t pts = pkt.pts;
1220 if ( this->first_pts > 0 )
1221 pts -= this->first_pts;
1222 else if ( context->start_time != AV_NOPTS_VALUE )
1223 pts -= context->start_time;
1224 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1225 if ( pkt.pts == AV_NOPTS_VALUE )
1227 this->invalid_pts_counter++;
1228 if ( this->invalid_pts_counter > 20 )
1230 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1231 mlt_properties_set_int( properties, "new_seek", 0 );
1232 int_position = req_position;
1238 this->invalid_pts_counter = 0;
1240 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1241 pkt.pts, req_position, this->current_position, int_position );
1245 if ( pkt.dts != AV_NOPTS_VALUE )
1247 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1248 if ( context->start_time != AV_NOPTS_VALUE )
1249 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1250 last_position = this->last_position;
1251 if ( int_position == last_position )
1252 int_position = last_position + 1;
1256 int_position = req_position;
1258 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1259 pkt.dts, req_position, this->current_position, int_position );
1260 // Make a dumb assumption on streams that contain wild timestamps
1261 if ( abs( req_position - int_position ) > 999 )
1263 int_position = req_position;
1264 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1267 this->last_position = int_position;
1270 if ( must_decode || int_position >= req_position )
1273 if ( g_vdpau && this->vdpau )
1275 if ( g_vdpau->producer != this )
1277 vdpau_decoder_close();
1278 vdpau_decoder_init( this );
1281 this->vdpau->is_decoded = 0;
1284 codec_context->reordered_opaque = pkt.pts;
1285 if ( int_position >= req_position )
1286 codec_context->skip_loop_filter = AVDISCARD_NONE;
1287 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1288 ret = avcodec_decode_video2( codec_context, this->av_frame, &got_picture, &pkt );
1290 ret = avcodec_decode_video( codec_context, this->av_frame, &got_picture, pkt.data, pkt.size );
1292 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1295 if ( ++decode_errors <= 10 )
1308 // Determine time code of the packet
1309 int64_t pts = this->av_frame->reordered_opaque;
1310 if ( this->first_pts > 0 )
1311 pts -= this->first_pts;
1312 else if ( context->start_time != AV_NOPTS_VALUE )
1313 pts -= context->start_time;
1314 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1315 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, this->av_frame->key_frame );
1318 if ( int_position < req_position )
1323 else if ( int_position >= req_position )
1326 codec_context->skip_loop_filter = AVDISCARD_NONE;
1328 else if ( ignore -- )
1333 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1336 // Now handle the picture if we have one
1339 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1341 // Workaround 1088 encodings missing cropping info.
1342 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1347 if ( this->vdpau->is_decoded )
1349 struct vdpau_render_state *render = (struct vdpau_render_state*) this->av_frame->data[0];
1351 uint32_t pitches[3];
1352 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1354 if ( !this->vdpau->buffer )
1355 this->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1356 this->av_frame->data[0] = planes[0] = this->vdpau->buffer;
1357 this->av_frame->data[2] = planes[1] = this->vdpau->buffer + codec_context->width * codec_context->height;
1358 this->av_frame->data[1] = planes[2] = this->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1359 this->av_frame->linesize[0] = pitches[0] = codec_context->width;
1360 this->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1361 this->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1363 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1364 if ( status == VDP_STATUS_OK )
1366 convert_image( this->av_frame, *buffer, PIX_FMT_YUV420P,
1367 format, *width, *height, this->colorspace );
1371 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1372 this->vdpau->is_decoded = 0;
1377 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1383 convert_image( this->av_frame, *buffer, codec_context->pix_fmt,
1384 format, *width, *height, this->colorspace );
1385 this->top_field_first |= this->av_frame->top_field_first;
1386 this->current_position = int_position;
1387 this->got_picture = 1;
1395 av_free_packet( &pkt );
1401 if ( this->got_picture && image_size > 0 && this->image_cache )
1403 // Copy buffer to image cache
1404 uint8_t *image = mlt_pool_alloc( image_size );
1405 memcpy( image, *buffer, image_size );
1406 mlt_cache_put( this->image_cache, (void*) position, image, *format, mlt_pool_release );
1409 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1410 this->video_expected = position + 1;
1413 // Set the progressive flag
1414 if ( mlt_properties_get( properties, "force_progressive" ) )
1415 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1416 else if ( this->av_frame )
1417 mlt_properties_set_int( frame_properties, "progressive", !this->av_frame->interlaced_frame );
1419 // Set the field order property for this frame
1420 if ( mlt_properties_get( properties, "force_tff" ) )
1421 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1423 mlt_properties_set_int( frame_properties, "top_field_first", this->top_field_first );
1425 // Set immutable properties of the selected track's (or overridden) source attributes.
1426 mlt_properties_set_int( properties, "meta.media.top_field_first", this->top_field_first );
1427 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1429 mlt_service_unlock( MLT_PRODUCER_SERVICE(this->parent) );
1431 return !this->got_picture;
1434 /** Process properties as AVOptions and apply to AV context obj
1437 static void apply_properties( void *obj, mlt_properties properties, int flags )
1440 int count = mlt_properties_count( properties );
1441 for ( i = 0; i < count; i++ )
1443 const char *opt_name = mlt_properties_get_name( properties, i );
1444 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1445 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1448 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1449 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1450 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1451 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1453 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1459 /** Initialize the video codec context.
1462 static int video_codec_init( producer_avformat this, int index, mlt_properties properties )
1464 // Initialise the codec if necessary
1465 if ( !this->video_codec )
1467 // Get the video stream
1468 AVStream *stream = this->video_format->streams[ index ];
1470 // Get codec context
1471 AVCodecContext *codec_context = stream->codec;
1474 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1476 if ( codec_context->codec_id == CODEC_ID_H264 )
1478 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1480 if ( vdpau_init( this ) )
1482 this->video_codec = codec_context;
1483 if ( !vdpau_decoder_init( this ) )
1484 vdpau_decoder_close();
1488 codec = avcodec_find_decoder( codec_context->codec_id );
1492 // Initialise multi-threading
1493 int thread_count = mlt_properties_get_int( properties, "threads" );
1494 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1495 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1496 if ( thread_count > 1 )
1498 avcodec_thread_init( codec_context, thread_count );
1499 codec_context->thread_count = thread_count;
1502 // If we don't have a codec and we can't initialise it, we can't do much more...
1504 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1506 // Now store the codec with its destructor
1507 this->video_codec = codec_context;
1511 // Remember that we can't use this later
1512 this->video_index = -1;
1516 // Process properties as AVOptions
1517 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1519 // Reset some image properties
1520 mlt_properties_set_int( properties, "width", this->video_codec->width );
1521 mlt_properties_set_int( properties, "height", this->video_codec->height );
1522 // For DV, we'll just use the saved aspect ratio
1523 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1524 get_aspect_ratio( properties, stream, this->video_codec, NULL );
1526 // Determine the fps first from the codec
1527 double source_fps = (double) this->video_codec->time_base.den /
1528 ( this->video_codec->time_base.num == 0 ? 1 : this->video_codec->time_base.num );
1530 if ( mlt_properties_get( properties, "force_fps" ) )
1532 source_fps = mlt_properties_get_double( properties, "force_fps" );
1533 stream->time_base = av_d2q( source_fps, 1024 );
1534 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1535 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1539 // If the muxer reports a frame rate different than the codec
1540 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1541 double muxer_fps = av_q2d( stream->avg_frame_rate );
1542 if ( muxer_fps == 0 ) muxer_fps = av_q2d( stream->r_frame_rate );
1544 double muxer_fps = av_q2d( stream->r_frame_rate );
1546 // Choose the lesser - the wrong tends to be off by some multiple of 10
1547 source_fps = FFMIN( source_fps, muxer_fps );
1548 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1550 mlt_properties_set_int( properties, "meta.media.frame_rate_num", this->video_codec->time_base.den );
1551 mlt_properties_set_int( properties, "meta.media.frame_rate_den", this->video_codec->time_base.num == 0 ? 1 : this->video_codec->time_base.num );
1553 else if ( muxer_fps > 0 )
1555 AVRational frame_rate = stream->r_frame_rate;
1556 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1557 // avg_frame_rate gives some approximate value that does not well match the media.
1558 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1559 // results in some very choppy output, but some value slightly different works
1561 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1562 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1563 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1565 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1566 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1570 source_fps = mlt_producer_get_fps( this->parent );
1571 AVRational frame_rate = av_d2q( source_fps, 255 );
1572 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1573 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1577 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1578 if ( source_fps > 0 )
1579 mlt_properties_set_double( properties, "source_fps", source_fps );
1581 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( this->parent ) );
1583 // Set the YUV colorspace from override or detect
1584 this->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1585 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1586 if ( ! this->colorspace )
1588 switch ( this->video_codec->colorspace )
1590 case AVCOL_SPC_SMPTE240M:
1591 this->colorspace = 240;
1593 case AVCOL_SPC_BT470BG:
1594 case AVCOL_SPC_SMPTE170M:
1595 this->colorspace = 601;
1597 case AVCOL_SPC_BT709:
1598 this->colorspace = 709;
1601 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1602 this->colorspace = this->video_codec->width * this->video_codec->height > 750000 ? 709 : 601;
1607 // Let apps get chosen colorspace
1608 mlt_properties_set_int( properties, "meta.media.colorspace", this->colorspace );
1610 return this->video_codec && this->video_index > -1;
1613 /** Set up video handling.
1616 static void producer_set_up_video( producer_avformat this, mlt_frame frame )
1619 mlt_producer producer = this->parent;
1621 // Get the properties
1622 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1624 // Fetch the video format context
1625 AVFormatContext *context = this->video_format;
1627 // Get the video_index
1628 int index = mlt_properties_get_int( properties, "video_index" );
1630 // Reopen the file if necessary
1631 if ( !context && index > -1 )
1633 mlt_events_block( properties, producer );
1634 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1635 mlt_properties_get( properties, "resource" ) );
1636 context = this->video_format;
1637 if ( this->dummy_context )
1640 av_close_input_file( this->dummy_context );
1643 this->dummy_context = NULL;
1644 mlt_events_unblock( properties, producer );
1645 if ( this->audio_format )
1646 get_audio_streams_info( this );
1648 // Process properties as AVOptions
1649 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1652 // Exception handling for video_index
1653 if ( context && index >= (int) context->nb_streams )
1655 // Get the last video stream
1656 for ( index = context->nb_streams - 1;
1657 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1659 mlt_properties_set_int( properties, "video_index", index );
1661 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1663 // Invalidate the video stream
1665 mlt_properties_set_int( properties, "video_index", index );
1668 // Update the video properties if the index changed
1669 if ( index != this->video_index )
1671 // Reset the video properties if the index changed
1672 this->video_index = index;
1673 if ( this->video_codec )
1676 avcodec_close( this->video_codec );
1679 this->video_codec = NULL;
1682 // Get the frame properties
1683 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1686 if ( context && index > -1 && video_codec_init( this, index, properties ) )
1688 // Set the frame properties
1689 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1690 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1691 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1693 // Set the width and height
1694 mlt_properties_set_int( frame_properties, "width", this->video_codec->width );
1695 mlt_properties_set_int( frame_properties, "height", this->video_codec->height );
1696 // real_width and real_height are deprecated in favor of meta.media.width and .height
1697 mlt_properties_set_int( properties, "meta.media.width", this->video_codec->width );
1698 mlt_properties_set_int( properties, "meta.media.height", this->video_codec->height );
1699 mlt_properties_set_int( frame_properties, "real_width", this->video_codec->width );
1700 mlt_properties_set_int( frame_properties, "real_height", this->video_codec->height );
1701 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1702 mlt_properties_set_int( frame_properties, "colorspace", this->colorspace );
1704 // Workaround 1088 encodings missing cropping info.
1705 if ( this->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1707 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1708 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1711 // Add our image operation
1712 mlt_frame_push_service( frame, this );
1713 mlt_frame_push_get_image( frame, producer_get_image );
1717 // If something failed, use test card image
1718 mlt_properties_set_int( frame_properties, "test_image", 1 );
1722 static int seek_audio( producer_avformat this, mlt_position position, double timecode, int *ignore )
1726 // Seek if necessary
1727 if ( position != this->audio_expected )
1729 if ( position + 1 == this->audio_expected )
1731 // We're paused - silence required
1734 else if ( !this->seekable && position > this->audio_expected && ( position - this->audio_expected ) < 250 )
1736 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1737 *ignore = position - this->audio_expected;
1739 else if ( position < this->audio_expected || position - this->audio_expected >= 12 )
1741 AVFormatContext *context = this->audio_format;
1742 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1743 if ( context->start_time != AV_NOPTS_VALUE )
1744 timestamp += context->start_time;
1745 if ( timestamp < 0 )
1748 // Set to the real timecode
1750 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1754 // Clear the usage in the audio buffer
1755 int i = MAX_AUDIO_STREAMS + 1;
1757 this->audio_used[i - 1] = 0;
1763 static int decode_audio( producer_avformat this, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1765 // Fetch the audio_format
1766 AVFormatContext *context = this->audio_format;
1768 // Get the current stream index
1769 int index = pkt.stream_index;
1771 // Get codec context
1772 AVCodecContext *codec_context = this->audio_codec[ index ];
1774 // Obtain the resample context if it exists (not always needed)
1775 ReSampleContext *resample = this->audio_resample[ index ];
1777 // Obtain the audio buffers
1778 int16_t *audio_buffer = this->audio_buffer[ index ];
1779 int16_t *decode_buffer = this->decode_buffer[ index ];
1781 int audio_used = this->audio_used[ index ];
1782 uint8_t *ptr = pkt.data;
1786 while ( ptr && ret >= 0 && len > 0 )
1788 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1791 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1792 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, &pkt );
1793 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1794 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1796 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1800 mlt_log_warning( MLT_PRODUCER_SERVICE(this->parent), "audio decoding error %d\n", ret );
1804 pkt.size = len -= ret;
1805 pkt.data = ptr += ret;
1807 // If decoded successfully
1808 if ( data_size > 0 )
1810 // Figure out how many samples will be needed after resampling
1811 int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1812 int samples_needed = this->resample_factor * convert_samples + 1;
1814 // Resize audio buffer to prevent overflow
1815 if ( audio_used * channels + samples_needed > this->audio_buffer_size[ index ] )
1817 this->audio_buffer_size[ index ] *= 2;
1818 audio_buffer = this->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, this->audio_buffer_size[ index ] * sizeof(int16_t) );
1822 // Copy to audio buffer while resampling
1823 int16_t *source = decode_buffer;
1824 int16_t *dest = &audio_buffer[ audio_used * channels ];
1826 audio_used += audio_resample( resample, dest, source, convert_samples );
1831 // Straight copy to audio buffer
1832 memcpy( &audio_buffer[ audio_used * codec_context->channels ], decode_buffer, data_size );
1833 audio_used += convert_samples;
1837 while ( *ignore && audio_used > samples )
1840 audio_used -= samples;
1841 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) ],
1842 audio_used * sizeof( int16_t ) );
1847 // If we're behind, ignore this packet
1850 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
1851 int req_position = ( int )( timecode * fps + 0.5 );
1852 int int_position = ( int )( current_pts * fps + 0.5 );
1853 if ( context->start_time != AV_NOPTS_VALUE )
1854 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1856 if ( this->seekable && *ignore == 0 )
1858 if ( int_position < req_position )
1859 // We are behind, so skip some
1861 else if ( int_position > req_position + 2 )
1862 // We are ahead, so seek backwards some more
1863 seek_audio( this, req_position, timecode - 1.0, ignore );
1867 this->audio_used[ index ] = audio_used;
1872 /** Get the audio from a frame.
1875 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1878 producer_avformat this = mlt_frame_pop_audio( frame );
1880 mlt_service_lock( MLT_PRODUCER_SERVICE(this->parent) );
1882 // Obtain the frame number of this frame
1883 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1885 // Calculate the real time code
1886 double real_timecode = producer_time_of_frame( this->parent, position );
1888 // Get the producer fps
1889 double fps = mlt_producer_get_fps( this->parent );
1891 // Number of frames to ignore (for ffwd)
1894 // Flag for paused (silence)
1895 int paused = seek_audio( this, position, real_timecode, &ignore );
1897 // Fetch the audio_format
1898 AVFormatContext *context = this->audio_format;
1900 // Determine the tracks to use
1901 int index = this->audio_index;
1902 int index_max = this->audio_index + 1;
1903 if ( this->audio_index == INT_MAX )
1906 index_max = context->nb_streams;
1907 *channels = this->total_channels;
1908 *frequency = this->max_frequency;
1911 // Initialize the resamplers and buffers
1912 for ( ; index < index_max; index++ )
1914 // Get codec context
1915 AVCodecContext *codec_context = this->audio_codec[ index ];
1917 if ( codec_context && !this->audio_buffer[ index ] )
1919 // Check for resample and create if necessary
1920 if ( codec_context->channels <= 2 )
1922 // Determine by how much resampling will increase number of samples
1923 double resample_factor = this->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
1924 resample_factor *= (double) *frequency / codec_context->sample_rate;
1925 if ( resample_factor > this->resample_factor )
1926 this->resample_factor = resample_factor;
1928 // Create the resampler
1929 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1930 this->audio_resample[ index ] = av_audio_resample_init(
1931 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1932 codec_context->channels, *frequency, codec_context->sample_rate,
1933 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1935 this->audio_resample[ index ] = audio_resample_init(
1936 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1937 codec_context->channels, *frequency, codec_context->sample_rate );
1942 codec_context->request_channels = this->audio_index == INT_MAX ? codec_context->channels : *channels;
1945 // Check for audio buffer and create if necessary
1946 this->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1947 this->audio_buffer[ index ] = mlt_pool_alloc( this->audio_buffer_size[ index ] * sizeof( int16_t ) );
1949 // Check for decoder buffer and create if necessary
1950 this->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1954 // Get the audio if required
1961 av_init_packet( &pkt );
1963 // If not resampling, give consumer more than requested.
1964 // It requested number samples based on requested frame rate.
1965 // Do not clean this up with a samples *= ...!
1966 if ( this->audio_index != INT_MAX && ! this->audio_resample[ this->audio_index ] )
1967 *samples = *samples * this->audio_codec[ this->audio_index ]->sample_rate / *frequency;
1969 while ( ret >= 0 && !got_audio )
1971 // Check if the buffer already contains the samples required
1972 if ( this->audio_index != INT_MAX && this->audio_used[ this->audio_index ] >= *samples && ignore == 0 )
1980 ret = av_read_frame( context, &pkt );
1983 // We only deal with audio from the selected audio index
1984 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == this->audio_index ||
1985 ( this->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
1987 int channels2 = this->audio_index == INT_MAX ? this->audio_codec[pkt.stream_index]->channels : *channels;
1988 ret = decode_audio( this, &ignore, pkt, channels2, *samples, real_timecode, fps );
1990 av_free_packet( &pkt );
1992 if ( this->audio_index == INT_MAX && ret >= 0 )
1994 // Determine if there is enough audio for all streams
1996 for ( index = 0; index < context->nb_streams; index++ )
1998 if ( this->audio_codec[ index ] && this->audio_used[ index ] < *samples )
2004 // Allocate and set the frame's audio buffer
2005 int size = *samples * *channels * sizeof(int16_t);
2006 *buffer = mlt_pool_alloc( size );
2007 *format = mlt_audio_s16;
2008 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2010 // Interleave tracks if audio_index=all
2011 if ( this->audio_index == INT_MAX )
2013 int16_t *dest = *buffer;
2015 for ( i = 0; i < *samples; i++ )
2017 for ( index = 0; index < index_max; index++ )
2018 if ( this->audio_codec[ index ] )
2020 int current_channels = this->audio_codec[ index ]->channels;
2021 int16_t *src = this->audio_buffer[ index ] + i * current_channels;
2022 memcpy( dest, src, current_channels * sizeof(int16_t) );
2023 dest += current_channels;
2026 for ( index = 0; index < index_max; index++ )
2027 if ( this->audio_codec[ index ] && this->audio_used[ index ] >= *samples )
2029 int current_channels = this->audio_codec[ index ]->channels;
2030 int16_t *src = this->audio_buffer[ index ] + *samples * current_channels;
2031 this->audio_used[index] -= *samples;
2032 memmove( this->audio_buffer[ index ], src, this->audio_used[ index ] * current_channels * sizeof(int16_t) );
2035 // Copy a single track to the output buffer
2038 index = this->audio_index;
2040 // Now handle the audio if we have enough
2041 if ( this->audio_used[ index ] > 0 )
2043 int16_t *src = this->audio_buffer[ index ];
2044 *samples = this->audio_used[ index ] < *samples ? this->audio_used[ index ] : *samples;
2045 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
2046 this->audio_used[ index ] -= *samples;
2047 memmove( src, &src[ *samples * *channels ], this->audio_used[ index ] * *channels * sizeof(int16_t) );
2051 // Otherwise fill with silence
2052 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
2054 if ( !this->audio_resample[ index ] )
2056 // TODO: uncomment and remove following line when full multi-channel support is ready
2057 // *channels = codec_context->channels;
2058 *frequency = this->audio_codec[ index ]->sample_rate;
2064 // Get silence and don't touch the context
2065 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2068 // Regardless of speed (other than paused), we expect to get the next frame
2070 this->audio_expected = position + 1;
2072 mlt_service_unlock( MLT_PRODUCER_SERVICE(this->parent) );
2077 /** Initialize the audio codec context.
2080 static int audio_codec_init( producer_avformat this, int index, mlt_properties properties )
2082 // Initialise the codec if necessary
2083 if ( !this->audio_codec[ index ] )
2085 // Get codec context
2086 AVCodecContext *codec_context = this->audio_format->streams[index]->codec;
2089 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2091 // If we don't have a codec and we can't initialise it, we can't do much more...
2093 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2095 // Now store the codec with its destructor
2096 if ( this->audio_codec[ index ] )
2097 avcodec_close( this->audio_codec[ index ] );
2098 this->audio_codec[ index ] = codec_context;
2102 // Remember that we can't use this later
2103 this->audio_index = -1;
2107 // Process properties as AVOptions
2108 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2110 return this->audio_codec[ index ] && this->audio_index > -1;
2113 /** Set up audio handling.
2116 static void producer_set_up_audio( producer_avformat this, mlt_frame frame )
2119 mlt_producer producer = this->parent;
2121 // Get the properties
2122 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2124 // Fetch the audio format context
2125 AVFormatContext *context = this->audio_format;
2127 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2129 // Get the audio_index
2130 int index = mlt_properties_get_int( properties, "audio_index" );
2132 // Handle all audio tracks
2133 if ( this->audio_index > -1 &&
2134 mlt_properties_get( properties, "audio_index" ) &&
2135 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2138 // Reopen the file if necessary
2139 if ( !context && this->audio_index > -1 && index > -1 )
2141 mlt_events_block( properties, producer );
2142 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2143 mlt_properties_get( properties, "resource" ) );
2144 context = this->audio_format;
2145 if ( this->dummy_context )
2148 av_close_input_file( this->dummy_context );
2151 this->dummy_context = NULL;
2152 mlt_events_unblock( properties, producer );
2153 get_audio_streams_info( this );
2156 // Exception handling for audio_index
2157 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2159 for ( index = context->nb_streams - 1;
2160 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2162 mlt_properties_set_int( properties, "audio_index", index );
2164 if ( context && index > -1 && index < INT_MAX &&
2165 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2167 index = this->audio_index;
2168 mlt_properties_set_int( properties, "audio_index", index );
2171 // Update the audio properties if the index changed
2172 if ( context && index > -1 && index != this->audio_index )
2174 if ( this->audio_codec[ this->audio_index ] )
2177 avcodec_close( this->audio_codec[ this->audio_index ] );
2180 this->audio_codec[ this->audio_index ] = NULL;
2182 if ( this->audio_index != -1 )
2183 this->audio_index = index;
2188 if ( context && index == INT_MAX )
2190 mlt_properties_set_int( frame_properties, "frequency", this->max_frequency );
2191 mlt_properties_set_int( frame_properties, "channels", this->total_channels );
2192 for ( index = 0; index < context->nb_streams; index++ )
2194 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2195 audio_codec_init( this, index, properties );
2198 else if ( context && index > -1 && audio_codec_init( this, index, properties ) )
2200 // Set the frame properties
2201 if ( index < INT_MAX )
2203 mlt_properties_set_int( frame_properties, "frequency", this->audio_codec[ index ]->sample_rate );
2204 mlt_properties_set_int( frame_properties, "channels", this->audio_codec[ index ]->channels );
2207 if ( context && index > -1 )
2209 // Add our audio operation
2210 mlt_frame_push_audio( frame, this );
2211 mlt_frame_push_audio( frame, producer_get_audio );
2215 /** Our get frame implementation.
2218 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2220 // Access the private data
2221 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2222 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2223 producer_avformat this = mlt_cache_item_data( cache_item, NULL );
2228 this = calloc( 1, sizeof( struct producer_avformat_s ) );
2229 producer->child = this;
2230 this->parent = producer;
2231 mlt_service_cache_put( service, "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
2232 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2235 // Create an empty frame
2236 *frame = mlt_frame_init( service);
2240 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2244 mlt_cache_item_close( cache_item );
2248 // Update timecode on the frame we're creating
2249 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2251 // Set the position of this producer
2252 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2255 producer_set_up_video( this, *frame );
2258 producer_set_up_audio( this, *frame );
2260 // Calculate the next timecode
2261 mlt_producer_prepare_next( producer );
2266 static void producer_avformat_close( producer_avformat this )
2268 mlt_log_debug( NULL, "producer_avformat_close\n" );
2270 av_free( this->av_frame );
2273 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2275 if ( this->audio_resample[i] )
2276 audio_resample_close( this->audio_resample[i] );
2277 mlt_pool_release( this->audio_buffer[i] );
2278 av_free( this->decode_buffer[i] );
2279 if ( this->audio_codec[i] )
2280 avcodec_close( this->audio_codec[i] );
2282 if ( this->video_codec )
2283 avcodec_close( this->video_codec );
2284 if ( this->dummy_context )
2285 av_close_input_file( this->dummy_context );
2286 if ( this->audio_format )
2287 av_close_input_file( this->audio_format );
2288 if ( this->video_format )
2289 av_close_input_file( this->video_format );
2292 vdpau_producer_close( this );
2294 if ( this->image_cache )
2295 mlt_cache_close( this->image_cache );
2299 static void producer_close( mlt_producer parent )
2302 parent->close = NULL;
2303 mlt_producer_close( parent );