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