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