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