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