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