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