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