]> git.sesse.net Git - mlt/blob - src/modules/avformat/producer_avformat.c
Provide A/V sync for non-seekable sources.
[mlt] / src / modules / avformat / producer_avformat.c
1 /*
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
7  *
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.
12  *
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.
17  *
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
21  */
22
23 // MLT Header files
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>
31
32 // ffmpeg Header files
33 #include <libavformat/avformat.h>
34 #ifdef SWSCALE
35 #  include <libswscale/swscale.h>
36 #endif
37 #if LIBAVCODEC_VERSION_MAJOR > 52
38 #include <libavutil/samplefmt.h>
39 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
40 const char *avcodec_get_sample_fmt_name(int sample_fmt);
41 #endif
42 #ifdef VDPAU
43 #  include <libavcodec/vdpau.h>
44 #endif
45 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
46 #  include <libavutil/pixdesc.h>
47 #endif
48
49 // System header files
50 #include <stdlib.h>
51 #include <string.h>
52 #include <pthread.h>
53 #include <limits.h>
54
55 #if LIBAVUTIL_VERSION_INT < (50<<16)
56 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
57 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
58 #endif
59
60 #if LIBAVCODEC_VERSION_MAJOR > 52
61 #include <libavutil/opt.h>
62 #define CODEC_TYPE_VIDEO      AVMEDIA_TYPE_VIDEO
63 #define CODEC_TYPE_AUDIO      AVMEDIA_TYPE_AUDIO
64 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
65 #else
66 #include <libavcodec/opt.h>
67 #endif
68
69 #define POSITION_INITIAL (-2)
70 #define POSITION_INVALID (-1)
71
72 #define MAX_AUDIO_STREAMS (10)
73 #define MAX_VDPAU_SURFACES (10)
74
75 void avformat_lock( );
76 void avformat_unlock( );
77
78 struct producer_avformat_s
79 {
80         mlt_producer parent;
81         AVFormatContext *dummy_context;
82         AVFormatContext *audio_format;
83         AVFormatContext *video_format;
84         AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
85         AVCodecContext *video_codec;
86         AVFrame *av_frame;
87         ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
88         mlt_position audio_expected;
89         mlt_position video_expected;
90         int audio_index;
91         int video_index;
92         double start_time;
93         int first_pts;
94         int last_position;
95         int seekable;
96         int current_position;
97         mlt_position nonseek_position;
98         int got_picture;
99         int top_field_first;
100         uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
101         size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
102         uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
103         int audio_used[ MAX_AUDIO_STREAMS ];
104         int audio_streams;
105         int audio_max_stream;
106         int total_channels;
107         int max_channel;
108         int max_frequency;
109         unsigned int invalid_pts_counter;
110         double resample_factor;
111         mlt_cache image_cache;
112         int colorspace;
113         pthread_mutex_t video_mutex;
114         pthread_mutex_t audio_mutex;
115         mlt_deque apackets;
116         mlt_deque vpackets;
117         pthread_mutex_t packets_mutex;
118 #ifdef VDPAU
119         struct
120         {
121                 // from FFmpeg
122                 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
123                 
124                 // internal
125                 mlt_deque deque;
126                 int b_age;
127                 int ip_age[2];
128                 int is_decoded;
129                 uint8_t *buffer;
130         } *vdpau;
131 #endif
132 };
133 typedef struct producer_avformat_s *producer_avformat;
134
135 // Forward references.
136 static int list_components( char* file );
137 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL );
138 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
139 static void producer_avformat_close( producer_avformat );
140 static void producer_close( mlt_producer parent );
141 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
142 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
143 static void apply_properties( void *obj, mlt_properties properties, int flags );
144 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
145 static void get_audio_streams_info( producer_avformat self );
146
147 #ifdef VDPAU
148 #include "vdpau.c"
149 #endif
150
151 /** Constructor for libavformat.
152 */
153
154 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
155 {
156         if ( list_components( file ) )
157                 return NULL;
158
159         mlt_producer producer = NULL;
160
161         // Check that we have a non-NULL argument
162         if ( file )
163         {
164                 // Construct the producer
165                 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
166                 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
167
168                 // Initialise it
169                 if ( mlt_producer_init( producer, self ) == 0 )
170                 {
171                         self->parent = producer;
172
173                         // Get the properties
174                         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
175
176                         // Set the resource property (required for all producers)
177                         mlt_properties_set( properties, "resource", file );
178
179                         // Register transport implementation with the producer
180                         producer->close = (mlt_destructor) producer_close;
181
182                         // Register our get_frame implementation
183                         producer->get_frame = producer_get_frame;
184
185                         if ( strcmp( service, "avformat-novalidate" ) )
186                         {
187                                 // Open the file
188                                 if ( producer_open( self, profile, file ) != 0 )
189                                 {
190                                         // Clean up
191                                         mlt_producer_close( producer );
192                                         producer = NULL;
193                                 }
194                                 else if ( self->seekable )
195                                 {
196                                         // Close the file to release resources for large playlists - reopen later as needed
197                                         avformat_lock();
198                                         if ( self->audio_format )
199                                                 av_close_input_file( self->audio_format );
200                                         self->audio_format = NULL;
201                                         if ( self->video_format )
202                                                 av_close_input_file( self->video_format );
203                                         self->video_format = NULL;
204                                         avformat_unlock();
205                                 }
206                         }
207                         if ( producer )
208                         {
209                                 // Default the user-selectable indices from the auto-detected indices
210                                 mlt_properties_set_int( properties, "audio_index",  self->audio_index );
211                                 mlt_properties_set_int( properties, "video_index",  self->video_index );
212 #ifdef VDPAU
213                                 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
214 #endif
215                                 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
216                         }
217                 }
218         }
219         return producer;
220 }
221
222 int list_components( char* file )
223 {
224         int skip = 0;
225
226         // Report information about available demuxers and codecs as YAML Tiny
227         if ( file && strstr( file, "f-list" ) )
228         {
229                 fprintf( stderr, "---\nformats:\n" );
230                 AVInputFormat *format = NULL;
231                 while ( ( format = av_iformat_next( format ) ) )
232                         fprintf( stderr, "  - %s\n", format->name );
233                 fprintf( stderr, "...\n" );
234                 skip = 1;
235         }
236         if ( file && strstr( file, "acodec-list" ) )
237         {
238                 fprintf( stderr, "---\naudio_codecs:\n" );
239                 AVCodec *codec = NULL;
240                 while ( ( codec = av_codec_next( codec ) ) )
241                         if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
242                                 fprintf( stderr, "  - %s\n", codec->name );
243                 fprintf( stderr, "...\n" );
244                 skip = 1;
245         }
246         if ( file && strstr( file, "vcodec-list" ) )
247         {
248                 fprintf( stderr, "---\nvideo_codecs:\n" );
249                 AVCodec *codec = NULL;
250                 while ( ( codec = av_codec_next( codec ) ) )
251                         if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
252                                 fprintf( stderr, "  - %s\n", codec->name );
253                 fprintf( stderr, "...\n" );
254                 skip = 1;
255         }
256
257         return skip;
258 }
259
260 /** Find the default streams.
261 */
262
263 static mlt_properties find_default_streams( producer_avformat self )
264 {
265         int i;
266         char key[200];
267         AVMetadataTag *tag = NULL;
268         AVFormatContext *context = self->video_format;
269         mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
270
271         // Default to the first audio and video streams found
272         self->audio_index = -1;
273         self->video_index = -1;
274
275         mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
276
277         // Allow for multiple audio and video streams in the file and select first of each (if available)
278         for( i = 0; i < context->nb_streams; i++ )
279         {
280                 // Get the codec context
281                 AVStream *stream = context->streams[ i ];
282                 if ( ! stream ) continue;
283                 AVCodecContext *codec_context = stream->codec;
284                 if ( ! codec_context ) continue;
285                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
286                 if ( ! codec ) continue;
287
288                 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
289
290                 // Determine the type and obtain the first index of each type
291                 switch( codec_context->codec_type )
292                 {
293                         case CODEC_TYPE_VIDEO:
294                                 // Use first video stream
295                                 if ( self->video_index < 0 )
296                                         self->video_index = i;
297                                 mlt_properties_set( meta_media, key, "video" );
298                                 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
299 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
300                                 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
301                                 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
302                                         ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
303                                 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
304 #else
305                                 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
306 #endif
307
308 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
309                                 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
310                                 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
311 #endif
312                                 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
313                                 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
314                                                                                    ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
315                                 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
316                                 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
317                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
318                                 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
319 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
320                                 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
321                                 switch ( codec_context->colorspace )
322                                 {
323                                 case AVCOL_SPC_SMPTE240M:
324                                         mlt_properties_set_int( meta_media, key, 240 );
325                                         break;
326                                 case AVCOL_SPC_BT470BG:
327                                 case AVCOL_SPC_SMPTE170M:
328                                         mlt_properties_set_int( meta_media, key, 601 );
329                                         break;
330                                 case AVCOL_SPC_BT709:
331                                         mlt_properties_set_int( meta_media, key, 709 );
332                                         break;
333                                 default:
334                                         // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
335                                         mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
336                                         break;
337                                 }
338 #endif
339                                 break;
340                         case CODEC_TYPE_AUDIO:
341                                 // Use first audio stream
342                                 if ( self->audio_index < 0 )
343                                         self->audio_index = i;
344                                 mlt_properties_set( meta_media, key, "audio" );
345 #if LIBAVCODEC_VERSION_MAJOR > 52
346                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
347                                 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
348 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
349                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
350                                 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
351 #endif
352                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
353                                 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
354                                 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
355                                 mlt_properties_set_int( meta_media, key, codec_context->channels );
356                                 break;
357                         default:
358                                 break;
359                 }
360 //              snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
361 //              mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
362                 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
363                 mlt_properties_set( meta_media, key, codec->name );
364 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
365                 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
366                 mlt_properties_set( meta_media, key, codec->long_name );
367 #endif
368                 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
369                 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
370 //              snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
371 //              mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
372 //              snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
373 //              mlt_properties_set_int( meta_media, key, codec_context->profile );
374 //              snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
375 //              mlt_properties_set_int( meta_media, key, codec_context->level );
376
377                 // Read Metadata
378 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
379                 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
380                 {
381                         if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
382                         {
383                                 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
384                                 mlt_properties_set( meta_media, key, tag->value );
385                         }
386                 }
387 #endif
388         }
389 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
390         while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
391         {
392                 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
393                 {
394                         snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
395                         mlt_properties_set( meta_media, key, tag->value );
396                 }
397         }
398 #else
399         if ( context->title && strcmp( context->title, "" ) )
400                 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
401         if ( context->author && strcmp( context->author, "" ) )
402                 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
403         if ( context->copyright && strcmp( context->copyright, "" ) )
404                 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
405         if ( context->comment )
406                 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
407         if ( context->album )
408                 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
409         if ( context->year )
410                 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
411         if ( context->track )
412                 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
413 #endif
414
415         return meta_media;
416 }
417
418 static inline int dv_is_pal( AVPacket *pkt )
419 {
420         return pkt->data[3] & 0x80;
421 }
422
423 static int dv_is_wide( AVPacket *pkt )
424 {
425         int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
426
427         for ( ; i < pkt->size; i += 5 /* packet size */ )
428         {
429                 if ( pkt->data[ i ] == 0x61 )
430                 {
431                         uint8_t x = pkt->data[ i + 2 ] & 0x7;
432                         return ( x == 2 ) || ( x == 7 );
433                 }
434         }
435         return 0;
436 }
437
438 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
439 {
440         double aspect_ratio = 1.0;
441
442         if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
443         {
444                 if ( pkt )
445                 {
446                         if ( dv_is_pal( pkt ) )
447                         {
448                                 if ( dv_is_wide( pkt ) )
449                                 {
450                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
451                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
452                                 }
453                                 else
454                                 {
455                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
456                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
457                                 }
458                         }
459                         else
460                         {
461                                 if ( dv_is_wide( pkt ) )
462                                 {
463                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
464                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
465                                 }
466                                 else
467                                 {
468                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
469                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
470                                 }
471                         }
472                 }
473                 else
474                 {
475                         AVRational ar =
476 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
477                                 stream->sample_aspect_ratio;
478 #else
479                                 codec_context->sample_aspect_ratio;
480 #endif
481                         // Override FFmpeg's notion of DV aspect ratios, which are
482                         // based upon a width of 704. Since we do not have a normaliser
483                         // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
484                         // we just coerce the values to facilitate a passive behaviour through
485                         // the rescale normaliser when using equivalent producers and consumers.
486                         // = display_aspect / (width * height)
487                         if ( ar.num == 10 && ar.den == 11 )
488                         {
489                                 // 4:3 NTSC
490                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
491                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
492                         }
493                         else if ( ar.num == 59 && ar.den == 54 )
494                         {
495                                 // 4:3 PAL
496                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
497                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
498                         }
499                         else if ( ar.num == 40 && ar.den == 33 )
500                         {
501                                 // 16:9 NTSC
502                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
503                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
504                         }
505                         else if ( ar.num == 118 && ar.den == 81 )
506                         {
507                                 // 16:9 PAL
508                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
509                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
510                         }
511                 }
512         }
513         else
514         {
515                 AVRational codec_sar = codec_context->sample_aspect_ratio;
516                 AVRational stream_sar =
517 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
518                         stream->sample_aspect_ratio;
519 #else
520                         { 0, 1 };
521 #endif
522                 if ( codec_sar.num > 0 )
523                 {
524                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
525                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
526                 }
527                 else if ( stream_sar.num > 0 )
528                 {
529                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
530                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
531                 }
532                 else
533                 {
534                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
535                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
536                 }
537         }
538         AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
539         aspect_ratio = av_q2d( ar );
540         mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
541
542         return aspect_ratio;
543 }
544
545 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
546 {
547         if ( !URL ) return NULL;
548
549         const char *result = URL;
550         char *protocol = strdup( URL );
551         char *url = strchr( protocol, ':' );
552
553         // Only if there is not a protocol specification that avformat can handle
554 #if LIBAVFORMAT_VERSION_MAJOR > 52
555         if ( url && avio_check( URL, 0 ) < 0 )
556 #else
557         if ( url && !url_exist( URL ) )
558 #endif
559         {
560                 // Truncate protocol string
561                 url[0] = 0;
562                 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
563
564                 // Lookup the format
565                 *format = av_find_input_format( protocol );
566
567                 // Eat the format designator
568                 result = ++url;
569
570                 if ( *format )
571                 {
572                         // These are required by video4linux2 (defaults)
573                         params->width = profile->width;
574                         params->height = profile->height;
575                         params->time_base= (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
576                         params->channels = 2;
577                         params->sample_rate = 48000;
578
579                         // Parse out params
580                         url = strchr( url, '?' );
581                         while ( url )
582                         {
583                                 url[0] = 0;
584                                 char *name = strdup( ++url );
585                                 char *value = strchr( name, ':' );
586                                 if ( value )
587                                 {
588                                         value[0] = 0;
589                                         value++;
590                                         char *t = strchr( value, '&' );
591                                         if ( t )
592                                                 t[0] = 0;
593                                         if ( !strcmp( name, "frame_rate" ) )
594                                                 params->time_base.den = atoi( value );
595                                         else if ( !strcmp( name, "frame_rate_base" ) )
596                                                 params->time_base.num = atoi( value );
597                                         else if ( !strcmp( name, "sample_rate" ) )
598                                                 params->sample_rate = atoi( value );
599                                         else if ( !strcmp( name, "channel" ) )
600                                                 params->channel = atoi( value );
601                                         else if ( !strcmp( name, "channels" ) )
602                                                 params->channels = atoi( value );
603 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
604                                         else if ( !strcmp( name, "pix_fmt" ) )
605                                                 params->pix_fmt = av_get_pix_fmt( value );
606 #endif
607                                         else if ( !strcmp( name, "width" ) )
608                                                 params->width = atoi( value );
609                                         else if ( !strcmp( name, "height" ) )
610                                                 params->height = atoi( value );
611                                         else if ( !strcmp( name, "standard" ) )
612                                                 params->standard = strdup( value );
613                                 }
614                                 free( name );
615                                 url = strchr( url, '&' );
616                         }
617                 }
618         }
619         result = strdup( result );
620         free( protocol );
621         return result;
622 }
623
624 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
625 {
626         int error = 0;
627
628         // Get the properties
629         mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
630
631         AVFormatContext *format = self->video_format;
632
633         // We will treat everything with the producer fps.
634         // TODO: make this more flexible.
635         double fps = mlt_profile_fps( profile );
636
637         // Get the duration
638         if ( !mlt_properties_get_int( properties, "_length_computed" ) )
639         {
640                 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
641                 // when producer_open is called after initial call when restoring or reseting the producer.
642                 if ( format->duration != AV_NOPTS_VALUE )
643                 {
644                         // This isn't going to be accurate for all formats
645                         mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
646                         mlt_properties_set_position( properties, "out", frames - 1 );
647                         mlt_properties_set_position( properties, "length", frames );
648                         mlt_properties_set_int( properties, "_length_computed", 1 );
649                 }
650                 else
651                 {
652                         // Set live sources to run forever
653                         mlt_properties_set_position( properties, "length", INT_MAX );
654                         mlt_properties_set_position( properties, "out", INT_MAX - 1 );
655                         mlt_properties_set( properties, "eof", "loop" );
656                         mlt_properties_set_int( properties, "_length_computed", 1 );
657                 }
658         }
659
660         if ( format->start_time != AV_NOPTS_VALUE )
661                 self->start_time = format->start_time;
662
663         // Check if we're seekable
664         // avdevices are typically AVFMT_NOFILE and not seekable
665         self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
666         if ( format->pb )
667         {
668                 // protocols can indicate if they support seeking
669 #if LIBAVFORMAT_VERSION_MAJOR > 52
670                 self->seekable = format->pb->seekable;
671 #else
672                 URLContext *uc = url_fileno( format->pb );
673                 if ( uc )
674                         self->seekable = !uc->is_streamed;
675 #endif
676         }
677         if ( self->seekable )
678         {
679                 // Do a more rigourous test of seekable on a disposable context
680                 self->seekable = av_seek_frame( format, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
681                 mlt_properties_set_int( properties, "seekable", self->seekable );
682                 self->dummy_context = format;
683                 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
684                 format = self->video_format;
685                 av_find_stream_info( format );
686         }
687
688         // Fetch the width, height and aspect ratio
689         if ( self->video_index != -1 )
690         {
691                 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
692                 mlt_properties_set_int( properties, "width", codec_context->width );
693                 mlt_properties_set_int( properties, "height", codec_context->height );
694
695                 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
696                 {
697                         // Fetch the first frame of DV so we can read it directly
698                         AVPacket pkt;
699                         int ret = 0;
700                         while ( ret >= 0 )
701                         {
702                                 ret = av_read_frame( format, &pkt );
703                                 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
704                                 {
705                                         get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
706                                         break;
707                                 }
708                         }
709                 }
710                 else
711                 {
712                         get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
713                 }
714
715 #ifdef SWSCALE
716                 // Verify that we can convert this to YUV 4:2:2
717                 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
718                 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
719                         codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
720                 if ( context )
721                         sws_freeContext( context );
722                 else
723                         error = 1;
724 #endif
725         }
726         return error;
727 }
728
729 /** Open the file.
730 */
731
732 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL )
733 {
734         // Return an error code (0 == no error)
735         int error = 0;
736         mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
737
738         // Lock the service
739         pthread_mutex_init( &self->audio_mutex, NULL );
740         pthread_mutex_init( &self->video_mutex, NULL );
741         pthread_mutex_init( &self->packets_mutex, NULL );
742         mlt_events_block( properties, self->parent );
743         pthread_mutex_lock( &self->audio_mutex );
744         pthread_mutex_lock( &self->video_mutex );
745
746         // Parse URL
747         AVInputFormat *format = NULL;
748         AVFormatParameters params;
749         memset( &params, 0, sizeof(params) );
750         char *filename = parse_url( profile, URL, &format, &params );
751
752         // Now attempt to open the file or device with filename
753         error = av_open_input_file( &self->video_format, filename, format, 0, &params ) < 0;
754         if ( error )
755                 // If the URL is a network stream URL, then we probably need to open with full URL
756                 error = av_open_input_file( &self->video_format, URL, format, 0, &params ) < 0;
757
758         // Set MLT properties onto video AVFormatContext
759         if ( !error && self->video_format )
760         {
761                 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
762 #if LIBAVFORMAT_VERSION_MAJOR > 52
763                 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
764                         apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
765 #endif
766         }
767
768         // Cleanup AVFormatParameters
769         if ( params.standard )
770                 free( (void*) params.standard );
771
772         // If successful, then try to get additional info
773         if ( !error && self->video_format )
774         {
775                 // Get the stream info
776                 error = av_find_stream_info( self->video_format ) < 0;
777
778                 // Continue if no error
779                 if ( !error && self->video_format )
780                 {
781                         // Find default audio and video streams
782                         find_default_streams( self );
783                         error = get_basic_info( self, profile, filename );
784
785                         // Initialize position info
786                         self->first_pts = -1;
787                         self->last_position = POSITION_INITIAL;
788
789                         // We're going to cheat here - for seekable A/V files, we will have separate contexts
790                         // to support independent seeking of audio from video.
791                         // TODO: Is this really necessary?
792                         if ( self->audio_index != -1 && self->video_index != -1 )
793                         {
794                                 if ( self->seekable )
795                                 {
796                                         // And open again for our audio context
797                                         av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
798                                         apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
799 #if LIBAVFORMAT_VERSION_MAJOR > 52
800                                         if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
801                                                 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
802 #endif
803                                         av_find_stream_info( self->audio_format );
804                                 }
805                                 else
806                                 {
807                                         self->audio_format = self->video_format;
808                                 }
809                         }
810                         else if ( self->audio_index != -1 )
811                         {
812                                 // We only have an audio context
813                                 self->audio_format = self->video_format;
814                                 self->video_format = NULL;
815                         }
816                         else if ( self->video_index == -1 )
817                         {
818                                 // Something has gone wrong
819                                 error = -1;
820                         }
821                         if ( self->audio_format && !self->audio_streams )
822                                 get_audio_streams_info( self );
823                 }
824         }
825         if ( filename )
826                 free( filename );
827         if ( !error )
828         {
829                 self->apackets = mlt_deque_init();
830                 self->vpackets = mlt_deque_init();
831         }
832
833         if ( self->dummy_context )
834         {
835                 av_close_input_file( self->dummy_context );
836                 self->dummy_context = NULL;
837         }
838
839         // Unlock the service
840         pthread_mutex_unlock( &self->audio_mutex );
841         pthread_mutex_unlock( &self->video_mutex );
842         mlt_events_unblock( properties, self->parent );
843
844         return error;
845 }
846
847 static void reopen_video( producer_avformat self, mlt_producer producer )
848 {
849         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
850         mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
851         pthread_mutex_lock( &self->audio_mutex );
852
853         if ( self->video_codec )
854         {
855                 avformat_lock();
856                 avcodec_close( self->video_codec );
857                 avformat_unlock();
858         }
859         self->video_codec = NULL;
860         if ( self->dummy_context )
861                 av_close_input_file( self->dummy_context );
862         self->dummy_context = NULL;
863         if ( self->video_format )
864                 av_close_input_file( self->video_format );
865         self->video_format = NULL;
866
867         int audio_index = self->audio_index;
868         int video_index = self->video_index;
869
870         pthread_mutex_unlock( &self->audio_mutex );
871         pthread_mutex_unlock( &self->video_mutex );
872         producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
873                 mlt_properties_get( properties, "resource" ) );
874         pthread_mutex_lock( &self->video_mutex );
875         pthread_mutex_lock( &self->audio_mutex );
876
877         self->audio_index = audio_index;
878         if ( self->video_format && video_index > -1 )
879         {
880                 self->video_index = video_index;
881                 video_codec_init( self, video_index, properties );
882         }
883
884         pthread_mutex_unlock( &self->audio_mutex );
885         mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
886 }
887
888 static int seek_video( producer_avformat self, mlt_position position,
889         int req_position, int must_decode, int use_new_seek, int *ignore )
890 {
891         mlt_producer producer = self->parent;
892         int paused = 0;
893
894         if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
895         {
896                 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
897
898                 // Fetch the video format context
899                 AVFormatContext *context = self->video_format;
900
901                 // Get the video stream
902                 AVStream *stream = context->streams[ self->video_index ];
903
904                 // Get codec context
905                 AVCodecContext *codec_context = stream->codec;
906
907                 // We may want to use the source fps if available
908                 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
909                         mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
910
911                 if ( self->av_frame && position + 1 == self->video_expected )
912                 {
913                         // We're paused - use last image
914                         paused = 1;
915                 }
916                 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
917                 {
918                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
919                         *ignore = ( int )( ( position - self->video_expected ) / mlt_producer_get_fps( producer ) * source_fps );
920                         codec_context->skip_loop_filter = AVDISCARD_NONREF;
921                 }
922                 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
923                 {
924                         if ( use_new_seek && self->last_position == POSITION_INITIAL )
925                         {
926                                 // find first key frame
927                                 int ret = 0;
928                                 int toscan = 100;
929                                 AVPacket pkt;
930
931                                 while ( ret >= 0 && toscan-- > 0 )
932                                 {
933                                         ret = av_read_frame( context, &pkt );
934                                         if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
935                                         {
936                                                 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n", pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
937                                                 self->first_pts = pkt.pts;
938                                                 toscan = 0;
939                                         }
940                                         av_free_packet( &pkt );
941                                 }
942                                 // Rewind
943                                 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
944                         }
945
946                         // Calculate the timestamp for the requested frame
947                         int64_t timestamp;
948                         if ( use_new_seek )
949                         {
950                                 timestamp = ( req_position - 0.1 / source_fps ) /
951                                         ( av_q2d( stream->time_base ) * source_fps );
952                                 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %"PRId64" ", req_position, timestamp );
953                                 if ( self->first_pts > 0 )
954                                         timestamp += self->first_pts;
955                                 else if ( context->start_time != AV_NOPTS_VALUE )
956                                         timestamp += context->start_time;
957                         }
958                         else
959                         {
960                                 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
961                                 if ( context->start_time != AV_NOPTS_VALUE )
962                                         timestamp += context->start_time;
963                         }
964                         if ( must_decode )
965                                 timestamp -= AV_TIME_BASE;
966                         if ( timestamp < 0 )
967                                 timestamp = 0;
968                         mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %d\n",
969                                 timestamp, position, self->video_expected, self->last_position );
970
971                         // Seek to the timestamp
972                         if ( use_new_seek )
973                         {
974                                 codec_context->skip_loop_filter = AVDISCARD_NONREF;
975                                 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
976                         }
977                         else if ( req_position > 0 || self->last_position <= 0 )
978                         {
979                                 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
980                         }
981                         else
982                         {
983                                 // Re-open video stream when rewinding to beginning from somewhere else.
984                                 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
985                                 // not reliably seeking to the first frame across formats.
986                                 reopen_video( self, producer );
987                         }
988
989                         // Remove the cached info relating to the previous position
990                         self->current_position = POSITION_INVALID;
991                         self->last_position = POSITION_INVALID;
992                         av_freep( &self->av_frame );
993
994                         if ( use_new_seek )
995                         {
996                                 // flush any pictures still in decode buffer
997                                 avcodec_flush_buffers( codec_context );
998                         }
999                 }
1000         }
1001         return paused;
1002 }
1003
1004 /** Convert a frame position to a time code.
1005 */
1006
1007 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1008 {
1009         return ( double )position / mlt_producer_get_fps( producer );
1010 }
1011
1012 // Collect information about all audio streams
1013
1014 static void get_audio_streams_info( producer_avformat self )
1015 {
1016         // Fetch the audio format context
1017         AVFormatContext *context = self->audio_format;
1018         int i;
1019
1020         for ( i = 0;
1021                   i < context->nb_streams;
1022                   i++ )
1023         {
1024                 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1025                 {
1026                         AVCodecContext *codec_context = context->streams[i]->codec;
1027                         AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1028
1029                         // If we don't have a codec and we can't initialise it, we can't do much more...
1030                         avformat_lock( );
1031                         if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1032                         {
1033                                 self->audio_streams++;
1034                                 self->audio_max_stream = i;
1035                                 self->total_channels += codec_context->channels;
1036                                 if ( codec_context->channels > self->max_channel )
1037                                         self->max_channel = codec_context->channels;
1038                                 if ( codec_context->sample_rate > self->max_frequency )
1039                                         self->max_frequency = codec_context->sample_rate;
1040                                 avcodec_close( codec_context );
1041                         }
1042                         avformat_unlock( );
1043                 }
1044         }
1045         mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1046                 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1047         
1048         // Other audio-specific initializations
1049         self->resample_factor = 1.0;
1050 }
1051
1052 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1053 {
1054 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1055         int *coefficients;
1056         const int *new_coefficients;
1057         int full_range;
1058         int brightness, contrast, saturation;
1059
1060         if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1061                         &brightness, &contrast, &saturation ) != -1 )
1062         {
1063                 // Don't change these from defaults unless explicitly told to.
1064                 if ( use_full_range >= 0 )
1065                         full_range = use_full_range;
1066                 switch ( colorspace )
1067                 {
1068                 case 170:
1069                 case 470:
1070                 case 601:
1071                 case 624:
1072                         new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1073                         break;
1074                 case 240:
1075                         new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1076                         break;
1077                 case 709:
1078                         new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1079                         break;
1080                 default:
1081                         new_coefficients = coefficients;
1082                         break;
1083                 }
1084                 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1085                         brightness, contrast, saturation );
1086         }
1087 #endif
1088 }
1089
1090 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1091         mlt_image_format *format, int width, int height, int colorspace )
1092 {
1093 #ifdef SWSCALE
1094         int full_range = -1;
1095         int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
1096
1097 #ifdef USE_MMX
1098         flags |= SWS_CPU_CAPS_MMX;
1099 #endif
1100 #ifdef USE_SSE
1101         flags |= SWS_CPU_CAPS_MMX2;
1102 #endif
1103
1104         if ( pix_fmt == PIX_FMT_RGB32 )
1105         {
1106                 *format = mlt_image_rgb24a;
1107                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1108                         width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
1109                 AVPicture output;
1110                 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1111                 set_luma_transfer( context, colorspace, full_range );
1112                 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1113                         output.data, output.linesize);
1114                 sws_freeContext( context );
1115         }
1116         else if ( *format == mlt_image_yuv420p )
1117         {
1118                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1119                         width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1120                 AVPicture output;
1121                 output.data[0] = buffer;
1122                 output.data[1] = buffer + width * height;
1123                 output.data[2] = buffer + ( 5 * width * height ) / 4;
1124                 output.linesize[0] = width;
1125                 output.linesize[1] = width >> 1;
1126                 output.linesize[2] = width >> 1;
1127                 set_luma_transfer( context, colorspace, full_range );
1128                 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1129                         output.data, output.linesize);
1130                 sws_freeContext( context );
1131         }
1132         else if ( *format == mlt_image_rgb24 )
1133         {
1134                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1135                         width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1136                 AVPicture output;
1137                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1138                 set_luma_transfer( context, colorspace, full_range );
1139                 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1140                         output.data, output.linesize);
1141                 sws_freeContext( context );
1142         }
1143         else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1144         {
1145                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1146                         width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1147                 AVPicture output;
1148                 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1149                 set_luma_transfer( context, colorspace, full_range );
1150                 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1151                         output.data, output.linesize);
1152                 sws_freeContext( context );
1153         }
1154         else
1155         {
1156                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1157                         width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1158                 AVPicture output;
1159                 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1160                 set_luma_transfer( context, colorspace, full_range );
1161                 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1162                         output.data, output.linesize);
1163                 sws_freeContext( context );
1164         }
1165 #else
1166         if ( *format == mlt_image_yuv420p )
1167         {
1168                 AVPicture pict;
1169                 pict.data[0] = buffer;
1170                 pict.data[1] = buffer + width * height;
1171                 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1172                 pict.linesize[0] = width;
1173                 pict.linesize[1] = width >> 1;
1174                 pict.linesize[2] = width >> 1;
1175                 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1176         }
1177         else if ( *format == mlt_image_rgb24 )
1178         {
1179                 AVPicture output;
1180                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1181                 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1182         }
1183         else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1184         {
1185                 AVPicture output;
1186                 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1187                 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1188         }
1189         else
1190         {
1191                 AVPicture output;
1192                 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1193                 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1194         }
1195 #endif
1196 }
1197
1198 /** Allocate the image buffer and set it on the frame.
1199 */
1200
1201 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1202 {
1203         int size = 0;
1204
1205         if ( codec_context->width == 0 || codec_context->height == 0 )
1206                 return size;
1207
1208         *width = codec_context->width;
1209         *height = codec_context->height;
1210
1211         if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
1212                 size = *width * ( *height + 1 ) * 4;
1213         else
1214                 size = mlt_image_format_size( *format, *width, *height, NULL );
1215
1216         // Construct the output image
1217         *buffer = mlt_pool_alloc( size );
1218         if ( *buffer )
1219                 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1220         else
1221                 size = 0;
1222
1223         return size;
1224 }
1225
1226 /** Get an image from a frame.
1227 */
1228
1229 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1230 {
1231         // Get the producer
1232         producer_avformat self = mlt_frame_pop_service( frame );
1233         mlt_producer producer = self->parent;
1234
1235         // Get the properties from the frame
1236         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1237
1238         // Obtain the frame number of this frame
1239         mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1240
1241         // Get the producer properties
1242         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1243
1244         pthread_mutex_lock( &self->video_mutex );
1245
1246         // Fetch the video format context
1247         AVFormatContext *context = self->video_format;
1248
1249         // Get the video stream
1250         AVStream *stream = context->streams[ self->video_index ];
1251
1252         // Get codec context
1253         AVCodecContext *codec_context = stream->codec;
1254
1255         // Get the image cache
1256         if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1257                 self->image_cache = mlt_cache_init();
1258         if ( self->image_cache )
1259         {
1260                 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1261                 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1262                 if ( original )
1263                 {
1264                         // Set the resolution
1265                         *width = codec_context->width;
1266                         *height = codec_context->height;
1267
1268                         // Workaround 1088 encodings missing cropping info.
1269                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1270                                 *height = 1080;
1271
1272                         // Cache hit
1273                         int size = mlt_image_format_size( *format, *width, *height, NULL );
1274                         if ( writable )
1275                         {
1276                                 *buffer = mlt_pool_alloc( size );
1277                                 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1278                                 memcpy( *buffer, original, size );
1279                                 mlt_cache_item_close( item );
1280                         }
1281                         else
1282                         {
1283                                 *buffer = original;
1284                                 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1285                                 mlt_frame_set_image( frame, *buffer, size, NULL );
1286                         }
1287                         self->got_picture = 1;
1288
1289                         goto exit_get_image;
1290                 }
1291         }
1292         // Cache miss
1293         int image_size = 0;
1294
1295         // Packet
1296         AVPacket pkt;
1297
1298         // Special case ffwd handling
1299         int ignore = 0;
1300
1301         // We may want to use the source fps if available
1302         double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1303                 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1304
1305         // This is the physical frame position in the source
1306         int req_position = ( int )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1307
1308         // Determines if we have to decode all frames in a sequence
1309         // Temporary hack to improve intra frame only
1310         int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1311                                   strcmp( codec_context->codec->name, "dvvideo" ) &&
1312                                   strcmp( codec_context->codec->name, "huffyuv" ) &&
1313                                   strcmp( codec_context->codec->name, "mjpeg" ) &&
1314                                   strcmp( codec_context->codec->name, "rawvideo" );
1315
1316         // Turn on usage of new seek API and PTS for seeking
1317         int use_new_seek = self->seekable &&
1318                 codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1319         if ( mlt_properties_get( properties, "new_seek" ) )
1320                 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1321
1322         // Seek if necessary
1323         int paused = seek_video( self, position, req_position, must_decode, use_new_seek, &ignore );
1324
1325         // Seek might have reopened the file
1326         context = self->video_format;
1327         stream = context->streams[ self->video_index ];
1328         codec_context = stream->codec;
1329
1330         // Duplicate the last image if necessary
1331         if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture
1332                  && ( paused
1333                           || self->current_position == req_position
1334                           || ( !use_new_seek && self->current_position > req_position ) ) )
1335         {
1336                 // Duplicate it
1337                 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1338                 {
1339                         // Workaround 1088 encodings missing cropping info.
1340                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1341                                 *height = 1080;
1342 #ifdef VDPAU
1343                         if ( self->vdpau && self->vdpau->buffer )
1344                         {
1345                                 AVPicture picture;
1346                                 picture.data[0] = self->vdpau->buffer;
1347                                 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1348                                 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1349                                 picture.linesize[0] = codec_context->width;
1350                                 picture.linesize[1] = codec_context->width / 2;
1351                                 picture.linesize[2] = codec_context->width / 2;
1352                                 convert_image( (AVFrame*) &picture, *buffer,
1353                                         PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1354                         }
1355                         else
1356 #endif
1357                         convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1358                                 format, *width, *height, self->colorspace );
1359                 }
1360                 else
1361                         mlt_frame_get_image( frame, buffer, format, width, height, writable );
1362         }
1363         else
1364         {
1365                 int ret = 0;
1366                 int int_position = 0;
1367                 int decode_errors = 0;
1368                 int got_picture = 0;
1369
1370                 av_init_packet( &pkt );
1371
1372                 // Construct an AVFrame for YUV422 conversion
1373                 if ( !self->av_frame )
1374                         self->av_frame = avcodec_alloc_frame( );
1375
1376                 while( ret >= 0 && !got_picture )
1377                 {
1378                         // Read a packet
1379                         pthread_mutex_lock( &self->packets_mutex );
1380                         if ( mlt_deque_count( self->vpackets ) )
1381                         {
1382                                 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1383                                 pkt = *tmp;
1384                                 free( tmp );
1385                         }
1386                         else
1387                         {
1388                                 ret = av_read_frame( context, &pkt );
1389                                 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->audio_index )
1390                                 {
1391                                         if ( !av_dup_packet( &pkt ) )
1392                                         {
1393                                                 AVPacket *tmp = malloc( sizeof(AVPacket) );
1394                                                 *tmp = pkt;
1395                                                 mlt_deque_push_back( self->apackets, tmp );
1396                                         }
1397                                 }
1398                         }
1399                         pthread_mutex_unlock( &self->packets_mutex );
1400
1401                         // We only deal with video from the selected video_index
1402                         if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1403                         {
1404                                 // Determine time code of the packet
1405                                 if ( use_new_seek )
1406                                 {
1407                                         int64_t pts = pkt.pts;
1408                                         if ( self->first_pts > 0 )
1409                                                 pts -= self->first_pts;
1410                                         else if ( context->start_time != AV_NOPTS_VALUE )
1411                                                 pts -= context->start_time;
1412                                         int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1413                                         if ( pkt.pts == AV_NOPTS_VALUE )
1414                                         {
1415                                                 self->invalid_pts_counter++;
1416                                                 if ( self->invalid_pts_counter > 20 )
1417                                                 {
1418                                                         mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1419                                                         mlt_properties_set_int( properties, "new_seek", 0 );
1420                                                         int_position = req_position;
1421                                                         use_new_seek = 0;
1422                                                 }
1423                                         }
1424                                         else
1425                                         {
1426                                                 self->invalid_pts_counter = 0;
1427                                         }
1428                                         mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1429                                                 pkt.pts, req_position, self->current_position, int_position );
1430                                 }
1431                                 else
1432                                 {
1433                                         if ( pkt.dts != AV_NOPTS_VALUE )
1434                                         {
1435                                                 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1436                                                 if ( context->start_time != AV_NOPTS_VALUE )
1437                                                         int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1438                                                 if ( int_position == self->last_position )
1439                                                         int_position = self->last_position + 1;
1440                                         }
1441                                         mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1442                                                 pkt.dts, req_position, self->current_position, int_position );
1443                                         // Make a dumb assumption on streams that contain wild timestamps
1444                                         if ( abs( req_position - int_position ) > 999 )
1445                                         {
1446                                                 int_position = req_position;
1447                                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1448                                         }
1449                                 }
1450                                 self->last_position = int_position;
1451
1452                                 // Decode the image
1453                                 if ( must_decode || int_position >= req_position )
1454                                 {
1455 #ifdef VDPAU
1456                                         if ( g_vdpau && self->vdpau )
1457                                         {
1458                                                 if ( g_vdpau->producer != self )
1459                                                 {
1460                                                         vdpau_decoder_close();
1461                                                         vdpau_decoder_init( self );
1462                                                 }
1463                                                 if ( self->vdpau )
1464                                                         self->vdpau->is_decoded = 0;
1465                                         }
1466 #endif
1467                                         codec_context->reordered_opaque = pkt.pts;
1468                                         if ( int_position >= req_position )
1469                                                 codec_context->skip_loop_filter = AVDISCARD_NONE;
1470 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1471                                         ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1472 #else
1473                                         ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1474 #endif
1475                                         // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1476                                         if ( ret < 0 )
1477                                         {
1478                                                 if ( ++decode_errors <= 10 )
1479                                                         ret = 0;
1480                                         }
1481                                         else
1482                                         {
1483                                                 decode_errors = 0;
1484                                         }
1485                                 }
1486
1487                                 if ( got_picture )
1488                                 {
1489                                         if ( use_new_seek )
1490                                         {
1491                                                 // Determine time code of the packet
1492                                                 int64_t pts = self->av_frame->reordered_opaque;
1493                                                 if ( self->first_pts > 0 )
1494                                                         pts -= self->first_pts;
1495                                                 else if ( context->start_time != AV_NOPTS_VALUE )
1496                                                         pts -= context->start_time;
1497                                                 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1498                                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1499                                         }
1500                                         // Handle ignore
1501                                         if ( int_position < req_position )
1502                                         {
1503                                                 ignore = 0;
1504                                                 got_picture = 0;
1505                                         }
1506                                         else if ( int_position >= req_position )
1507                                         {
1508                                                 ignore = 0;
1509                                                 codec_context->skip_loop_filter = AVDISCARD_NONE;
1510                                         }
1511                                         else if ( ignore -- )
1512                                         {
1513                                                 got_picture = 0;
1514                                         }
1515                                 }
1516                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1517                         }
1518
1519                         // Now handle the picture if we have one
1520                         if ( got_picture )
1521                         {
1522                                 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1523                                 {
1524                                         // Workaround 1088 encodings missing cropping info.
1525                                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1526                                                 *height = 1080;
1527 #ifdef VDPAU
1528                                         if ( self->vdpau )
1529                                         {
1530                                                 if ( self->vdpau->is_decoded )
1531                                                 {
1532                                                         struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1533                                                         void *planes[3];
1534                                                         uint32_t pitches[3];
1535                                                         VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1536                                                         
1537                                                         if ( !self->vdpau->buffer )
1538                                                                 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1539                                                         self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1540                                                         self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1541                                                         self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1542                                                         self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1543                                                         self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1544                                                         self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1545
1546                                                         VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1547                                                         if ( status == VDP_STATUS_OK )
1548                                                         {
1549                                                                 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1550                                                                         format, *width, *height, self->colorspace );
1551                                                         }
1552                                                         else
1553                                                         {
1554                                                                 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1555                                                                 image_size = self->vdpau->is_decoded = 0;
1556                                                         }
1557                                                 }
1558                                                 else
1559                                                 {
1560                                                         mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1561                                                         image_size = got_picture = 0;
1562                                                 }
1563                                         }
1564                                         else
1565 #endif
1566                                         convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1567                                                 format, *width, *height, self->colorspace );
1568                                         self->top_field_first |= self->av_frame->top_field_first;
1569                                         self->current_position = int_position;
1570                                         self->got_picture = 1;
1571                                 }
1572                                 else
1573                                 {
1574                                         got_picture = 0;
1575                                 }
1576                         }
1577                         if ( self->seekable || pkt.stream_index != self->audio_index )
1578                                 av_free_packet( &pkt );
1579                 }
1580         }
1581
1582         if ( self->got_picture && image_size > 0 && self->image_cache )
1583         {
1584                 // Copy buffer to image cache   
1585                 uint8_t *image = mlt_pool_alloc( image_size );
1586                 memcpy( image, *buffer, image_size );
1587                 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1588         }
1589         // Try to duplicate last image if there was a decoding failure
1590         else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1591         {
1592                 // Duplicate it
1593                 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1594                 {
1595                         // Workaround 1088 encodings missing cropping info.
1596                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1597                                 *height = 1080;
1598 #ifdef VDPAU
1599                         if ( self->vdpau && self->vdpau->buffer )
1600                         {
1601                                 AVPicture picture;
1602                                 picture.data[0] = self->vdpau->buffer;
1603                                 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1604                                 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1605                                 picture.linesize[0] = codec_context->width;
1606                                 picture.linesize[1] = codec_context->width / 2;
1607                                 picture.linesize[2] = codec_context->width / 2;
1608                                 convert_image( (AVFrame*) &picture, *buffer,
1609                                         PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1610                         }
1611                         else
1612 #endif
1613                         convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1614                                 format, *width, *height, self->colorspace );
1615                         self->got_picture = 1;
1616                 }
1617                 else
1618                         mlt_frame_get_image( frame, buffer, format, width, height, writable );
1619         }
1620
1621         // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1622         self->video_expected = position + 1;
1623
1624 exit_get_image:
1625
1626         pthread_mutex_unlock( &self->video_mutex );
1627
1628         // Set the progressive flag
1629         if ( mlt_properties_get( properties, "force_progressive" ) )
1630                 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1631         else if ( self->av_frame )
1632                 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1633
1634         // Set the field order property for this frame
1635         if ( mlt_properties_get( properties, "force_tff" ) )
1636                 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1637         else
1638                 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1639
1640         // Set immutable properties of the selected track's (or overridden) source attributes.
1641         mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1642         mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1643         mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1644         mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1645
1646         return !self->got_picture;
1647 }
1648
1649 /** Process properties as AVOptions and apply to AV context obj
1650 */
1651
1652 static void apply_properties( void *obj, mlt_properties properties, int flags )
1653 {
1654         int i;
1655         int count = mlt_properties_count( properties );
1656         for ( i = 0; i < count; i++ )
1657         {
1658                 const char *opt_name = mlt_properties_get_name( properties, i );
1659                 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1660                 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1661                 {
1662                         if ( opt )
1663 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1664                                 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1665 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1666                                 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1667 #else
1668                                 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1669 #endif
1670                 }
1671         }
1672 }
1673
1674 /** Initialize the video codec context.
1675  */
1676
1677 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1678 {
1679         // Initialise the codec if necessary
1680         if ( !self->video_codec )
1681         {
1682                 // Get the video stream
1683                 AVStream *stream = self->video_format->streams[ index ];
1684
1685                 // Get codec context
1686                 AVCodecContext *codec_context = stream->codec;
1687
1688                 // Find the codec
1689                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1690 #ifdef VDPAU
1691                 if ( codec_context->codec_id == CODEC_ID_H264 )
1692                 {
1693                         if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1694                         {
1695                                 if ( vdpau_init( self ) )
1696                                 {
1697                                         self->video_codec = codec_context;
1698                                         if ( !vdpau_decoder_init( self ) )
1699                                                 vdpau_decoder_close();
1700                                 }
1701                         }
1702                         if ( !self->vdpau )
1703                                 codec = avcodec_find_decoder( codec_context->codec_id );
1704                 }
1705 #endif
1706
1707                 // Initialise multi-threading
1708                 int thread_count = mlt_properties_get_int( properties, "threads" );
1709                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1710                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1711                 if ( thread_count > 1 )
1712                         codec_context->thread_count = thread_count;
1713
1714                 // If we don't have a codec and we can't initialise it, we can't do much more...
1715                 avformat_lock( );
1716                 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1717                 {
1718                         // Now store the codec with its destructor
1719                         self->video_codec = codec_context;
1720                 }
1721                 else
1722                 {
1723                         // Remember that we can't use this later
1724                         self->video_index = -1;
1725                         avformat_unlock( );
1726                         return 0;
1727                 }
1728                 avformat_unlock( );
1729
1730                 // Process properties as AVOptions
1731                 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1732 #if LIBAVCODEC_VERSION_MAJOR > 52
1733                 if ( codec->priv_class && codec_context->priv_data )
1734                         apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1735 #endif
1736
1737                 // Reset some image properties
1738                 mlt_properties_set_int( properties, "width", self->video_codec->width );
1739                 mlt_properties_set_int( properties, "height", self->video_codec->height );
1740                 // For DV, we'll just use the saved aspect ratio
1741                 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1742                         get_aspect_ratio( properties, stream, self->video_codec, NULL );
1743
1744                 // Determine the fps first from the codec
1745                 double source_fps = (double) self->video_codec->time_base.den /
1746                                                                    ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1747                 
1748                 if ( mlt_properties_get( properties, "force_fps" ) )
1749                 {
1750                         source_fps = mlt_properties_get_double( properties, "force_fps" );
1751                         stream->time_base = av_d2q( source_fps, 1024 );
1752                         mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1753                         mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1754                 }
1755                 else
1756                 {
1757                         // If the muxer reports a frame rate different than the codec
1758 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1759                         double muxer_fps = av_q2d( stream->avg_frame_rate );
1760                         if ( isnan( muxer_fps ) || muxer_fps == 0 )
1761                                 muxer_fps = av_q2d( stream->r_frame_rate );
1762 #else
1763                         double muxer_fps = av_q2d( stream->r_frame_rate );
1764 #endif
1765                         // Choose the lesser - the wrong tends to be off by some multiple of 10
1766                         source_fps = FFMIN( source_fps, muxer_fps );
1767                         if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1768                         {
1769                                 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1770                                 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1771                         }
1772                         else if ( muxer_fps > 0 )
1773                         {
1774                                 AVRational frame_rate = stream->r_frame_rate;
1775                                 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1776                                 // avg_frame_rate gives some approximate value that does not well match the media.
1777                                 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1778                                 // results in some very choppy output, but some value slightly different works
1779                                 // great.
1780 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1781                                 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1782                                         frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1783 #endif
1784                                 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1785                                 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1786                         }
1787                         else
1788                         {
1789                                 source_fps = mlt_producer_get_fps( self->parent );
1790                                 AVRational frame_rate = av_d2q( source_fps, 255 );
1791                                 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1792                                 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1793                         }
1794                 }
1795
1796                 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1797                 if ( source_fps > 0 )
1798                         mlt_properties_set_double( properties, "source_fps", source_fps );
1799                 else
1800                         mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1801
1802                 // Set the YUV colorspace from override or detect
1803                 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1804 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)               
1805                 if ( ! self->colorspace )
1806                 {
1807                         switch ( self->video_codec->colorspace )
1808                         {
1809                         case AVCOL_SPC_SMPTE240M:
1810                                 self->colorspace = 240;
1811                                 break;
1812                         case AVCOL_SPC_BT470BG:
1813                         case AVCOL_SPC_SMPTE170M:
1814                                 self->colorspace = 601;
1815                                 break;
1816                         case AVCOL_SPC_BT709:
1817                                 self->colorspace = 709;
1818                                 break;
1819                         default:
1820                                 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1821                                 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1822                                 break;
1823                         }
1824                 }
1825 #endif
1826                 // Let apps get chosen colorspace
1827                 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1828         }
1829         return self->video_codec && self->video_index > -1;
1830 }
1831
1832 /** Set up video handling.
1833 */
1834
1835 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1836 {
1837         // Get the producer
1838         mlt_producer producer = self->parent;
1839
1840         // Get the properties
1841         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1842
1843         // Fetch the video format context
1844         AVFormatContext *context = self->video_format;
1845
1846         // Get the video_index
1847         int index = mlt_properties_get_int( properties, "video_index" );
1848
1849         // Reopen the file if necessary
1850         if ( !context && index > -1 )
1851         {
1852                 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1853                         mlt_properties_get( properties, "resource" ) );
1854                 context = self->video_format;
1855         }
1856
1857         // Exception handling for video_index
1858         if ( context && index >= (int) context->nb_streams )
1859         {
1860                 // Get the last video stream
1861                 for ( index = context->nb_streams - 1;
1862                           index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1863                           index-- );
1864                 mlt_properties_set_int( properties, "video_index", index );
1865         }
1866         if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1867         {
1868                 // Invalidate the video stream
1869                 index = -1;
1870                 mlt_properties_set_int( properties, "video_index", index );
1871         }
1872
1873         // Update the video properties if the index changed
1874         if ( index != self->video_index )
1875         {
1876                 // Reset the video properties if the index changed
1877                 self->video_index = index;
1878                 if ( self->video_codec )
1879                 {
1880                         avformat_lock();
1881                         avcodec_close( self->video_codec );
1882                         avformat_unlock();
1883                 }
1884                 self->video_codec = NULL;
1885         }
1886
1887         // Get the frame properties
1888         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1889
1890         // Get the codec
1891         if ( context && index > -1 && video_codec_init( self, index, properties ) )
1892         {
1893                 // Set the frame properties
1894                 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1895                 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1896                         force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1897
1898                 // Set the width and height
1899                 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1900                 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1901                 // real_width and real_height are deprecated in favor of meta.media.width and .height
1902                 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1903                 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1904                 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1905                 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1906                 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1907                 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1908
1909                 // Workaround 1088 encodings missing cropping info.
1910                 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1911                 {
1912                         mlt_properties_set_int( properties, "meta.media.height", 1080 );
1913                         mlt_properties_set_int( frame_properties, "real_height", 1080 );
1914                 }
1915
1916                 // Add our image operation
1917                 mlt_frame_push_service( frame, self );
1918                 mlt_frame_push_get_image( frame, producer_get_image );
1919         }
1920         else
1921         {
1922                 // If something failed, use test card image
1923                 mlt_properties_set_int( frame_properties, "test_image", 1 );
1924         }
1925 }
1926
1927 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1928 {
1929         int paused = 0;
1930
1931         // Seek if necessary
1932         if ( self->seekable && position != self->audio_expected )
1933         {
1934                 if ( position + 1 == self->audio_expected )
1935                 {
1936                         // We're paused - silence required
1937                         paused = 1;
1938                 }
1939                 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1940                 {
1941                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
1942                         *ignore = position - self->audio_expected;
1943                 }
1944                 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1945                 {
1946                         AVFormatContext *context = self->audio_format;
1947                         int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1948                         if ( context->start_time != AV_NOPTS_VALUE )
1949                                 timestamp += context->start_time;
1950                         if ( timestamp < 0 )
1951                                 timestamp = 0;
1952
1953                         // Set to the real timecode
1954                         if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1955                                 paused = 1;
1956
1957                         // Clear the usage in the audio buffer
1958                         int i = MAX_AUDIO_STREAMS + 1;
1959                         while ( --i )
1960                                 self->audio_used[i - 1] = 0;
1961                 }
1962         }
1963         return paused;
1964 }
1965
1966 static int sample_bytes( AVCodecContext *context )
1967 {
1968 #if LIBAVCODEC_VERSION_MAJOR > 52
1969         return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
1970 #else
1971         return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
1972 #endif
1973 }
1974
1975 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1976 {
1977         // Fetch the audio_format
1978         AVFormatContext *context = self->audio_format;
1979
1980         // Get the current stream index
1981         int index = pkt.stream_index;
1982
1983         // Get codec context
1984         AVCodecContext *codec_context = self->audio_codec[ index ];
1985
1986         // Obtain the resample context if it exists (not always needed)
1987         ReSampleContext *resample = self->audio_resample[ index ];
1988
1989         // Obtain the audio buffers
1990         uint8_t *audio_buffer = self->audio_buffer[ index ];
1991         uint8_t *decode_buffer = self->decode_buffer[ index ];
1992
1993         int audio_used = self->audio_used[ index ];
1994         uint8_t *ptr = pkt.data;
1995         int len = pkt.size;
1996         int ret = 0;
1997
1998         while ( ptr && ret >= 0 && len > 0 )
1999         {
2000                 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2001                 int data_size = self->audio_buffer_size[ index ];
2002
2003                 // Decode the audio
2004 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2005                 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2006 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2007                 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2008 #else
2009                 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2010 #endif
2011                 if ( ret < 0 )
2012                 {
2013                         mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2014                         break;
2015                 }
2016
2017                 pkt.size = len -= ret;
2018                 pkt.data = ptr += ret;
2019
2020                 // If decoded successfully
2021                 if ( data_size > 0 )
2022                 {
2023                         // Figure out how many samples will be needed after resampling
2024                         int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2025                         int samples_needed = self->resample_factor * convert_samples;
2026
2027                         // Resize audio buffer to prevent overflow
2028                         if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2029                         {
2030                                 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2031                                 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2032                         }
2033                         if ( resample )
2034                         {
2035                                 // Copy to audio buffer while resampling
2036                                 uint8_t *source = decode_buffer;
2037                                 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2038                                 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2039                         }
2040                         else
2041                         {
2042                                 // Straight copy to audio buffer
2043                                 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2044                                 audio_used += convert_samples;
2045                         }
2046
2047                         // Handle ignore
2048                         while ( *ignore && audio_used > samples )
2049                         {
2050                                 *ignore -= 1;
2051                                 audio_used -= samples;
2052                                 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2053                                                  audio_used * sizeof_sample );
2054                         }
2055                 }
2056         }
2057
2058         // If we're behind, ignore this packet
2059         if ( pkt.pts >= 0 )
2060         {
2061                 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
2062                 int req_position = ( int )( timecode * fps + 0.5 );
2063                 int int_position = ( int )( current_pts * fps + 0.5 );
2064                 if ( context->start_time != AV_NOPTS_VALUE )
2065                         int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
2066
2067                 if ( *ignore == 0 )
2068                 {
2069                         if ( int_position < req_position )
2070                                 // We are behind, so skip some
2071                                 *ignore = 1;
2072
2073                         // We use nb_streams in this test because the tolerance is dependent
2074                         // on the interleaving of all streams esp. when there is more than
2075                         // one audio stream.
2076                         else if ( int_position > req_position + context->nb_streams )
2077                                 // We are ahead, so seek backwards some more
2078                                 seek_audio( self, req_position, timecode - 1.0, ignore );
2079                 }
2080         }
2081
2082         self->audio_used[ index ] = audio_used;
2083
2084         return ret;
2085 }
2086
2087 /** Get the audio from a frame.
2088 */
2089 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2090 {
2091         // Get the producer
2092         producer_avformat self = mlt_frame_pop_audio( frame );
2093
2094         pthread_mutex_lock( &self->audio_mutex );
2095         
2096         // Obtain the frame number of this frame
2097         mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2098
2099         // Calculate the real time code
2100         double real_timecode = producer_time_of_frame( self->parent, position );
2101
2102         // Get the producer fps
2103         double fps = mlt_producer_get_fps( self->parent );
2104
2105         // Number of frames to ignore (for ffwd)
2106         int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2107
2108         // Flag for paused (silence)
2109         int paused = seek_audio( self, position, real_timecode, &ignore[0] );
2110
2111         // Initialize ignore for all streams from the seek return value
2112         int i = MAX_AUDIO_STREAMS;
2113         while ( i-- )
2114                 ignore[i] = ignore[0];
2115
2116         // Fetch the audio_format
2117         AVFormatContext *context = self->audio_format;
2118
2119         int sizeof_sample = sizeof( int16_t );
2120         
2121         // Determine the tracks to use
2122         int index = self->audio_index;
2123         int index_max = self->audio_index + 1;
2124         if ( self->audio_index == INT_MAX )
2125         {
2126                 index = 0;
2127                 index_max = context->nb_streams;
2128                 *channels = self->total_channels;
2129                 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2130                 *frequency = FFMAX( self->max_frequency, *frequency );
2131         }
2132
2133         // Initialize the resamplers and buffers
2134         for ( ; index < index_max; index++ )
2135         {
2136                 // Get codec context
2137                 AVCodecContext *codec_context = self->audio_codec[ index ];
2138
2139                 if ( codec_context && !self->audio_buffer[ index ] )
2140                 {
2141                         // Check for resample and create if necessary
2142                         if ( codec_context->channels <= 2 )
2143                         {
2144                                 // Determine by how much resampling will increase number of samples
2145                                 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2146                                 resample_factor *= (double) *frequency / codec_context->sample_rate;
2147                                 if ( resample_factor > self->resample_factor )
2148                                         self->resample_factor = resample_factor;
2149                                 
2150                                 // Create the resampler
2151 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2152                                 self->audio_resample[ index ] = av_audio_resample_init(
2153                                         self->audio_index == INT_MAX ? codec_context->channels : *channels,
2154                                         codec_context->channels, *frequency, codec_context->sample_rate,
2155                                         SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2156 #else
2157                                 self->audio_resample[ index ] = audio_resample_init(
2158                                         self->audio_index == INT_MAX ? codec_context->channels : *channels,
2159                                         codec_context->channels, *frequency, codec_context->sample_rate );
2160 #endif
2161                         }
2162                         else
2163                         {
2164                                 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2165                                 sizeof_sample = sample_bytes( codec_context );
2166                         }
2167
2168                         // Check for audio buffer and create if necessary
2169                         self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2170                         self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2171
2172                         // Check for decoder buffer and create if necessary
2173                         self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2174                 }
2175         }
2176
2177         // Get the audio if required
2178         if ( !paused )
2179         {
2180                 int ret = 0;
2181                 int got_audio = 0;
2182                 AVPacket pkt;
2183
2184                 av_init_packet( &pkt );
2185                 
2186                 // If not resampling, give consumer more than requested.
2187                 // It requested number samples based on requested frame rate.
2188                 // Do not clean this up with a samples *= ...!
2189                 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2190                         *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2191
2192                 while ( ret >= 0 && !got_audio )
2193                 {
2194                         // Check if the buffer already contains the samples required
2195                         if ( self->audio_index != INT_MAX &&
2196                                  self->audio_used[ self->audio_index ] >= *samples &&
2197                                  ignore[ self->audio_index ] == 0 )
2198                         {
2199                                 got_audio = 1;
2200                                 break;
2201                         }
2202                         else if ( self->audio_index == INT_MAX )
2203                         {
2204                                 // Check if there is enough audio for all streams
2205                                 got_audio = 1;
2206                                 for ( index = 0; got_audio && index < context->nb_streams; index++ )
2207                                         if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2208                                                 got_audio = 0;
2209                                 if ( got_audio )
2210                                         break;
2211                         }
2212
2213                         // Read a packet
2214                         pthread_mutex_lock( &self->packets_mutex );
2215                         if ( mlt_deque_count( self->apackets ) )
2216                         {
2217                                 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2218                                 pkt = *tmp;
2219                                 free( tmp );
2220                         }
2221                         else
2222                         {
2223                                 ret = av_read_frame( context, &pkt );
2224                                 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2225                                 {
2226                                         if ( !av_dup_packet( &pkt ) )
2227                                         {
2228                                                 AVPacket *tmp = malloc( sizeof(AVPacket) );
2229                                                 *tmp = pkt;
2230                                                 mlt_deque_push_back( self->vpackets, tmp );
2231                                         }
2232                                 }
2233                         }
2234                         pthread_mutex_unlock( &self->packets_mutex );
2235
2236                         // We only deal with audio from the selected audio index
2237                         index = pkt.stream_index;
2238                         if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2239                                  ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2240                         {
2241                                 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2242                                         self->audio_codec[index]->channels : *channels;
2243                                 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2244                         }
2245
2246                         if ( self->seekable || index != self->video_index )
2247                                 av_free_packet( &pkt );
2248
2249                 }
2250
2251                 // Set some additional return values
2252                 *format = mlt_audio_s16;
2253                 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2254                 {
2255                         index = self->audio_index;
2256                         *channels = self->audio_codec[ index ]->channels;
2257                         *frequency = self->audio_codec[ index ]->sample_rate;
2258                         *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2259                                 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2260                                 : mlt_audio_s16;
2261                         sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2262                 }
2263                 else if ( self->audio_index == INT_MAX )
2264                 {
2265                         // This only works if all audio tracks have the same sample format.
2266                         for ( index = 0; index < index_max; index++ )
2267                                 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2268                                 {
2269                                         *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2270                                                 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2271                                                 : mlt_audio_s16;
2272                                         sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2273                                         break;
2274                                 }
2275                 }
2276
2277                 // Allocate and set the frame's audio buffer
2278                 int size = mlt_audio_format_size( *format, *samples, *channels );
2279                 *buffer = mlt_pool_alloc( size );
2280                 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2281
2282                 // Interleave tracks if audio_index=all
2283                 if ( self->audio_index == INT_MAX )
2284                 {
2285                         uint8_t *dest = *buffer;
2286                         int i;
2287                         for ( i = 0; i < *samples; i++ )
2288                         {
2289                                 for ( index = 0; index < index_max; index++ )
2290                                 if ( self->audio_codec[ index ] )
2291                                 {
2292                                         int current_channels = self->audio_codec[ index ]->channels;
2293                                         uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2294                                         memcpy( dest, src, current_channels * sizeof_sample );
2295                                         dest += current_channels * sizeof_sample;
2296                                 }
2297                         }
2298                         for ( index = 0; index < index_max; index++ )
2299                         if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2300                         {
2301                                 int current_channels = self->audio_codec[ index ]->channels;
2302                                 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2303                                 self->audio_used[index] -= *samples;
2304                                 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2305                         }
2306                 }
2307                 // Copy a single track to the output buffer
2308                 else
2309                 {
2310                         index = self->audio_index;
2311
2312                         // Now handle the audio if we have enough
2313                         if ( self->audio_used[ index ] > 0 )
2314                         {
2315                                 uint8_t *src = self->audio_buffer[ index ];
2316                                 // copy samples from audio_buffer
2317                                 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2318                                 memcpy( *buffer, src, size * *channels * sizeof_sample );
2319                                 // supply the remaining requested samples as silence
2320                                 if ( *samples > self->audio_used[ index ] )
2321                                         memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2322                                 // reposition the samples within audio_buffer
2323                                 self->audio_used[ index ] -= size;
2324                                 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2325                         }
2326                         else
2327                         {
2328                                 // Otherwise fill with silence
2329                                 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2330                         }
2331                 }
2332         }
2333         else
2334         {
2335                 // Get silence and don't touch the context
2336                 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2337         }
2338         
2339         // Regardless of speed (other than paused), we expect to get the next frame
2340         if ( !paused )
2341                 self->audio_expected = position + 1;
2342
2343         pthread_mutex_unlock( &self->audio_mutex );
2344
2345         return 0;
2346 }
2347
2348 /** Initialize the audio codec context.
2349 */
2350
2351 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2352 {
2353         // Initialise the codec if necessary
2354         if ( !self->audio_codec[ index ] )
2355         {
2356                 // Get codec context
2357                 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2358
2359                 // Find the codec
2360                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2361
2362                 // If we don't have a codec and we can't initialise it, we can't do much more...
2363                 avformat_lock( );
2364                 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2365                 {
2366                         // Now store the codec with its destructor
2367                         if ( self->audio_codec[ index ] )
2368                                 avcodec_close( self->audio_codec[ index ] );
2369                         self->audio_codec[ index ] = codec_context;
2370                 }
2371                 else
2372                 {
2373                         // Remember that we can't use self later
2374                         self->audio_index = -1;
2375                 }
2376                 avformat_unlock( );
2377
2378                 // Process properties as AVOptions
2379                 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2380 #if LIBAVCODEC_VERSION_MAJOR > 52
2381                 if ( codec && codec->priv_class && codec_context->priv_data )
2382                         apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2383 #endif
2384         }
2385         return self->audio_codec[ index ] && self->audio_index > -1;
2386 }
2387
2388 /** Set up audio handling.
2389 */
2390
2391 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2392 {
2393         // Get the producer
2394         mlt_producer producer = self->parent;
2395
2396         // Get the properties
2397         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2398
2399         // Fetch the audio format context
2400         AVFormatContext *context = self->audio_format;
2401
2402         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2403
2404         // Get the audio_index
2405         int index = mlt_properties_get_int( properties, "audio_index" );
2406
2407         // Handle all audio tracks
2408         if ( self->audio_index > -1 &&
2409              mlt_properties_get( properties, "audio_index" ) &&
2410              !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2411                 index = INT_MAX;
2412
2413         // Reopen the file if necessary
2414         if ( !context && self->audio_index > -1 && index > -1 )
2415         {
2416                 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2417                         mlt_properties_get( properties, "resource" ) );
2418                 context = self->audio_format;
2419         }
2420
2421         // Exception handling for audio_index
2422         if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2423         {
2424                 for ( index = context->nb_streams - 1;
2425                           index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2426                           index-- );
2427                 mlt_properties_set_int( properties, "audio_index", index );
2428         }
2429         if ( context && index > -1 && index < INT_MAX &&
2430                  context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2431         {
2432                 index = self->audio_index;
2433                 mlt_properties_set_int( properties, "audio_index", index );
2434         }
2435
2436         // Update the audio properties if the index changed
2437         if ( context && index > -1 && index != self->audio_index )
2438         {
2439                 if ( self->audio_codec[ self->audio_index ] )
2440                 {
2441                         avformat_lock();
2442                         avcodec_close( self->audio_codec[ self->audio_index ] );
2443                         avformat_unlock();
2444                 }
2445                 self->audio_codec[ self->audio_index ] = NULL;
2446         }
2447         if ( self->audio_index != -1 )
2448                 self->audio_index = index;
2449         else
2450                 index = -1;
2451
2452         // Get the codec(s)
2453         if ( context && index == INT_MAX )
2454         {
2455                 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2456                 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2457                 for ( index = 0; index < context->nb_streams; index++ )
2458                 {
2459                         if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2460                                 audio_codec_init( self, index, properties );
2461                 }
2462         }
2463         else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2464         {
2465                 // Set the frame properties
2466                 if ( index < INT_MAX )
2467                 {
2468                         mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2469                         mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2470                 }
2471         }
2472         if ( context && index > -1 )
2473         {
2474                 // Add our audio operation
2475                 mlt_frame_push_audio( frame, self );
2476                 mlt_frame_push_audio( frame, producer_get_audio );
2477         }
2478 }
2479
2480 /** Our get frame implementation.
2481 */
2482
2483 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2484 {
2485         // Access the private data
2486         mlt_service service = MLT_PRODUCER_SERVICE( producer );
2487         mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2488         producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2489
2490         // If cache miss
2491         if ( !self )
2492         {
2493                 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2494                 producer->child = self;
2495                 self->parent = producer;
2496                 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2497                 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2498         }
2499
2500         // Create an empty frame
2501         *frame = mlt_frame_init( service);
2502         
2503         if ( *frame )
2504         {
2505                 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2506         }
2507         else
2508         {
2509                 mlt_cache_item_close( cache_item );
2510                 return 1;
2511         }
2512
2513         // Update timecode on the frame we're creating
2514         mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2515
2516         // Set the position of this producer
2517         mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2518         mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", position );
2519         
2520         // Set up the video
2521         producer_set_up_video( self, *frame );
2522
2523         // Set up the audio
2524         producer_set_up_audio( self, *frame );
2525
2526         // Calculate the next timecode
2527         mlt_producer_prepare_next( producer );
2528
2529         return 0;
2530 }
2531
2532 static void producer_avformat_close( producer_avformat self )
2533 {
2534         mlt_log_debug( NULL, "producer_avformat_close\n" );
2535
2536         // Cleanup av contexts
2537         av_free( self->av_frame );
2538         avformat_lock();
2539         int i;
2540         for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2541         {
2542                 if ( self->audio_resample[i] )
2543                         audio_resample_close( self->audio_resample[i] );
2544                 mlt_pool_release( self->audio_buffer[i] );
2545                 av_free( self->decode_buffer[i] );
2546                 if ( self->audio_codec[i] )
2547                         avcodec_close( self->audio_codec[i] );
2548         }
2549         if ( self->video_codec )
2550                 avcodec_close( self->video_codec );
2551         // Close the file
2552         if ( self->dummy_context )
2553                 av_close_input_file( self->dummy_context );
2554         if ( self->seekable && self->audio_format )
2555                 av_close_input_file( self->audio_format );
2556         if ( self->video_format )
2557                 av_close_input_file( self->video_format );
2558         avformat_unlock();
2559 #ifdef VDPAU
2560         vdpau_producer_close( self );
2561 #endif
2562         if ( self->image_cache )
2563                 mlt_cache_close( self->image_cache );
2564
2565         // Cleanup the mutexes
2566         pthread_mutex_destroy( &self->audio_mutex );
2567         pthread_mutex_destroy( &self->video_mutex );
2568         pthread_mutex_destroy( &self->packets_mutex );
2569
2570         // Cleanup the packet queues
2571         AVPacket *pkt;
2572         while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2573         {
2574                 av_free_packet( pkt );
2575                 free( pkt );
2576         }
2577         while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2578         {
2579                 av_free_packet( pkt );
2580                 free( pkt );
2581         }
2582
2583         free( self );
2584 }
2585
2586 static void producer_close( mlt_producer parent )
2587 {
2588         // Remove this instance from the cache
2589         mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2590
2591         // Close the parent
2592         parent->close = NULL;
2593         mlt_producer_close( parent );
2594
2595         // Free the memory
2596         free( parent );
2597 }