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