]> git.sesse.net Git - mlt/blob - src/modules/avformat/producer_avformat.c
14e1083ba9841c02d3e96b14c50fe2bda110367a
[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_U8:
1261                 return mlt_audio_u8;
1262         case AV_SAMPLE_FMT_S16:
1263                 return mlt_audio_s16;
1264         case AV_SAMPLE_FMT_S32:
1265                 return mlt_audio_s32le;
1266         case AV_SAMPLE_FMT_FLT:
1267                 return mlt_audio_f32le;
1268         // planar - this producer converts planar to interleaved
1269 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1270         case AV_SAMPLE_FMT_U8P:
1271                 return mlt_audio_u8;
1272         case AV_SAMPLE_FMT_S16P:
1273                 return mlt_audio_s16;
1274         case AV_SAMPLE_FMT_S32P:
1275                 return mlt_audio_s32le;
1276         case AV_SAMPLE_FMT_FLTP:
1277                 return mlt_audio_f32le;
1278 #endif
1279         default:
1280                 return mlt_audio_none;
1281         }
1282 }
1283
1284 static void convert_image( producer_avformat self, AVFrame *frame, uint8_t *buffer, int pix_fmt,
1285         mlt_image_format *format, int width, int height, uint8_t **alpha )
1286 {
1287 #ifdef SWSCALE
1288         int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1289
1290 #ifdef USE_MMX
1291         flags |= SWS_CPU_CAPS_MMX;
1292 #endif
1293 #ifdef USE_SSE
1294         flags |= SWS_CPU_CAPS_MMX2;
1295 #endif
1296
1297         // extract alpha from planar formats
1298         if ( ( pix_fmt == PIX_FMT_YUVA420P
1299 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1300                         || pix_fmt == PIX_FMT_YUVA444P
1301 #endif
1302                         ) &&
1303                 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1304                 frame->data[3] && frame->linesize[3] )
1305         {
1306                 int i;
1307                 uint8_t *src, *dst;
1308
1309                 dst = *alpha = mlt_pool_alloc( width * height );
1310                 src = frame->data[3];
1311
1312                 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1313                         memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1314         }
1315
1316         if ( *format == mlt_image_yuv420p )
1317         {
1318                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1319                         width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1320                 AVPicture output;
1321                 output.data[0] = buffer;
1322                 output.data[1] = buffer + width * height;
1323                 output.data[2] = buffer + ( 5 * width * height ) / 4;
1324                 output.linesize[0] = width;
1325                 output.linesize[1] = width >> 1;
1326                 output.linesize[2] = width >> 1;
1327                 set_luma_transfer( context, self->colorspace, -1 );
1328                 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1329                         output.data, output.linesize);
1330                 sws_freeContext( context );
1331         }
1332         else if ( *format == mlt_image_rgb24 )
1333         {
1334                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1335                         width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1336                 AVPicture output;
1337                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1338                 set_luma_transfer( context, self->colorspace, self->full_luma );
1339                 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1340                         output.data, output.linesize);
1341                 sws_freeContext( context );
1342         }
1343         else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1344         {
1345                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1346                         width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1347                 AVPicture output;
1348                 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1349                 set_luma_transfer( context, self->colorspace, self->full_luma );
1350                 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1351                         output.data, output.linesize);
1352                 sws_freeContext( context );
1353         }
1354         else
1355         {
1356                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1357                         width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1358                 AVPicture output;
1359                 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1360                 set_luma_transfer( context, self->colorspace, -1 );
1361                 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1362                         output.data, output.linesize);
1363                 sws_freeContext( context );
1364         }
1365 #else
1366         if ( *format == mlt_image_yuv420p )
1367         {
1368                 AVPicture pict;
1369                 pict.data[0] = buffer;
1370                 pict.data[1] = buffer + width * height;
1371                 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1372                 pict.linesize[0] = width;
1373                 pict.linesize[1] = width >> 1;
1374                 pict.linesize[2] = width >> 1;
1375                 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1376         }
1377         else if ( *format == mlt_image_rgb24 )
1378         {
1379                 AVPicture output;
1380                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1381                 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1382         }
1383         else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1384         {
1385                 AVPicture output;
1386                 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1387                 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1388         }
1389         else
1390         {
1391                 AVPicture output;
1392                 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1393                 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1394         }
1395 #endif
1396 }
1397
1398 /** Allocate the image buffer and set it on the frame.
1399 */
1400
1401 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1402 {
1403         int size = 0;
1404
1405         if ( codec_context->width == 0 || codec_context->height == 0 )
1406                 return size;
1407         *width = codec_context->width;
1408         *height = codec_context->height;
1409         size = mlt_image_format_size( *format, *width, *height, NULL );
1410         *buffer = mlt_pool_alloc( size );
1411         if ( *buffer )
1412                 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1413         else
1414                 size = 0;
1415
1416         return size;
1417 }
1418
1419 /** Get an image from a frame.
1420 */
1421
1422 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1423 {
1424         // Get the producer
1425         producer_avformat self = mlt_frame_pop_service( frame );
1426         mlt_producer producer = self->parent;
1427
1428         // Get the properties from the frame
1429         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1430
1431         // Obtain the frame number of this frame
1432         mlt_position position = mlt_frame_original_position( frame );
1433
1434         // Get the producer properties
1435         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1436
1437         pthread_mutex_lock( &self->video_mutex );
1438
1439         // Fetch the video format context
1440         AVFormatContext *context = self->video_format;
1441
1442         // Get the video stream
1443         AVStream *stream = context->streams[ self->video_index ];
1444
1445         // Get codec context
1446         AVCodecContext *codec_context = stream->codec;
1447
1448         uint8_t *alpha = NULL;
1449         int got_picture = 0;
1450         int image_size = 0;
1451
1452         // Get the image cache
1453         if ( ! self->image_cache )
1454         {
1455                 // if cache size supplied by environment variable
1456                 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1457                 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1458
1459                 // cache size supplied via property
1460                 if ( mlt_properties_get( properties, "cache" ) )
1461                 {
1462                         cache_supplied = 1;
1463                         cache_size = mlt_properties_get_int( properties, "cache" );
1464                 }
1465                 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1466                         cache_size = 0;
1467                 // create cache if not disabled
1468                 if ( !cache_supplied || cache_size > 0 )
1469                         self->image_cache = mlt_cache_init();
1470                 // set cache size if supplied
1471                 if ( self->image_cache && cache_supplied )
1472                         mlt_cache_set_size( self->image_cache, cache_size );
1473         }
1474         if ( self->image_cache )
1475         {
1476                 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1477                 if ( original )
1478                 {
1479                         mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1480                         int size = 0;
1481
1482                         *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1483                         if (*buffer)
1484                                 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1485                         *buffer = mlt_properties_get_data( orig_props, "image", &size );
1486                         mlt_frame_set_image( frame, *buffer, size, NULL );
1487                         mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1488                         *format = mlt_properties_get_int( orig_props, "format" );
1489
1490                         // Set the resolution
1491                         *width = codec_context->width;
1492                         *height = codec_context->height;
1493
1494                         // Workaround 1088 encodings missing cropping info.
1495                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1496                                 *height = 1080;
1497
1498                         got_picture = 1;
1499                         goto exit_get_image;
1500                 }
1501         }
1502         // Cache miss
1503
1504         // We may want to use the source fps if available
1505         double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1506                 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1507
1508         // This is the physical frame position in the source
1509         int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1510
1511         // Determines if we have to decode all frames in a sequence
1512         // Temporary hack to improve intra frame only
1513         int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1514                                   strcmp( codec_context->codec->name, "dnxhd" ) &&
1515                                   strcmp( codec_context->codec->name, "dvvideo" ) &&
1516                                   strcmp( codec_context->codec->name, "huffyuv" ) &&
1517                                   strcmp( codec_context->codec->name, "mjpeg" ) &&
1518                                   strcmp( codec_context->codec->name, "rawvideo" ) );
1519
1520         double delay = mlt_properties_get_double( properties, "video_delay" );
1521
1522         // Seek if necessary
1523         const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1524         int preseek = must_decode
1525 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1526                 && ( interp && strcmp( interp, "nearest" ) )
1527 #endif
1528                 && codec_context->has_b_frames;
1529         int paused = seek_video( self, position, req_position, preseek );
1530
1531         // Seek might have reopened the file
1532         context = self->video_format;
1533         stream = context->streams[ self->video_index ];
1534         codec_context = stream->codec;
1535         if ( *format == mlt_image_none ||
1536                         codec_context->pix_fmt == PIX_FMT_ARGB ||
1537                         codec_context->pix_fmt == PIX_FMT_RGBA ||
1538                         codec_context->pix_fmt == PIX_FMT_ABGR ||
1539                         codec_context->pix_fmt == PIX_FMT_BGRA )
1540                 *format = pick_pix_format( codec_context->pix_fmt );
1541
1542         // Duplicate the last image if necessary
1543         if ( self->av_frame && self->av_frame->linesize[0]
1544                  && ( paused || self->current_position >= req_position ) )
1545         {
1546                 // Duplicate it
1547                 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1548                 {
1549                         // Workaround 1088 encodings missing cropping info.
1550                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1551                                 *height = 1080;
1552 #ifdef VDPAU
1553                         if ( self->vdpau && self->vdpau->buffer )
1554                         {
1555                                 AVPicture picture;
1556                                 picture.data[0] = self->vdpau->buffer;
1557                                 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1558                                 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1559                                 picture.linesize[0] = codec_context->width;
1560                                 picture.linesize[1] = codec_context->width / 2;
1561                                 picture.linesize[2] = codec_context->width / 2;
1562                                 convert_image( self, (AVFrame*) &picture, *buffer,
1563                                         PIX_FMT_YUV420P, format, *width, *height, &alpha );
1564                         }
1565                         else
1566 #endif
1567                         convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1568                                 format, *width, *height, &alpha );
1569                         got_picture = 1;
1570                 }
1571         }
1572         else
1573         {
1574                 int ret = 0;
1575                 int64_t int_position = 0;
1576                 int decode_errors = 0;
1577
1578                 // Construct an AVFrame for YUV422 conversion
1579                 if ( !self->av_frame )
1580                         self->av_frame = avcodec_alloc_frame( );
1581
1582                 while( ret >= 0 && !got_picture )
1583                 {
1584                         // Read a packet
1585                         if ( self->pkt.stream_index == self->video_index )
1586                                 av_free_packet( &self->pkt );
1587                         av_init_packet( &self->pkt );
1588                         pthread_mutex_lock( &self->packets_mutex );
1589                         if ( mlt_deque_count( self->vpackets ) )
1590                         {
1591                                 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1592                                 self->pkt = *tmp;
1593                                 free( tmp );
1594                         }
1595                         else
1596                         {
1597                                 ret = av_read_frame( context, &self->pkt );
1598                                 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1599                                 {
1600                                         if ( !av_dup_packet( &self->pkt ) )
1601                                         {
1602                                                 AVPacket *tmp = malloc( sizeof(AVPacket) );
1603                                                 *tmp = self->pkt;
1604                                                 mlt_deque_push_back( self->apackets, tmp );
1605                                         }
1606                                 }
1607                         }
1608                         pthread_mutex_unlock( &self->packets_mutex );
1609
1610                         // We only deal with video from the selected video_index
1611                         if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1612                         {
1613                                 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1614                                 if ( pts != AV_NOPTS_VALUE )
1615                                 {
1616                                         if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1617                                                 self->first_pts = pts;
1618                                         if ( self->first_pts != AV_NOPTS_VALUE )
1619                                                 pts -= self->first_pts;
1620                                         else if ( context->start_time != AV_NOPTS_VALUE )
1621                                                 pts -= context->start_time;
1622                                         int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1623                                         if ( int_position == self->last_position )
1624                                                 int_position = self->last_position + 1;
1625                                 }
1626                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1627                                         "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1628                                         self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1629
1630                                 // Make a dumb assumption on streams that contain wild timestamps
1631                                 if ( abs( req_position - int_position ) > 999 )
1632                                 {
1633                                         int_position = req_position;
1634                                         mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1635                                 }
1636                                 self->last_position = int_position;
1637
1638                                 // Decode the image
1639                                 if ( must_decode || int_position >= req_position )
1640                                 {
1641 #ifdef VDPAU
1642                                         if ( self->vdpau )
1643                                         {
1644                                                 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1645                                                 {
1646                                                         vdpau_decoder_init( self );
1647                                                 }
1648                                                 self->vdpau->is_decoded = 0;
1649                                         }
1650 #endif
1651                                         codec_context->reordered_opaque = int_position;
1652                                         if ( int_position >= req_position )
1653                                                 codec_context->skip_loop_filter = AVDISCARD_NONE;
1654 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1655                                         ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &self->pkt );
1656 #else
1657                                         ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, self->pkt.data, self->pkt.size );
1658 #endif
1659                                         // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1660                                         if ( ret < 0 )
1661                                         {
1662                                                 if ( ++decode_errors <= 10 )
1663                                                         ret = 0;
1664                                         }
1665                                         else
1666                                         {
1667                                                 decode_errors = 0;
1668                                         }
1669                                 }
1670
1671                                 if ( got_picture )
1672                                 {
1673                                         // Get position of reordered frame
1674                                         int_position = self->av_frame->reordered_opaque;
1675 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1676                                         pts = best_pts( self, self->av_frame->pkt_pts, self->av_frame->pkt_dts );
1677                                         if ( pts != AV_NOPTS_VALUE )
1678                                         {
1679                                                 if ( self->first_pts != AV_NOPTS_VALUE )
1680                                                         pts -= self->first_pts;
1681                                                 else if ( context->start_time != AV_NOPTS_VALUE )
1682                                                         pts -= context->start_time;
1683                                                 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1684                                         }
1685 #endif
1686
1687                                         if ( int_position < req_position )
1688                                                 got_picture = 0;
1689                                         else if ( int_position >= req_position )
1690                                                 codec_context->skip_loop_filter = AVDISCARD_NONE;
1691                                 }
1692                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1693                         }
1694
1695                         // Now handle the picture if we have one
1696                         if ( got_picture )
1697                         {
1698                                 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1699                                 {
1700                                         // Workaround 1088 encodings missing cropping info.
1701                                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1702                                                 *height = 1080;
1703 #ifdef VDPAU
1704                                         if ( self->vdpau )
1705                                         {
1706                                                 if ( self->vdpau->is_decoded )
1707                                                 {
1708                                                         struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1709                                                         void *planes[3];
1710                                                         uint32_t pitches[3];
1711                                                         VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1712                                                         
1713                                                         if ( !self->vdpau->buffer )
1714                                                                 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1715                                                         self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1716                                                         self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1717                                                         self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1718                                                         self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1719                                                         self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1720                                                         self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1721
1722                                                         VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1723                                                         if ( status == VDP_STATUS_OK )
1724                                                         {
1725                                                                 convert_image( self, self->av_frame, *buffer, PIX_FMT_YUV420P,
1726                                                                         format, *width, *height, &alpha );
1727                                                         }
1728                                                         else
1729                                                         {
1730                                                                 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1731                                                                 image_size = self->vdpau->is_decoded = 0;
1732                                                         }
1733                                                 }
1734                                                 else
1735                                                 {
1736                                                         mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1737                                                         image_size = got_picture = 0;
1738                                                 }
1739                                         }
1740                                         else
1741 #endif
1742                                         convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1743                                                 format, *width, *height, &alpha );
1744                                         self->top_field_first |= self->av_frame->top_field_first;
1745                                         self->current_position = int_position;
1746                                 }
1747                                 else
1748                                 {
1749                                         got_picture = 0;
1750                                 }
1751                         }
1752
1753                         // Free packet data if not video and not live audio packet
1754                         if ( self->pkt.stream_index != self->video_index &&
1755                                  !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1756                                 av_free_packet( &self->pkt );
1757                 }
1758         }
1759
1760         // set alpha
1761         if ( alpha )
1762                 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1763
1764         if ( image_size > 0 && self->image_cache )
1765         {
1766                 mlt_properties_set_int( frame_properties, "format", *format );
1767                 mlt_cache_put_frame( self->image_cache, frame );
1768         }
1769
1770         // Try to duplicate last image if there was a decoding failure
1771         // TODO: with multithread decoding a partial frame decoding resulting
1772         // in failure also resets av_frame making test below fail.
1773         if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1774         {
1775                 // Duplicate it
1776                 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1777                 {
1778                         // Workaround 1088 encodings missing cropping info.
1779                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1780                                 *height = 1080;
1781 #ifdef VDPAU
1782                         if ( self->vdpau && self->vdpau->buffer )
1783                         {
1784                                 AVPicture picture;
1785                                 picture.data[0] = self->vdpau->buffer;
1786                                 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1787                                 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1788                                 picture.linesize[0] = codec_context->width;
1789                                 picture.linesize[1] = codec_context->width / 2;
1790                                 picture.linesize[2] = codec_context->width / 2;
1791                                 convert_image( self, (AVFrame*) &picture, *buffer,
1792                                         PIX_FMT_YUV420P, format, *width, *height, &alpha );
1793                         }
1794                         else
1795 #endif
1796                         convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1797                                 format, *width, *height, &alpha );
1798                         got_picture = 1;
1799                 }
1800         }
1801
1802         // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1803         self->video_expected = position + 1;
1804
1805 exit_get_image:
1806
1807         pthread_mutex_unlock( &self->video_mutex );
1808
1809         // Set the progressive flag
1810         if ( mlt_properties_get( properties, "force_progressive" ) )
1811                 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1812         else if ( self->av_frame )
1813                 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1814
1815         // Set the field order property for this frame
1816         if ( mlt_properties_get( properties, "force_tff" ) )
1817                 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1818         else
1819                 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1820
1821         // Set immutable properties of the selected track's (or overridden) source attributes.
1822         mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1823         mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1824         mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1825         mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1826
1827         // If we already have RGB, then the full range processing either happened already
1828         // or does not apply (RGB source).
1829         if ( *format == mlt_image_rgb24 || *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1830                 mlt_properties_set( frame_properties, "force_full_luma", NULL );
1831
1832         return !got_picture;
1833 }
1834
1835 /** Process properties as AVOptions and apply to AV context obj
1836 */
1837
1838 static void apply_properties( void *obj, mlt_properties properties, int flags )
1839 {
1840         int i;
1841         int count = mlt_properties_count( properties );
1842         for ( i = 0; i < count; i++ )
1843         {
1844                 const char *opt_name = mlt_properties_get_name( properties, i );
1845 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1846                 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1847 #else
1848                 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1849 #endif
1850                 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1851                 {
1852                         if ( opt )
1853 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1854                                 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1855 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1856                                 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1857 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1858                                 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1859 #else
1860                                 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1861 #endif
1862                 }
1863         }
1864 }
1865
1866 /** Initialize the video codec context.
1867  */
1868
1869 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1870 {
1871         // Initialise the codec if necessary
1872         if ( !self->video_codec )
1873         {
1874                 // Get the video stream
1875                 AVStream *stream = self->video_format->streams[ index ];
1876
1877                 // Get codec context
1878                 AVCodecContext *codec_context = stream->codec;
1879
1880                 // Find the codec
1881                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1882 #ifdef VDPAU
1883                 if ( codec_context->codec_id == CODEC_ID_H264 )
1884                 {
1885                         if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1886                         {
1887                                 if ( vdpau_init( self ) )
1888                                 {
1889                                         self->video_codec = codec_context;
1890                                         if ( !vdpau_decoder_init( self ) )
1891                                                 vdpau_fini( self );
1892                                 }
1893                         }
1894                         if ( !self->vdpau )
1895                                 codec = avcodec_find_decoder( codec_context->codec_id );
1896                 }
1897 #endif
1898
1899                 // Initialise multi-threading
1900                 int thread_count = mlt_properties_get_int( properties, "threads" );
1901                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1902                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1903                 if ( thread_count > 1 )
1904                         codec_context->thread_count = thread_count;
1905
1906                 // If we don't have a codec and we can't initialise it, we can't do much more...
1907                 pthread_mutex_lock( &self->open_mutex );
1908 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1909                 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1910 #else
1911                 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1912 #endif
1913                 {
1914                         // Now store the codec with its destructor
1915                         self->video_codec = codec_context;
1916                 }
1917                 else
1918                 {
1919                         // Remember that we can't use this later
1920                         self->video_index = -1;
1921                         pthread_mutex_unlock( &self->open_mutex );
1922                         return 0;
1923                 }
1924                 pthread_mutex_unlock( &self->open_mutex );
1925
1926                 // Process properties as AVOptions
1927                 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1928 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1929                 if ( codec->priv_class && codec_context->priv_data )
1930                         apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1931 #endif
1932
1933                 // Reset some image properties
1934                 if ( self->video_codec )
1935                 {
1936                         mlt_properties_set_int( properties, "width", self->video_codec->width );
1937                         mlt_properties_set_int( properties, "height", self->video_codec->height );
1938                 }
1939                 // For DV, we'll just use the saved aspect ratio
1940                 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1941                         get_aspect_ratio( properties, stream, self->video_codec, NULL );
1942
1943                 // Determine the fps first from the codec
1944                 double source_fps = (double) self->video_codec->time_base.den /
1945                                                                    ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1946                 
1947                 {
1948                         // If the muxer reports a frame rate different than the codec
1949 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1950                         double muxer_fps = av_q2d( stream->avg_frame_rate );
1951                         if ( isnan( muxer_fps ) || muxer_fps == 0 )
1952                                 muxer_fps = av_q2d( stream->r_frame_rate );
1953 #else
1954                         double muxer_fps = av_q2d( stream->r_frame_rate );
1955 #endif
1956                         // Choose the lesser - the wrong tends to be off by some multiple of 10
1957                         source_fps = FFMIN( source_fps, muxer_fps );
1958                         if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1959                         {
1960                                 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1961                                 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1962                         }
1963                         else if ( muxer_fps > 0 )
1964                         {
1965                                 AVRational frame_rate = stream->r_frame_rate;
1966                                 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1967                                 // avg_frame_rate gives some approximate value that does not well match the media.
1968                                 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1969                                 // results in some very choppy output, but some value slightly different works
1970                                 // great.
1971 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1972                                 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1973                                         frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1974 #endif
1975                                 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1976                                 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1977                         }
1978                         else
1979                         {
1980                                 source_fps = mlt_producer_get_fps( self->parent );
1981                                 AVRational frame_rate = av_d2q( source_fps, 255 );
1982                                 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1983                                 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1984                         }
1985                 }
1986                 if ( mlt_properties_get( properties, "force_fps" ) )
1987                 {
1988                         double source_fps = mlt_properties_get_double( properties, "force_fps" );
1989                         AVRational fps = av_d2q( source_fps, 1024 );
1990                         stream->time_base.num *= mlt_properties_get_int( properties, "meta.media.frame_rate_num" ) * fps.den;
1991                         stream->time_base.den *= mlt_properties_get_int( properties, "meta.media.frame_rate_den" ) * fps.num;
1992                         mlt_properties_set_int( properties, "meta.media.frame_rate_num", fps.num );
1993                         mlt_properties_set_int( properties, "meta.media.frame_rate_den", fps.den );
1994                 }
1995
1996                 // Set the YUV colorspace from override or detect
1997                 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1998 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)               
1999                 if ( ! self->colorspace )
2000                 {
2001                         switch ( self->video_codec->colorspace )
2002                         {
2003                         case AVCOL_SPC_SMPTE240M:
2004                                 self->colorspace = 240;
2005                                 break;
2006                         case AVCOL_SPC_BT470BG:
2007                         case AVCOL_SPC_SMPTE170M:
2008                                 self->colorspace = 601;
2009                                 break;
2010                         case AVCOL_SPC_BT709:
2011                                 self->colorspace = 709;
2012                                 break;
2013                         default:
2014                                 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
2015                                 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
2016                                 break;
2017                         }
2018                 }
2019 #endif
2020                 // Let apps get chosen colorspace
2021                 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
2022
2023                 self->full_luma = -1;
2024 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(72<<8)+2)
2025                 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent), "color_range %d\n", codec_context->color_range );
2026                 if ( codec_context->color_range == AVCOL_RANGE_JPEG )
2027                         self->full_luma = 1;
2028 #endif
2029                 if ( mlt_properties_get( properties, "set.force_full_luma" ) )
2030                         self->full_luma = mlt_properties_get_int( properties, "set.force_full_luma" );
2031         }
2032         return self->video_codec && self->video_index > -1;
2033 }
2034
2035 /** Set up video handling.
2036 */
2037
2038 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2039 {
2040         // Get the producer
2041         mlt_producer producer = self->parent;
2042
2043         // Get the properties
2044         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2045
2046         // Fetch the video format context
2047         AVFormatContext *context = self->video_format;
2048
2049         // Get the video_index
2050         int index = mlt_properties_get_int( properties, "video_index" );
2051
2052         // Reopen the file if necessary
2053         if ( !context && index > -1 )
2054         {
2055                 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2056                         mlt_properties_get( properties, "resource" ), 1 );
2057                 context = self->video_format;
2058         }
2059
2060         // Exception handling for video_index
2061         if ( context && index >= (int) context->nb_streams )
2062         {
2063                 // Get the last video stream
2064                 for ( index = context->nb_streams - 1;
2065                           index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2066                           index-- );
2067                 mlt_properties_set_int( properties, "video_index", index );
2068         }
2069         if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2070         {
2071                 // Invalidate the video stream
2072                 index = -1;
2073                 mlt_properties_set_int( properties, "video_index", index );
2074         }
2075
2076         // Update the video properties if the index changed
2077         if ( index != self->video_index )
2078         {
2079                 // Reset the video properties if the index changed
2080                 self->video_index = index;
2081                 pthread_mutex_lock( &self->open_mutex );
2082                 if ( self->video_codec )
2083                         avcodec_close( self->video_codec );
2084                 self->video_codec = NULL;
2085                 pthread_mutex_unlock( &self->open_mutex );
2086         }
2087
2088         // Get the frame properties
2089         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2090
2091         // Get the codec
2092         if ( context && index > -1 && video_codec_init( self, index, properties ) )
2093         {
2094                 // Set the frame properties
2095                 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2096                 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2097                         force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2098
2099                 // Set the width and height
2100                 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2101                 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2102                 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2103                 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2104                 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2105                 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2106
2107                 // Workaround 1088 encodings missing cropping info.
2108                 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2109                 {
2110                         mlt_properties_set_int( properties, "meta.media.height", 1080 );
2111                 }
2112
2113                 // Add our image operation
2114                 mlt_frame_push_service( frame, self );
2115                 mlt_frame_push_get_image( frame, producer_get_image );
2116         }
2117         else
2118         {
2119                 // If something failed, use test card image
2120                 mlt_properties_set_int( frame_properties, "test_image", 1 );
2121         }
2122 }
2123
2124 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
2125 {
2126         int paused = 0;
2127
2128         // Seek if necessary
2129         if ( self->seekable && position != self->audio_expected )
2130         {
2131                 if ( position + 1 == self->audio_expected )
2132                 {
2133                         // We're paused - silence required
2134                         paused = 1;
2135                 }
2136                 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2137                 {
2138                         AVFormatContext *context = self->audio_format;
2139                         int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2140                         if ( context->start_time != AV_NOPTS_VALUE )
2141                                 timestamp += context->start_time;
2142                         if ( timestamp < 0 )
2143                                 timestamp = 0;
2144
2145                         // Set to the real timecode
2146                         if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2147                                 paused = 1;
2148
2149                         // Clear the usage in the audio buffer
2150                         int i = MAX_AUDIO_STREAMS + 1;
2151                         while ( --i )
2152                                 self->audio_used[i - 1] = 0;
2153                 }
2154         }
2155         return paused;
2156 }
2157
2158 static int sample_bytes( AVCodecContext *context )
2159 {
2160 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2161         return av_get_bytes_per_sample( context->sample_fmt );
2162 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2163         return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2164 #else
2165         return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2166 #endif
2167 }
2168
2169 static void planar_to_interleaved( uint8_t *dest, uint8_t *src, int samples, int channels, int bytes_per_sample )
2170 {
2171         int s, c;
2172         for ( s = 0; s < samples; s++ )
2173         {
2174                 for ( c = 0; c < channels; c++ )
2175                 {
2176                         memcpy( dest, src + ( c * samples + s ) * bytes_per_sample, bytes_per_sample );
2177                         dest += bytes_per_sample;
2178                 }
2179         }
2180 }
2181
2182 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2183 {
2184         // Fetch the audio_format
2185         AVFormatContext *context = self->audio_format;
2186
2187         // Get the current stream index
2188         int index = pkt.stream_index;
2189
2190         // Get codec context
2191         AVCodecContext *codec_context = self->audio_codec[ index ];
2192
2193         // Obtain the resample context if it exists (not always needed)
2194         ReSampleContext *resample = self->audio_resample[ index ];
2195
2196         // Obtain the audio buffers
2197         uint8_t *audio_buffer = self->audio_buffer[ index ];
2198         uint8_t *decode_buffer = self->decode_buffer[ index ];
2199
2200         int audio_used = self->audio_used[ index ];
2201         uint8_t *ptr = pkt.data;
2202         int len = pkt.size;
2203         int ret = 0;
2204
2205         while ( ptr && ret >= 0 && len > 0 )
2206         {
2207                 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2208                 int data_size = self->audio_buffer_size[ index ];
2209
2210                 // Decode the audio
2211 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2212                 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2213 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2214                 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2215 #else
2216                 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2217 #endif
2218                 if ( ret < 0 )
2219                 {
2220                         mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2221                         break;
2222                 }
2223
2224                 pkt.size = len -= ret;
2225                 pkt.data = ptr += ret;
2226
2227                 // If decoded successfully
2228                 if ( data_size > 0 )
2229                 {
2230                         // Figure out how many samples will be needed after resampling
2231                         int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2232                         int samples_needed = self->resample_factor * convert_samples;
2233
2234                         // Resize audio buffer to prevent overflow
2235                         if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2236                         {
2237                                 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2238                                 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2239                         }
2240                         if ( resample )
2241                         {
2242                                 // Copy to audio buffer while resampling
2243                                 uint8_t *source = decode_buffer;
2244                                 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2245                                 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2246                         }
2247                         else
2248                         {
2249                                 uint8_t *source = decode_buffer;
2250                                 uint8_t *dest = &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ];
2251                                 switch ( codec_context->sample_fmt )
2252                                 {
2253 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2254                                 case AV_SAMPLE_FMT_U8P:
2255                                 case AV_SAMPLE_FMT_S16P:
2256                                 case AV_SAMPLE_FMT_S32P:
2257                                 case AV_SAMPLE_FMT_FLTP:
2258                                         planar_to_interleaved( dest, source, convert_samples, codec_context->channels, sizeof_sample );
2259                                         break;
2260 #endif
2261                                 default:
2262                                         // Straight copy to audio buffer
2263                                         memcpy( dest, decode_buffer, data_size );
2264                                 }
2265                                 audio_used += convert_samples;
2266                         }
2267
2268                         // Handle ignore
2269                         while ( *ignore && audio_used )
2270                         {
2271                                 *ignore -= 1;
2272                                 audio_used -= audio_used > samples ? samples : audio_used;
2273                                 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2274                                                  audio_used * sizeof_sample );
2275                         }
2276                 }
2277         }
2278
2279         // If we're behind, ignore this packet
2280         // Skip this on non-seekable, audio-only inputs.
2281         if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2282         {
2283                 int64_t pts = pkt.pts;
2284                 if ( self->first_pts != 0 )
2285                         pts -= self->first_pts;
2286                 else if ( context->start_time != AV_NOPTS_VALUE )
2287                         pts -= context->start_time;
2288                 double timebase = av_q2d( context->streams[ index ]->time_base );
2289                 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2290                 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2291
2292                 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2293                         "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2294                         pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2295
2296                 if ( int_position > 0 )
2297                 {
2298                         if ( int_position < req_position )
2299                                 // We are behind, so skip some
2300                                 *ignore = req_position - int_position;
2301                         else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2302                                 // We are ahead, so seek backwards some more
2303                                 seek_audio( self, req_position, timecode - 1.0 );
2304                 }
2305         }
2306
2307         self->audio_used[ index ] = audio_used;
2308
2309         return ret;
2310 }
2311
2312 /** Get the audio from a frame.
2313 */
2314 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2315 {
2316         // Get the producer
2317         producer_avformat self = mlt_frame_pop_audio( frame );
2318
2319         pthread_mutex_lock( &self->audio_mutex );
2320         
2321         // Obtain the frame number of this frame
2322         mlt_position position = mlt_frame_original_position( frame );
2323
2324         // Calculate the real time code
2325         double real_timecode = producer_time_of_frame( self->parent, position );
2326
2327         // Get the producer fps
2328         double fps = mlt_producer_get_fps( self->parent );
2329
2330         // Number of frames to ignore (for ffwd)
2331         int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2332
2333         // Flag for paused (silence)
2334         int paused = seek_audio( self, position, real_timecode );
2335
2336         // Initialize ignore for all streams from the seek return value
2337         int i = MAX_AUDIO_STREAMS;
2338         while ( i-- )
2339                 ignore[i] = ignore[0];
2340
2341         // Fetch the audio_format
2342         AVFormatContext *context = self->audio_format;
2343
2344         int sizeof_sample = sizeof( int16_t );
2345         
2346         // Determine the tracks to use
2347         int index = self->audio_index;
2348         int index_max = self->audio_index + 1;
2349         if ( self->audio_index == INT_MAX )
2350         {
2351                 index = 0;
2352                 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2353                 *channels = self->total_channels;
2354                 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2355                 *frequency = FFMAX( self->max_frequency, *frequency );
2356         }
2357
2358         // Initialize the resamplers and buffers
2359         for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2360         {
2361                 // Get codec context
2362                 AVCodecContext *codec_context = self->audio_codec[ index ];
2363
2364                 if ( codec_context && !self->audio_buffer[ index ] )
2365                 {
2366 #if LIBAVCODEC_VERSION_INT < ((54<<16)+(26<<8)+0)
2367                         // Check for resample and create if necessary
2368                         if ( codec_context->channels <= 2 )
2369                         {
2370                                 // Determine by how much resampling will increase number of samples
2371                                 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2372                                 resample_factor *= (double) *frequency / codec_context->sample_rate;
2373                                 if ( resample_factor > self->resample_factor )
2374                                         self->resample_factor = resample_factor;
2375                                 
2376                                 // Create the resampler
2377 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2378                                 self->audio_resample[ index ] = av_audio_resample_init(
2379                                         self->audio_index == INT_MAX ? codec_context->channels : *channels,
2380                                         codec_context->channels, *frequency, codec_context->sample_rate,
2381                                         AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2382 #else
2383                                 self->audio_resample[ index ] = audio_resample_init(
2384                                         self->audio_index == INT_MAX ? codec_context->channels : *channels,
2385                                         codec_context->channels, *frequency, codec_context->sample_rate );
2386 #endif
2387                         }
2388                         else
2389 #endif
2390                         {
2391                                 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2392                                 sizeof_sample = sample_bytes( codec_context );
2393                         }
2394
2395                         // Check for audio buffer and create if necessary
2396                         self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2397                         self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2398
2399                         // Check for decoder buffer and create if necessary
2400                         self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2401                 }
2402         }
2403
2404         // Get the audio if required
2405         if ( !paused && *frequency > 0 )
2406         {
2407                 int ret = 0;
2408                 int got_audio = 0;
2409                 AVPacket pkt;
2410
2411                 av_init_packet( &pkt );
2412                 
2413                 // If not resampling, give consumer more than requested.
2414                 // It requested number samples based on requested frame rate.
2415                 // Do not clean this up with a samples *= ...!
2416                 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2417                         *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2418
2419                 while ( ret >= 0 && !got_audio )
2420                 {
2421                         // Check if the buffer already contains the samples required
2422                         if ( self->audio_index != INT_MAX &&
2423                                  self->audio_used[ self->audio_index ] >= *samples &&
2424                                  ignore[ self->audio_index ] == 0 )
2425                         {
2426                                 got_audio = 1;
2427                                 break;
2428                         }
2429                         else if ( self->audio_index == INT_MAX )
2430                         {
2431                                 // Check if there is enough audio for all streams
2432                                 got_audio = 1;
2433                                 for ( index = 0; got_audio && index < index_max; index++ )
2434                                         if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2435                                                 got_audio = 0;
2436                                 if ( got_audio )
2437                                         break;
2438                         }
2439
2440                         // Read a packet
2441                         pthread_mutex_lock( &self->packets_mutex );
2442                         if ( mlt_deque_count( self->apackets ) )
2443                         {
2444                                 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2445                                 pkt = *tmp;
2446                                 free( tmp );
2447                         }
2448                         else
2449                         {
2450                                 ret = av_read_frame( context, &pkt );
2451                                 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2452                                 {
2453                                         if ( !av_dup_packet( &pkt ) )
2454                                         {
2455                                                 AVPacket *tmp = malloc( sizeof(AVPacket) );
2456                                                 *tmp = pkt;
2457                                                 mlt_deque_push_back( self->vpackets, tmp );
2458                                         }
2459                                 }
2460                         }
2461                         pthread_mutex_unlock( &self->packets_mutex );
2462
2463                         // We only deal with audio from the selected audio index
2464                         index = pkt.stream_index;
2465                         if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2466                                  ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2467                         {
2468                                 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2469                                         self->audio_codec[index]->channels : *channels;
2470                                 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2471                         }
2472
2473                         if ( self->seekable || index != self->video_index )
2474                                 av_free_packet( &pkt );
2475
2476                 }
2477
2478                 // Set some additional return values
2479                 *format = mlt_audio_s16;
2480                 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2481                 {
2482                         index = self->audio_index;
2483                         *channels = self->audio_codec[ index ]->channels;
2484                         *frequency = self->audio_codec[ index ]->sample_rate;
2485                         *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2486                         sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2487                 }
2488                 else if ( self->audio_index == INT_MAX )
2489                 {
2490                         for ( index = 0; index < index_max; index++ )
2491                                 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2492                                 {
2493                                         // XXX: This only works if all audio tracks have the same sample format.
2494                                         *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2495                                         sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2496                                         break;
2497                                 }
2498                 }
2499
2500                 // Allocate and set the frame's audio buffer
2501                 int size = mlt_audio_format_size( *format, *samples, *channels );
2502                 *buffer = mlt_pool_alloc( size );
2503                 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2504
2505                 // Interleave tracks if audio_index=all
2506                 if ( self->audio_index == INT_MAX )
2507                 {
2508                         uint8_t *dest = *buffer;
2509                         int i;
2510                         for ( i = 0; i < *samples; i++ )
2511                         {
2512                                 for ( index = 0; index < index_max; index++ )
2513                                 if ( self->audio_codec[ index ] )
2514                                 {
2515                                         int current_channels = self->audio_codec[ index ]->channels;
2516                                         uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2517                                         memcpy( dest, src, current_channels * sizeof_sample );
2518                                         dest += current_channels * sizeof_sample;
2519                                 }
2520                         }
2521                         for ( index = 0; index < index_max; index++ )
2522                         if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2523                         {
2524                                 int current_channels = self->audio_codec[ index ]->channels;
2525                                 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2526                                 self->audio_used[index] -= *samples;
2527                                 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2528                         }
2529                 }
2530                 // Copy a single track to the output buffer
2531                 else
2532                 {
2533                         index = self->audio_index;
2534
2535                         // Now handle the audio if we have enough
2536                         if ( self->audio_used[ index ] > 0 )
2537                         {
2538                                 uint8_t *src = self->audio_buffer[ index ];
2539                                 // copy samples from audio_buffer
2540                                 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2541                                 memcpy( *buffer, src, size * *channels * sizeof_sample );
2542                                 // supply the remaining requested samples as silence
2543                                 if ( *samples > self->audio_used[ index ] )
2544                                         memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2545                                 // reposition the samples within audio_buffer
2546                                 self->audio_used[ index ] -= size;
2547                                 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2548                         }
2549                         else
2550                         {
2551                                 // Otherwise fill with silence
2552                                 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2553                         }
2554                 }
2555         }
2556         else
2557         {
2558                 // Get silence and don't touch the context
2559                 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2560         }
2561         
2562         // Regardless of speed (other than paused), we expect to get the next frame
2563         if ( !paused )
2564                 self->audio_expected = position + 1;
2565
2566         pthread_mutex_unlock( &self->audio_mutex );
2567
2568         return 0;
2569 }
2570
2571 /** Initialize the audio codec context.
2572 */
2573
2574 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2575 {
2576         // Initialise the codec if necessary
2577         if ( !self->audio_codec[ index ] )
2578         {
2579                 // Get codec context
2580                 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2581
2582                 // Find the codec
2583                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2584
2585                 // If we don't have a codec and we can't initialise it, we can't do much more...
2586                 pthread_mutex_lock( &self->open_mutex );
2587 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2588                 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2589 #else
2590                 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2591 #endif
2592                 {
2593                         // Now store the codec with its destructor
2594                         if ( self->audio_codec[ index ] )
2595                                 avcodec_close( self->audio_codec[ index ] );
2596                         self->audio_codec[ index ] = codec_context;
2597                 }
2598                 else
2599                 {
2600                         // Remember that we can't use self later
2601                         self->audio_index = -1;
2602                 }
2603                 pthread_mutex_unlock( &self->open_mutex );
2604
2605                 // Process properties as AVOptions
2606                 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2607 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2608                 if ( codec && codec->priv_class && codec_context->priv_data )
2609                         apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2610 #endif
2611         }
2612         return self->audio_codec[ index ] && self->audio_index > -1;
2613 }
2614
2615 /** Set up audio handling.
2616 */
2617
2618 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2619 {
2620         // Get the producer
2621         mlt_producer producer = self->parent;
2622
2623         // Get the properties
2624         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2625
2626         // Fetch the audio format context
2627         AVFormatContext *context = self->audio_format;
2628
2629         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2630
2631         // Get the audio_index
2632         int index = mlt_properties_get_int( properties, "audio_index" );
2633
2634         // Handle all audio tracks
2635         if ( self->audio_index > -1 &&
2636              mlt_properties_get( properties, "audio_index" ) &&
2637              !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2638                 index = INT_MAX;
2639
2640         // Reopen the file if necessary
2641         if ( !context && self->audio_index > -1 && index > -1 )
2642         {
2643                 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2644                         mlt_properties_get( properties, "resource" ), 1 );
2645                 context = self->audio_format;
2646         }
2647
2648         // Exception handling for audio_index
2649         if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2650         {
2651                 for ( index = context->nb_streams - 1;
2652                           index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2653                           index-- );
2654                 mlt_properties_set_int( properties, "audio_index", index );
2655         }
2656         if ( context && index > -1 && index < INT_MAX &&
2657                  context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2658         {
2659                 index = self->audio_index;
2660                 mlt_properties_set_int( properties, "audio_index", index );
2661         }
2662         if ( context && index > -1 && index < INT_MAX &&
2663                  pick_audio_format( context->streams[ index ]->codec->sample_fmt ) == mlt_audio_none )
2664         {
2665                 index = -1;
2666         }
2667
2668         // Update the audio properties if the index changed
2669         if ( context && index > -1 && index != self->audio_index )
2670         {
2671                 pthread_mutex_lock( &self->open_mutex );
2672                 if ( self->audio_codec[ self->audio_index ] )
2673                         avcodec_close( self->audio_codec[ self->audio_index ] );
2674                 self->audio_codec[ self->audio_index ] = NULL;
2675                 pthread_mutex_unlock( &self->open_mutex );
2676         }
2677         if ( self->audio_index != -1 )
2678                 self->audio_index = index;
2679         else
2680                 index = -1;
2681
2682         // Get the codec(s)
2683         if ( context && index == INT_MAX )
2684         {
2685                 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2686                 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2687                 for ( index = 0; index < context->nb_streams; index++ )
2688                 {
2689                         if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2690                                 audio_codec_init( self, index, properties );
2691                 }
2692         }
2693         else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2694         {
2695                 // Set the frame properties
2696                 if ( index < MAX_AUDIO_STREAMS )
2697                 {
2698                         mlt_properties_set_int( frame_properties, "audio_frequency", self->audio_codec[ index ]->sample_rate );
2699                         mlt_properties_set_int( frame_properties, "audio_channels", self->audio_codec[ index ]->channels );
2700                 }
2701         }
2702         if ( context && index > -1 )
2703         {
2704                 // Add our audio operation
2705                 mlt_frame_push_audio( frame, self );
2706                 mlt_frame_push_audio( frame, producer_get_audio );
2707         }
2708 }
2709
2710 /** Our get frame implementation.
2711 */
2712
2713 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2714 {
2715         // Access the private data
2716         mlt_service service = MLT_PRODUCER_SERVICE( producer );
2717         mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2718         producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2719
2720         // If cache miss
2721         if ( !self )
2722         {
2723                 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2724                 producer->child = self;
2725                 self->parent = producer;
2726                 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2727                 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2728         }
2729
2730         // Create an empty frame
2731         *frame = mlt_frame_init( service);
2732         
2733         if ( *frame )
2734         {
2735                 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2736         }
2737         else
2738         {
2739                 mlt_cache_item_close( cache_item );
2740                 return 1;
2741         }
2742
2743         // Update timecode on the frame we're creating
2744         mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2745
2746         // Set up the video
2747         producer_set_up_video( self, *frame );
2748
2749         // Set up the audio
2750         producer_set_up_audio( self, *frame );
2751
2752         // Set the position of this producer
2753         mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2754         mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2755
2756         // Calculate the next timecode
2757         mlt_producer_prepare_next( producer );
2758
2759         return 0;
2760 }
2761
2762 static void producer_avformat_close( producer_avformat self )
2763 {
2764         mlt_log_debug( NULL, "producer_avformat_close\n" );
2765
2766         // Cleanup av contexts
2767         av_free_packet( &self->pkt );
2768         av_free( self->av_frame );
2769         pthread_mutex_lock( &self->open_mutex );
2770         int i;
2771         for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2772         {
2773                 if ( self->audio_resample[i] )
2774                         audio_resample_close( self->audio_resample[i] );
2775                 mlt_pool_release( self->audio_buffer[i] );
2776                 av_free( self->decode_buffer[i] );
2777                 if ( self->audio_codec[i] )
2778                         avcodec_close( self->audio_codec[i] );
2779                 self->audio_codec[i] = NULL;
2780         }
2781         if ( self->video_codec )
2782                 avcodec_close( self->video_codec );
2783         self->video_codec = NULL;
2784         // Close the file
2785 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2786         if ( self->dummy_context )
2787                 avformat_close_input( &self->dummy_context );
2788         if ( self->seekable && self->audio_format )
2789                 avformat_close_input( &self->audio_format );
2790         if ( self->video_format )
2791                 avformat_close_input( &self->video_format );
2792 #else
2793         if ( self->dummy_context )
2794                 av_close_input_file( self->dummy_context );
2795         if ( self->seekable && self->audio_format )
2796                 av_close_input_file( self->audio_format );
2797         if ( self->video_format )
2798                 av_close_input_file( self->video_format );
2799 #endif
2800         pthread_mutex_unlock( &self->open_mutex );
2801 #ifdef VDPAU
2802         vdpau_producer_close( self );
2803 #endif
2804         if ( self->image_cache )
2805                 mlt_cache_close( self->image_cache );
2806
2807         // Cleanup the mutexes
2808         if ( self->is_mutex_init )
2809         {
2810                 pthread_mutex_destroy( &self->audio_mutex );
2811                 pthread_mutex_destroy( &self->video_mutex );
2812                 pthread_mutex_destroy( &self->packets_mutex );
2813                 pthread_mutex_destroy( &self->open_mutex );
2814         }
2815
2816         // Cleanup the packet queues
2817         AVPacket *pkt;
2818         if ( self->apackets )
2819         {
2820                 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2821                 {
2822                         av_free_packet( pkt );
2823                         free( pkt );
2824                 }
2825                 mlt_deque_close( self->apackets );
2826                 self->apackets = NULL;
2827         }
2828         if ( self->vpackets )
2829         {
2830                 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2831                 {
2832                         av_free_packet( pkt );
2833                         free( pkt );
2834                 }
2835                 mlt_deque_close( self->vpackets );
2836                 self->vpackets = NULL;
2837         }
2838
2839         free( self );
2840 }
2841
2842 static void producer_close( mlt_producer parent )
2843 {
2844         // Remove this instance from the cache
2845         mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2846
2847         // Close the parent
2848         parent->close = NULL;
2849         mlt_producer_close( parent );
2850
2851         // Free the memory
2852         free( parent );
2853 }