]> git.sesse.net Git - mlt/blob - src/modules/avformat/producer_avformat.c
Rename 'this' in avformat module.
[mlt] / src / modules / avformat / producer_avformat.c
1 /*
2  * producer_avformat.c -- avformat producer
3  * Copyright (C) 2003-2009 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 #include <libavcodec/opt.h>
35 #ifdef SWSCALE
36 #  include <libswscale/swscale.h>
37 #endif
38 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
39 #  include "audioconvert.h"
40 #endif
41 #ifdef VDPAU
42 #  include <libavcodec/vdpau.h>
43 #endif
44 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
45 #  include <libavutil/pixdesc.h>
46 #endif
47
48 // System header files
49 #include <stdlib.h>
50 #include <string.h>
51 #include <pthread.h>
52 #include <limits.h>
53
54 #if LIBAVUTIL_VERSION_INT < (50<<16)
55 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
56 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
57 #endif
58
59 #define POSITION_INITIAL (-2)
60 #define POSITION_INVALID (-1)
61
62 #define MAX_AUDIO_STREAMS (10)
63 #define MAX_VDPAU_SURFACES (10)
64
65 void avformat_lock( );
66 void avformat_unlock( );
67
68 struct producer_avformat_s
69 {
70         mlt_producer parent;
71         AVFormatContext *dummy_context;
72         AVFormatContext *audio_format;
73         AVFormatContext *video_format;
74         AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
75         AVCodecContext *video_codec;
76         AVFrame *av_frame;
77         ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
78         mlt_position audio_expected;
79         mlt_position video_expected;
80         int audio_index;
81         int video_index;
82         double start_time;
83         int first_pts;
84         int last_position;
85         int seekable;
86         int current_position;
87         int got_picture;
88         int top_field_first;
89         int16_t *audio_buffer[ MAX_AUDIO_STREAMS ];
90         size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
91         int16_t *decode_buffer[ MAX_AUDIO_STREAMS ];
92         int audio_used[ MAX_AUDIO_STREAMS ];
93         int audio_streams;
94         int audio_max_stream;
95         int total_channels;
96         int max_channel;
97         int max_frequency;
98         unsigned int invalid_pts_counter;
99         double resample_factor;
100         mlt_cache image_cache;
101         int colorspace;
102 #ifdef VDPAU
103         struct
104         {
105                 // from FFmpeg
106                 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
107                 
108                 // internal
109                 mlt_deque deque;
110                 int b_age;
111                 int ip_age[2];
112                 int is_decoded;
113                 uint8_t *buffer;
114         } *vdpau;
115 #endif
116 };
117 typedef struct producer_avformat_s *producer_avformat;
118
119 // Forward references.
120 static int producer_open( producer_avformat self, mlt_profile profile, char *file );
121 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
122 static void producer_avformat_close( producer_avformat );
123 static void producer_close( mlt_producer parent );
124 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
125
126 #ifdef VDPAU
127 #include "vdpau.c"
128 #endif
129
130 /** Constructor for libavformat.
131 */
132
133 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
134 {
135         int skip = 0;
136
137         // Report information about available demuxers and codecs as YAML Tiny
138         if ( file && strstr( file, "f-list" ) )
139         {
140                 fprintf( stderr, "---\nformats:\n" );
141                 AVInputFormat *format = NULL;
142                 while ( ( format = av_iformat_next( format ) ) )
143                         fprintf( stderr, "  - %s\n", format->name );
144                 fprintf( stderr, "...\n" );
145                 skip = 1;
146         }
147         if ( file && strstr( file, "acodec-list" ) )
148         {
149                 fprintf( stderr, "---\naudio_codecs:\n" );
150                 AVCodec *codec = NULL;
151                 while ( ( codec = av_codec_next( codec ) ) )
152                         if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
153                                 fprintf( stderr, "  - %s\n", codec->name );
154                 fprintf( stderr, "...\n" );
155                 skip = 1;
156         }
157         if ( file && strstr( file, "vcodec-list" ) )
158         {
159                 fprintf( stderr, "---\nvideo_codecs:\n" );
160                 AVCodec *codec = NULL;
161                 while ( ( codec = av_codec_next( codec ) ) )
162                         if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
163                                 fprintf( stderr, "  - %s\n", codec->name );
164                 fprintf( stderr, "...\n" );
165                 skip = 1;
166         }
167
168         // Check that we have a non-NULL argument
169         if ( !skip && file )
170         {
171                 // Construct the producer
172                 mlt_producer producer = calloc( 1, sizeof( struct mlt_producer_s ) );
173                 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
174
175                 // Initialise it
176                 if ( mlt_producer_init( producer, self ) == 0 )
177                 {
178                         self->parent = producer;
179
180                         // Get the properties
181                         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
182
183                         // Set the resource property (required for all producers)
184                         mlt_properties_set( properties, "resource", file );
185
186                         // Register transport implementation with the producer
187                         producer->close = (mlt_destructor) producer_close;
188
189                         // Register our get_frame implementation
190                         producer->get_frame = producer_get_frame;
191                         
192                         if ( strcmp( service, "avformat-novalidate" ) )
193                         {
194                                 // Open the file
195                                 if ( producer_open( self, profile, file ) != 0 )
196                                 {
197                                         // Clean up
198                                         mlt_producer_close( producer );
199                                         producer = NULL;
200                                 }
201                                 else
202                                 {
203                                         // Close the file to release resources for large playlists - reopen later as needed
204                                         avformat_lock();
205                                         if ( self->dummy_context )
206                                                 av_close_input_file( self->dummy_context );
207                                         self->dummy_context = NULL;
208                                         if ( self->audio_format )
209                                                 av_close_input_file( self->audio_format );
210                                         self->audio_format = NULL;
211                                         if ( self->video_format )
212                                                 av_close_input_file( self->video_format );
213                                         self->video_format = NULL;
214                                         avformat_unlock();
215         
216                                         // Default the user-selectable indices from the auto-detected indices
217                                         mlt_properties_set_int( properties, "audio_index",  self->audio_index );
218                                         mlt_properties_set_int( properties, "video_index",  self->video_index );
219                                         
220 #ifdef VDPAU
221                                         mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
222 #endif
223                                         mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
224                                 }
225                         }
226                         else
227                         {
228 #ifdef VDPAU
229                                 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
230 #endif
231                                 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
232                         }
233                         return producer;
234                 }
235         }
236         return NULL;
237 }
238
239 /** Find the default streams.
240 */
241
242 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
243 {
244         int i;
245         char key[200];
246         AVMetadataTag *tag = NULL;
247
248         mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
249
250         // Allow for multiple audio and video streams in the file and select first of each (if available)
251         for( i = 0; i < context->nb_streams; i++ )
252         {
253                 // Get the codec context
254                 AVStream *stream = context->streams[ i ];
255                 if ( ! stream ) continue;
256                 AVCodecContext *codec_context = stream->codec;
257                 if ( ! codec_context ) continue;
258                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
259                 if ( ! codec ) continue;
260
261                 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
262
263                 // Determine the type and obtain the first index of each type
264                 switch( codec_context->codec_type )
265                 {
266                         case CODEC_TYPE_VIDEO:
267                                 if ( *video_index < 0 )
268                                         *video_index = i;
269                                 mlt_properties_set( meta_media, key, "video" );
270                                 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
271 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
272                                 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
273                                 if (ffmpeg_fps == 0) ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
274                                 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
275 #else
276                                 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
277 #endif
278
279 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
280                                 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
281                                 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
282 #endif
283                                 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
284                                 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
285                                                                                    ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
286                                 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
287                                 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
288                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
289                                 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
290 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
291                                 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
292                                 switch ( codec_context->colorspace )
293                                 {
294                                 case AVCOL_SPC_SMPTE240M:
295                                         mlt_properties_set_int( meta_media, key, 240 );
296                                         break;
297                                 case AVCOL_SPC_BT470BG:
298                                 case AVCOL_SPC_SMPTE170M:
299                                         mlt_properties_set_int( meta_media, key, 601 );
300                                         break;
301                                 case AVCOL_SPC_BT709:
302                                         mlt_properties_set_int( meta_media, key, 709 );
303                                         break;
304                                 default:
305                                         // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
306                                         mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
307                                         break;
308                                 }
309 #endif
310                                 break;
311                         case CODEC_TYPE_AUDIO:
312                                 if ( *audio_index < 0 )
313                                         *audio_index = i;
314                                 mlt_properties_set( meta_media, key, "audio" );
315 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
316                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
317                                 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
318 #endif
319                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
320                                 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
321                                 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
322                                 mlt_properties_set_int( meta_media, key, codec_context->channels );
323                                 break;
324                         default:
325                                 break;
326                 }
327 //              snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
328 //              mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
329                 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
330                 mlt_properties_set( meta_media, key, codec->name );
331 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
332                 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
333                 mlt_properties_set( meta_media, key, codec->long_name );
334 #endif
335                 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
336                 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
337 //              snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
338 //              mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
339 //              snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
340 //              mlt_properties_set_int( meta_media, key, codec_context->profile );
341 //              snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
342 //              mlt_properties_set_int( meta_media, key, codec_context->level );
343
344                 // Read Metadata
345 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
346                 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
347                 {
348                         if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
349                         {
350                                 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
351                                 mlt_properties_set( meta_media, key, tag->value );
352                         }
353                 }
354 #endif
355         }
356 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
357         while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
358         {
359                 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
360                 {
361                         snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
362                         mlt_properties_set( meta_media, key, tag->value );
363                 }
364         }
365 #else
366         if ( context->title && strcmp( context->title, "" ) )
367                 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
368         if ( context->author && strcmp( context->author, "" ) )
369                 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
370         if ( context->copyright && strcmp( context->copyright, "" ) )
371                 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
372         if ( context->comment )
373                 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
374         if ( context->album )
375                 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
376         if ( context->year )
377                 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
378         if ( context->track )
379                 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
380 #endif
381
382         return meta_media;
383 }
384
385 static inline int dv_is_pal( AVPacket *pkt )
386 {
387         return pkt->data[3] & 0x80;
388 }
389
390 static int dv_is_wide( AVPacket *pkt )
391 {
392         int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
393
394         for ( ; i < pkt->size; i += 5 /* packet size */ )
395         {
396                 if ( pkt->data[ i ] == 0x61 )
397                 {
398                         uint8_t x = pkt->data[ i + 2 ] & 0x7;
399                         return ( x == 2 ) || ( x == 7 );
400                 }
401         }
402         return 0;
403 }
404
405 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
406 {
407         double aspect_ratio = 1.0;
408
409         if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
410         {
411                 if ( pkt )
412                 {
413                         if ( dv_is_pal( pkt ) )
414                         {
415                                 if ( dv_is_wide( pkt ) )
416                                 {
417                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
418                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
419                                 }
420                                 else
421                                 {
422                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
423                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
424                                 }
425                         }
426                         else
427                         {
428                                 if ( dv_is_wide( pkt ) )
429                                 {
430                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
431                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
432                                 }
433                                 else
434                                 {
435                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
436                                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
437                                 }
438                         }
439                 }
440                 else
441                 {
442                         AVRational ar =
443 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
444                                 stream->sample_aspect_ratio;
445 #else
446                                 codec_context->sample_aspect_ratio;
447 #endif
448                         // Override FFmpeg's notion of DV aspect ratios, which are
449                         // based upon a width of 704. Since we do not have a normaliser
450                         // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
451                         // we just coerce the values to facilitate a passive behaviour through
452                         // the rescale normaliser when using equivalent producers and consumers.
453                         // = display_aspect / (width * height)
454                         if ( ar.num == 10 && ar.den == 11 )
455                         {
456                                 // 4:3 NTSC
457                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
458                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
459                         }
460                         else if ( ar.num == 59 && ar.den == 54 )
461                         {
462                                 // 4:3 PAL
463                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
464                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
465                         }
466                         else if ( ar.num == 40 && ar.den == 33 )
467                         {
468                                 // 16:9 NTSC
469                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
470                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
471                         }
472                         else if ( ar.num == 118 && ar.den == 81 )
473                         {
474                                 // 16:9 PAL
475                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
476                                 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
477                         }
478                 }
479         }
480         else
481         {
482                 AVRational codec_sar = codec_context->sample_aspect_ratio;
483                 AVRational stream_sar =
484 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
485                         stream->sample_aspect_ratio;
486 #else
487                         { 0, 1 };
488 #endif
489                 if ( codec_sar.num > 0 )
490                 {
491                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
492                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
493                 }
494                 else if ( stream_sar.num > 0 )
495                 {
496                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
497                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
498                 }
499                 else
500                 {
501                         mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
502                         mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
503                 }
504         }
505         AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
506         aspect_ratio = av_q2d( ar );
507         mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
508
509         return aspect_ratio;
510 }
511
512 /** Open the file.
513 */
514
515 static int producer_open( producer_avformat self, mlt_profile profile, char *file )
516 {
517         // Return an error code (0 == no error)
518         int error = 0;
519
520         // Context for avformat
521         AVFormatContext *context = NULL;
522
523         // Get the properties
524         mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
525
526         // We will treat everything with the producer fps
527         double fps = mlt_profile_fps( profile );
528
529         // Lock the mutex now
530         avformat_lock( );
531
532         // If "MRL", then create AVInputFormat
533         AVInputFormat *format = NULL;
534         AVFormatParameters *params = NULL;
535         char *standard = NULL;
536         char *mrl = strchr( file, ':' );
537
538         // AV option (0 = both, 1 = video, 2 = audio)
539         int av = 0;
540
541         // Only if there is not a protocol specification that avformat can handle
542         if ( mrl && !url_exist( file ) )
543         {
544                 // 'file' becomes format abbreviation
545                 mrl[0] = 0;
546
547                 // Lookup the format
548                 format = av_find_input_format( file );
549
550                 // Eat the format designator
551                 file = ++mrl;
552
553                 if ( format )
554                 {
555                         // Allocate params
556                         params = calloc( sizeof( AVFormatParameters ), 1 );
557
558                         // These are required by video4linux (defaults)
559                         params->width = 640;
560                         params->height = 480;
561                         params->time_base= (AVRational){1,25};
562                         params->channels = 2;
563                         params->sample_rate = 48000;
564                 }
565
566                 // Parse out params
567                 mrl = strchr( file, '?' );
568                 while ( mrl )
569                 {
570                         mrl[0] = 0;
571                         char *name = strdup( ++mrl );
572                         char *value = strchr( name, ':' );
573                         if ( value )
574                         {
575                                 value[0] = 0;
576                                 value++;
577                                 char *t = strchr( value, '&' );
578                                 if ( t )
579                                         t[0] = 0;
580                                 if ( !strcmp( name, "frame_rate" ) )
581                                         params->time_base.den = atoi( value );
582                                 else if ( !strcmp( name, "frame_rate_base" ) )
583                                         params->time_base.num = atoi( value );
584                                 else if ( !strcmp( name, "sample_rate" ) )
585                                         params->sample_rate = atoi( value );
586                                 else if ( !strcmp( name, "channel" ) )
587                                         params->channel = atoi( value );
588                                 else if ( !strcmp( name, "channels" ) )
589                                         params->channels = atoi( value );
590 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
591                                 else if ( !strcmp( name, "pix_fmt" ) )
592                                         params->pix_fmt = av_get_pix_fmt( value );
593 #endif
594                                 else if ( !strcmp( name, "width" ) )
595                                         params->width = atoi( value );
596                                 else if ( !strcmp( name, "height" ) )
597                                         params->height = atoi( value );
598                                 else if ( !strcmp( name, "standard" ) )
599                                 {
600                                         standard = strdup( value );
601                                         params->standard = standard;
602                                 }
603                                 else if ( !strcmp( name, "av" ) )
604                                         av = atoi( value );
605                         }
606                         free( name );
607                         mrl = strchr( mrl, '&' );
608                 }
609         }
610
611         // Now attempt to open the file
612         error = av_open_input_file( &context, file, format, 0, params ) < 0;
613
614         // Cleanup AVFormatParameters
615         free( standard );
616         free( params );
617
618         // If successful, then try to get additional info
619         if ( !error )
620         {
621                 // Get the stream info
622                 error = av_find_stream_info( context ) < 0;
623
624                 // Continue if no error
625                 if ( !error )
626                 {
627                         // We will default to the first audio and video streams found
628                         int audio_index = -1;
629                         int video_index = -1;
630
631                         // Find default audio and video streams
632                         find_default_streams( properties, context, &audio_index, &video_index );
633
634                         // Now set properties where we can (use default unknowns if required)
635                         if ( context->duration != AV_NOPTS_VALUE )
636                         {
637                                 // This isn't going to be accurate for all formats
638                                 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps - 1 );
639                                 
640                                 // Workaround some clips whose estimated duration cause problems:
641                                 // http://www.kdenlive.org/mantis/view.php?id=2003
642                                 char *comment = mlt_properties_get( properties, "meta.attr.comment.markup" );
643                                 if ( comment && strstr( comment, "KODAK" ) && strstr( comment, "Zx3" ) )
644                                         frames -= 2;
645                                 
646                                 mlt_properties_set_position( properties, "out", frames - 1 );
647                                 mlt_properties_set_position( properties, "length", frames );
648                         }
649
650                         if ( context->start_time != AV_NOPTS_VALUE )
651                                 self->start_time = context->start_time;
652
653                         // Check if we're seekable
654                         // avdevices are typically AVFMT_NOFILE and not seekable
655                         self->seekable = !format || !( format->flags & AVFMT_NOFILE );
656                         if ( context->pb )
657                         {
658                                 // protocols can indicate if they support seeking
659                                 URLContext *uc = url_fileno( context->pb );
660                                 if ( uc )
661                                         self->seekable = !uc->is_streamed;
662                         }
663                         if ( self->seekable )
664                         {
665                                 self->seekable = av_seek_frame( context, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
666                                 mlt_properties_set_int( properties, "seekable", self->seekable );
667                                 self->dummy_context = context;
668                                 av_open_input_file( &context, file, NULL, 0, NULL );
669                                 av_find_stream_info( context );
670                         }
671
672                         // Store selected audio and video indexes on properties
673                         self->audio_index = audio_index;
674                         self->video_index = video_index;
675                         self->first_pts = -1;
676                         self->last_position = POSITION_INITIAL;
677
678                         // Fetch the width, height and aspect ratio
679                         if ( video_index != -1 )
680                         {
681                                 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
682                                 mlt_properties_set_int( properties, "width", codec_context->width );
683                                 mlt_properties_set_int( properties, "height", codec_context->height );
684
685                                 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
686                                 {
687                                         // Fetch the first frame of DV so we can read it directly
688                                         AVPacket pkt;
689                                         int ret = 0;
690                                         while ( ret >= 0 )
691                                         {
692                                                 ret = av_read_frame( context, &pkt );
693                                                 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
694                                                 {
695                                                         get_aspect_ratio( properties, context->streams[ video_index ], codec_context, &pkt );
696                                                         break;
697                                                 }
698                                         }
699                                 }
700                                 else
701                                 {
702                                         get_aspect_ratio( properties, context->streams[ video_index ], codec_context, NULL );
703                                 }
704 #ifdef SWSCALE
705                                 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
706                                         codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
707                                 if ( context )
708                                         sws_freeContext( context );
709                                 else
710                                         error = 1;
711 #endif
712                         }
713
714                         // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
715                         if ( av == 0 && audio_index != -1 && video_index != -1 )
716                         {
717                                 // We'll use the open one as our video_format
718                                 self->video_format = context;
719
720                                 // And open again for our audio context
721                                 av_open_input_file( &context, file, NULL, 0, NULL );
722                                 av_find_stream_info( context );
723
724                                 // Audio context
725                                 self->audio_format = context;
726                         }
727                         else if ( av != 2 && video_index != -1 )
728                         {
729                                 // We only have a video context
730                                 self->video_format = context;
731                         }
732                         else if ( audio_index != -1 )
733                         {
734                                 // We only have an audio context
735                                 self->audio_format = context;
736                         }
737                         else
738                         {
739                                 // Something has gone wrong
740                                 error = -1;
741                         }
742                 }
743         }
744
745         // Unlock the mutex now
746         avformat_unlock( );
747
748         return error;
749 }
750
751 /** Convert a frame position to a time code.
752 */
753
754 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
755 {
756         return ( double )position / mlt_producer_get_fps( producer );
757 }
758
759                 // Collect information about all audio streams
760
761 static void get_audio_streams_info( producer_avformat self )
762 {
763         // Fetch the audio format context
764         AVFormatContext *context = self->audio_format;
765         int i;
766
767         for ( i = 0;
768                   i < context->nb_streams;
769                   i++ )
770         {
771                 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
772                 {
773                         AVCodecContext *codec_context = context->streams[i]->codec;
774                         AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
775
776                         // If we don't have a codec and we can't initialise it, we can't do much more...
777                         avformat_lock( );
778                         if ( codec && avcodec_open( codec_context, codec ) >= 0 )
779                         {
780                                 self->audio_streams++;
781                                 self->audio_max_stream = i;
782                                 self->total_channels += codec_context->channels;
783                                 if ( codec_context->channels > self->max_channel )
784                                         self->max_channel = codec_context->channels;
785                                 if ( codec_context->sample_rate > self->max_frequency )
786                                         self->max_frequency = codec_context->sample_rate;
787                                 avcodec_close( codec_context );
788                         }
789                         avformat_unlock( );
790                 }
791         }
792         mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
793                 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
794         
795         // Other audio-specific initializations
796         self->resample_factor = 1.0;
797 }
798
799 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
800 {
801 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
802         int *coefficients;
803         int full_range;
804         int brightness, contrast, saturation;
805
806         if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
807                         &brightness, &contrast, &saturation ) != -1 )
808         {
809                 // Don't change these from defaults unless explicitly told to.
810                 if ( use_full_range >= 0 )
811                         full_range = use_full_range;
812                 switch ( colorspace )
813                 {
814                 case 170:
815                 case 470:
816                 case 601:
817                 case 624:
818                         coefficients = sws_getCoefficients( SWS_CS_ITU601 );
819                         break;
820                 case 240:
821                         coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
822                         break;
823                 case 709:
824                         coefficients = sws_getCoefficients( SWS_CS_ITU709 );
825                         break;
826                 }
827                 sws_setColorspaceDetails( context, coefficients, full_range, coefficients, full_range,
828                         brightness, contrast, saturation );
829         }
830 #endif
831 }
832
833 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
834         mlt_image_format *format, int width, int height, int colorspace )
835 {
836 #ifdef SWSCALE
837         int full_range = -1;
838         int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
839
840 #ifdef USE_MMX
841         flags |= SWS_CPU_CAPS_MMX;
842 #endif
843 #ifdef USE_SSE
844         flags |= SWS_CPU_CAPS_MMX2;
845 #endif
846
847         if ( pix_fmt == PIX_FMT_RGB32 )
848         {
849                 *format = mlt_image_rgb24a;
850                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
851                         width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
852                 AVPicture output;
853                 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
854                 set_luma_transfer( context, colorspace, full_range );
855                 sws_scale( context, frame->data, frame->linesize, 0, height,
856                         output.data, output.linesize);
857                 sws_freeContext( context );
858         }
859         else if ( *format == mlt_image_yuv420p )
860         {
861                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
862                         width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
863                 AVPicture output;
864                 output.data[0] = buffer;
865                 output.data[1] = buffer + width * height;
866                 output.data[2] = buffer + ( 5 * width * height ) / 4;
867                 output.linesize[0] = width;
868                 output.linesize[1] = width >> 1;
869                 output.linesize[2] = width >> 1;
870                 set_luma_transfer( context, colorspace, full_range );
871                 sws_scale( context, frame->data, frame->linesize, 0, height,
872                         output.data, output.linesize);
873                 sws_freeContext( context );
874         }
875         else if ( *format == mlt_image_rgb24 )
876         {
877                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
878                         width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
879                 AVPicture output;
880                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
881                 set_luma_transfer( context, colorspace, full_range );
882                 sws_scale( context, frame->data, frame->linesize, 0, height,
883                         output.data, output.linesize);
884                 sws_freeContext( context );
885         }
886         else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
887         {
888                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
889                         width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
890                 AVPicture output;
891                 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
892                 set_luma_transfer( context, colorspace, full_range );
893                 sws_scale( context, frame->data, frame->linesize, 0, height,
894                         output.data, output.linesize);
895                 sws_freeContext( context );
896         }
897         else
898         {
899                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
900                         width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
901                 AVPicture output;
902                 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
903                 set_luma_transfer( context, colorspace, full_range );
904                 sws_scale( context, frame->data, frame->linesize, 0, height,
905                         output.data, output.linesize);
906                 sws_freeContext( context );
907         }
908 #else
909         if ( *format == mlt_image_yuv420p )
910         {
911                 AVPicture pict;
912                 pict.data[0] = buffer;
913                 pict.data[1] = buffer + width * height;
914                 pict.data[2] = buffer + ( 5 * width * height ) / 4;
915                 pict.linesize[0] = width;
916                 pict.linesize[1] = width >> 1;
917                 pict.linesize[2] = width >> 1;
918                 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
919         }
920         else if ( *format == mlt_image_rgb24 )
921         {
922                 AVPicture output;
923                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
924                 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
925         }
926         else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
927         {
928                 AVPicture output;
929                 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
930                 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
931         }
932         else
933         {
934                 AVPicture output;
935                 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
936                 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
937         }
938 #endif
939 }
940
941 /** Allocate the image buffer and set it on the frame.
942 */
943
944 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
945 {
946         int size = 0;
947
948         if ( codec_context->width == 0 || codec_context->height == 0 )
949                 return size;
950
951         *width = codec_context->width;
952         *height = codec_context->height;
953
954         if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
955                 size = *width * ( *height + 1 ) * 4;
956         else switch ( *format )
957         {
958                 case mlt_image_yuv420p:
959                         size = *width * 3 * ( *height + 1 ) / 2;
960                         break;
961                 case mlt_image_rgb24:
962                         size = *width * ( *height + 1 ) * 3;
963                         break;
964                 case mlt_image_rgb24a:
965                 case mlt_image_opengl:
966                         size = *width * ( *height + 1 ) * 4;
967                         break;
968                 default:
969                         *format = mlt_image_yuv422;
970                         size = *width * ( *height + 1 ) * 2;
971                         break;
972         }
973
974         // Construct the output image
975         *buffer = mlt_pool_alloc( size );
976         if ( *buffer )
977                 mlt_properties_set_data( frame_properties, "image", *buffer, size, mlt_pool_release, NULL );
978         else
979                 size = 0;
980
981         return size;
982 }
983
984 /** Get an image from a frame.
985 */
986
987 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
988 {
989         // Get the producer
990         producer_avformat self = mlt_frame_pop_service( frame );
991         mlt_service_lock( MLT_PRODUCER_SERVICE(self->parent) );
992         mlt_producer producer = self->parent;
993
994         // Get the properties from the frame
995         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
996
997         // Obtain the frame number of this frame
998         mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
999
1000         // Get the producer properties
1001         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1002
1003         // Fetch the video format context
1004         AVFormatContext *context = self->video_format;
1005
1006         // Get the video stream
1007         AVStream *stream = context->streams[ self->video_index ];
1008
1009         // Get codec context
1010         AVCodecContext *codec_context = stream->codec;
1011
1012         // Get the image cache
1013         if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1014                 self->image_cache = mlt_cache_init();
1015         if ( self->image_cache )
1016         {
1017                 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1018                 *buffer = mlt_cache_item_data( item, (int*) format );
1019                 if ( *buffer )
1020                 {
1021                         // Set the resolution
1022                         *width = codec_context->width;
1023                         *height = codec_context->height;
1024
1025                         // Workaround 1088 encodings missing cropping info.
1026                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1027                                 *height = 1080;
1028
1029                         // Cache hit
1030                         int size;
1031                         switch ( *format )
1032                         {
1033                                 case mlt_image_yuv420p:
1034                                         size = *width * 3 * ( *height + 1 ) / 2;
1035                                         break;
1036                                 case mlt_image_rgb24:
1037                                         size = *width * ( *height + 1 ) * 3;
1038                                         break;
1039                                 case mlt_image_rgb24a:
1040                                 case mlt_image_opengl:
1041                                         size = *width * ( *height + 1 ) * 4;
1042                                         break;
1043                                 default:
1044                                         *format = mlt_image_yuv422;
1045                                         size = *width * ( *height + 1 ) * 2;
1046                                         break;
1047                         }
1048                         mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1049                         mlt_properties_set_data( frame_properties, "image", *buffer, size, NULL, NULL );
1050                         // self->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1051                         self->got_picture = 1;
1052
1053                         goto exit_get_image;
1054                 }
1055         }
1056         // Cache miss
1057         int image_size = 0;
1058
1059         avformat_lock();
1060
1061         // Packet
1062         AVPacket pkt;
1063
1064         // Special case pause handling flag
1065         int paused = 0;
1066
1067         // Special case ffwd handling
1068         int ignore = 0;
1069
1070         // We may want to use the source fps if available
1071         double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1072                 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1073         double fps = mlt_producer_get_fps( producer );
1074
1075         // This is the physical frame position in the source
1076         int req_position = ( int )( position / fps * source_fps + 0.5 );
1077
1078         // Determines if we have to decode all frames in a sequence
1079         // Temporary hack to improve intra frame only
1080         int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1081                                   strcmp( codec_context->codec->name, "dvvideo" ) &&
1082                                   strcmp( codec_context->codec->name, "huffyuv" ) &&
1083                                   strcmp( codec_context->codec->name, "mjpeg" ) &&
1084                                   strcmp( codec_context->codec->name, "rawvideo" );
1085
1086         int last_position = self->last_position;
1087
1088         // Turn on usage of new seek API and PTS for seeking
1089         int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1090         if ( mlt_properties_get( properties, "new_seek" ) )
1091                 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1092
1093         // Seek if necessary
1094         if ( position != self->video_expected || last_position < 0 )
1095         {
1096                 if ( self->av_frame && position + 1 == self->video_expected )
1097                 {
1098                         // We're paused - use last image
1099                         paused = 1;
1100                 }
1101                 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1102                 {
1103                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
1104                         ignore = ( int )( ( position - self->video_expected ) / fps * source_fps );
1105                         codec_context->skip_loop_filter = AVDISCARD_NONREF;
1106                 }
1107                 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || last_position < 0 ) )
1108                 {
1109                         if ( use_new_seek && last_position == POSITION_INITIAL )
1110                         {
1111                                 // find first key frame
1112                                 int ret = 0;
1113                                 int toscan = 100;
1114
1115                                 while ( ret >= 0 && toscan-- > 0 )
1116                                 {
1117                                         ret = av_read_frame( context, &pkt );
1118                                         if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1119                                         {
1120                                                 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "first_pts %lld dts %lld pts_dts_delta %d\n", pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1121                                                 self->first_pts = pkt.pts;
1122                                                 toscan = 0;
1123                                         }
1124                                         av_free_packet( &pkt );
1125                                 }
1126                                 // Rewind
1127                                 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1128                         }
1129
1130                         // Calculate the timestamp for the requested frame
1131                         int64_t timestamp;
1132                         if ( use_new_seek )
1133                         {
1134                                 timestamp = ( req_position - 0.1 / source_fps ) /
1135                                         ( av_q2d( stream->time_base ) * source_fps );
1136                                 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
1137                                 if ( self->first_pts > 0 )
1138                                         timestamp += self->first_pts;
1139                                 else if ( context->start_time != AV_NOPTS_VALUE )
1140                                         timestamp += context->start_time;
1141                         }
1142                         else
1143                         {
1144                                 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1145                                 if ( context->start_time != AV_NOPTS_VALUE )
1146                                         timestamp += context->start_time;
1147                         }
1148                         if ( must_decode )
1149                                 timestamp -= AV_TIME_BASE;
1150                         if ( timestamp < 0 )
1151                                 timestamp = 0;
1152                         mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
1153                                 timestamp, position, self->video_expected, last_position );
1154
1155                         // Seek to the timestamp
1156                         if ( use_new_seek )
1157                         {
1158                                 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1159                                 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1160                         }
1161                         else if ( timestamp > 0 || last_position <= 0 )
1162                         {
1163                                 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1164                         }
1165                         else
1166                         {
1167                                 // Re-open video stream when rewinding to beginning from somewhere else.
1168                                 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1169                                 // not reliably seeking to the first frame across formats.
1170                                 if ( self->video_codec )
1171                                         avcodec_close( self->video_codec );
1172                                 self->video_codec = NULL;
1173                                 if ( self->dummy_context )
1174                                         av_close_input_file( self->dummy_context );
1175                                 self->dummy_context = NULL;
1176                                 if ( self->video_format )
1177                                         av_close_input_file( self->video_format );
1178                                 self->video_format = NULL;
1179                                 avformat_unlock();
1180                                 producer_set_up_video( self, frame );
1181                                 if ( self->video_index < 0 )
1182                                         return 1;
1183                                 avformat_lock();
1184                                 context = self->video_format;
1185                                 stream = context->streams[ self->video_index ];
1186                                 codec_context = stream->codec;
1187                         }
1188
1189                         // Remove the cached info relating to the previous position
1190                         self->current_position = POSITION_INVALID;
1191                         self->last_position = POSITION_INVALID;
1192                         av_freep( &self->av_frame );
1193
1194                         if ( use_new_seek )
1195                         {
1196                                 // flush any pictures still in decode buffer
1197                                 avcodec_flush_buffers( codec_context );
1198                         }
1199                 }
1200         }
1201
1202         // Duplicate the last image if necessary
1203         if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture && self->seekable
1204                  && ( paused
1205                           || self->current_position == req_position
1206                           || ( !use_new_seek && self->current_position > req_position ) ) )
1207         {
1208                 // Duplicate it
1209                 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1210                 {
1211                         // Workaround 1088 encodings missing cropping info.
1212                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1213                                 *height = 1080;
1214 #ifdef VDPAU
1215                         if ( self->vdpau && self->vdpau->buffer )
1216                         {
1217                                 AVPicture picture;
1218                                 picture.data[0] = self->vdpau->buffer;
1219                                 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1220                                 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1221                                 picture.linesize[0] = codec_context->width;
1222                                 picture.linesize[1] = codec_context->width / 2;
1223                                 picture.linesize[2] = codec_context->width / 2;
1224                                 convert_image( (AVFrame*) &picture, *buffer,
1225                                         PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1226                         }
1227                         else
1228 #endif
1229                         convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1230                                 format, *width, *height, self->colorspace );
1231                 }
1232                 else
1233                         mlt_frame_get_image( frame, buffer, format, width, height, writable );
1234         }
1235         else
1236         {
1237                 int ret = 0;
1238                 int int_position = 0;
1239                 int decode_errors = 0;
1240                 int got_picture = 0;
1241
1242                 av_init_packet( &pkt );
1243
1244                 // Construct an AVFrame for YUV422 conversion
1245                 if ( !self->av_frame )
1246                         self->av_frame = avcodec_alloc_frame( );
1247
1248                 while( ret >= 0 && !got_picture )
1249                 {
1250                         // Read a packet
1251                         ret = av_read_frame( context, &pkt );
1252
1253                         // We only deal with video from the selected video_index
1254                         if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1255                         {
1256                                 // Determine time code of the packet
1257                                 if ( use_new_seek )
1258                                 {
1259                                         int64_t pts = pkt.pts;
1260                                         if ( self->first_pts > 0 )
1261                                                 pts -= self->first_pts;
1262                                         else if ( context->start_time != AV_NOPTS_VALUE )
1263                                                 pts -= context->start_time;
1264                                         int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1265                                         if ( pkt.pts == AV_NOPTS_VALUE )
1266                                         {
1267                                                 self->invalid_pts_counter++;
1268                                                 if ( self->invalid_pts_counter > 20 )
1269                                                 {
1270                                                         mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1271                                                         mlt_properties_set_int( properties, "new_seek", 0 );
1272                                                         int_position = req_position;
1273                                                         use_new_seek = 0;
1274                                                 }
1275                                         }
1276                                         else
1277                                         {
1278                                                 self->invalid_pts_counter = 0;
1279                                         }
1280                                         mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1281                                                 pkt.pts, req_position, self->current_position, int_position );
1282                                 }
1283                                 else
1284                                 {
1285                                         if ( self->seekable && pkt.dts != AV_NOPTS_VALUE )
1286                                         {
1287                                                 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1288                                                 if ( context->start_time != AV_NOPTS_VALUE )
1289                                                         int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1290                                                 last_position = self->last_position;
1291                                                 if ( int_position == last_position )
1292                                                         int_position = last_position + 1;
1293                                         }
1294                                         else
1295                                         {
1296                                                 int_position = req_position;
1297                                         }
1298                                         mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1299                                                 pkt.dts, req_position, self->current_position, int_position );
1300                                         // Make a dumb assumption on streams that contain wild timestamps
1301                                         if ( abs( req_position - int_position ) > 999 )
1302                                         {
1303                                                 int_position = req_position;
1304                                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1305                                         }
1306                                 }
1307                                 self->last_position = int_position;
1308
1309                                 // Decode the image
1310                                 if ( must_decode || int_position >= req_position )
1311                                 {
1312 #ifdef VDPAU
1313                                         if ( g_vdpau && self->vdpau )
1314                                         {
1315                                                 if ( g_vdpau->producer != self )
1316                                                 {
1317                                                         vdpau_decoder_close();
1318                                                         vdpau_decoder_init( self );
1319                                                 }
1320                                                 if ( self->vdpau )
1321                                                         self->vdpau->is_decoded = 0;
1322                                         }
1323 #endif
1324                                         codec_context->reordered_opaque = pkt.pts;
1325                                         if ( int_position >= req_position )
1326                                                 codec_context->skip_loop_filter = AVDISCARD_NONE;
1327 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1328                                         ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1329 #else
1330                                         ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1331 #endif
1332                                         // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1333                                         if ( ret < 0 )
1334                                         {
1335                                                 if ( ++decode_errors <= 10 )
1336                                                         ret = 0;
1337                                         }
1338                                         else
1339                                         {
1340                                                 decode_errors = 0;
1341                                         }
1342                                 }
1343
1344                                 if ( got_picture )
1345                                 {
1346                                         if ( use_new_seek )
1347                                         {
1348                                                 // Determine time code of the packet
1349                                                 int64_t pts = self->av_frame->reordered_opaque;
1350                                                 if ( self->first_pts > 0 )
1351                                                         pts -= self->first_pts;
1352                                                 else if ( context->start_time != AV_NOPTS_VALUE )
1353                                                         pts -= context->start_time;
1354                                                 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1355                                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1356                                         }
1357                                         // Handle ignore
1358                                         if ( int_position < req_position )
1359                                         {
1360                                                 ignore = 0;
1361                                                 got_picture = 0;
1362                                         }
1363                                         else if ( int_position >= req_position )
1364                                         {
1365                                                 ignore = 0;
1366                                                 codec_context->skip_loop_filter = AVDISCARD_NONE;
1367                                         }
1368                                         else if ( ignore -- )
1369                                         {
1370                                                 got_picture = 0;
1371                                         }
1372                                 }
1373                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1374                         }
1375
1376                         // Now handle the picture if we have one
1377                         if ( got_picture )
1378                         {
1379                                 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1380                                 {
1381                                         // Workaround 1088 encodings missing cropping info.
1382                                         if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1383                                                 *height = 1080;
1384 #ifdef VDPAU
1385                                         if ( self->vdpau )
1386                                         {
1387                                                 if ( self->vdpau->is_decoded )
1388                                                 {
1389                                                         struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1390                                                         void *planes[3];
1391                                                         uint32_t pitches[3];
1392                                                         VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1393                                                         
1394                                                         if ( !self->vdpau->buffer )
1395                                                                 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1396                                                         self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1397                                                         self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1398                                                         self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1399                                                         self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1400                                                         self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1401                                                         self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1402
1403                                                         VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1404                                                         if ( status == VDP_STATUS_OK )
1405                                                         {
1406                                                                 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1407                                                                         format, *width, *height, self->colorspace );
1408                                                         }
1409                                                         else
1410                                                         {
1411                                                                 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1412                                                                 self->vdpau->is_decoded = 0;
1413                                                         }
1414                                                 }
1415                                                 else
1416                                                 {
1417                                                         mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1418                                                         got_picture = 0;
1419                                                 }
1420                                         }
1421                                         else
1422 #endif
1423                                         convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1424                                                 format, *width, *height, self->colorspace );
1425                                         self->top_field_first |= self->av_frame->top_field_first;
1426                                         self->current_position = int_position;
1427                                         self->got_picture = 1;
1428                                 }
1429                                 else
1430                                 {
1431                                         got_picture = 0;
1432                                 }
1433                         }
1434                         if ( ret >= 0 )
1435                                 av_free_packet( &pkt );
1436                 }
1437         }
1438
1439         avformat_unlock();
1440
1441         if ( self->got_picture && image_size > 0 && self->image_cache )
1442         {
1443                 // Copy buffer to image cache   
1444                 uint8_t *image = mlt_pool_alloc( image_size );
1445                 memcpy( image, *buffer, image_size );
1446                 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1447         }
1448
1449         // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1450         self->video_expected = position + 1;
1451
1452 exit_get_image:
1453         // Set the progressive flag
1454         if ( mlt_properties_get( properties, "force_progressive" ) )
1455                 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1456         else if ( self->av_frame )
1457                 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1458
1459         // Set the field order property for this frame
1460         if ( mlt_properties_get( properties, "force_tff" ) )
1461                 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1462         else
1463                 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1464
1465         // Set immutable properties of the selected track's (or overridden) source attributes.
1466         mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1467         mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1468
1469         mlt_service_unlock( MLT_PRODUCER_SERVICE(self->parent) );
1470
1471         return !self->got_picture;
1472 }
1473
1474 /** Process properties as AVOptions and apply to AV context obj
1475 */
1476
1477 static void apply_properties( void *obj, mlt_properties properties, int flags )
1478 {
1479         int i;
1480         int count = mlt_properties_count( properties );
1481         for ( i = 0; i < count; i++ )
1482         {
1483                 const char *opt_name = mlt_properties_get_name( properties, i );
1484                 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1485                 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1486                 {
1487                         if ( opt )
1488 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1489                                 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1490 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1491                                 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1492 #else
1493                                 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1494 #endif
1495                 }
1496         }
1497 }
1498
1499 /** Initialize the video codec context.
1500  */
1501
1502 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1503 {
1504         // Initialise the codec if necessary
1505         if ( !self->video_codec )
1506         {
1507                 // Get the video stream
1508                 AVStream *stream = self->video_format->streams[ index ];
1509
1510                 // Get codec context
1511                 AVCodecContext *codec_context = stream->codec;
1512
1513                 // Find the codec
1514                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1515 #ifdef VDPAU
1516                 if ( codec_context->codec_id == CODEC_ID_H264 )
1517                 {
1518                         if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1519                         {
1520                                 if ( vdpau_init( self ) )
1521                                 {
1522                                         self->video_codec = codec_context;
1523                                         if ( !vdpau_decoder_init( self ) )
1524                                                 vdpau_decoder_close();
1525                                 }
1526                         }
1527                         if ( !self->vdpau )
1528                                 codec = avcodec_find_decoder( codec_context->codec_id );
1529                 }
1530 #endif
1531
1532                 // Initialise multi-threading
1533                 int thread_count = mlt_properties_get_int( properties, "threads" );
1534                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1535                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1536                 if ( thread_count > 1 )
1537                 {
1538                         avcodec_thread_init( codec_context, thread_count );
1539                         codec_context->thread_count = thread_count;
1540                 }
1541
1542                 // If we don't have a codec and we can't initialise it, we can't do much more...
1543                 avformat_lock( );
1544                 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1545                 {
1546                         // Now store the codec with its destructor
1547                         self->video_codec = codec_context;
1548                 }
1549                 else
1550                 {
1551                         // Remember that we can't use this later
1552                         self->video_index = -1;
1553                 }
1554                 avformat_unlock( );
1555
1556                 // Process properties as AVOptions
1557                 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1558
1559                 // Reset some image properties
1560                 mlt_properties_set_int( properties, "width", self->video_codec->width );
1561                 mlt_properties_set_int( properties, "height", self->video_codec->height );
1562                 // For DV, we'll just use the saved aspect ratio
1563                 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1564                         get_aspect_ratio( properties, stream, self->video_codec, NULL );
1565
1566                 // Determine the fps first from the codec
1567                 double source_fps = (double) self->video_codec->time_base.den /
1568                                                                    ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1569                 
1570                 if ( mlt_properties_get( properties, "force_fps" ) )
1571                 {
1572                         source_fps = mlt_properties_get_double( properties, "force_fps" );
1573                         stream->time_base = av_d2q( source_fps, 1024 );
1574                         mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1575                         mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1576                 }
1577                 else
1578                 {
1579                         // If the muxer reports a frame rate different than the codec
1580 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1581                         double muxer_fps = av_q2d( stream->avg_frame_rate );
1582                         if ( muxer_fps == 0 ) muxer_fps = av_q2d( stream->r_frame_rate );
1583 #else
1584                         double muxer_fps = av_q2d( stream->r_frame_rate );
1585 #endif
1586                         // Choose the lesser - the wrong tends to be off by some multiple of 10
1587                         source_fps = FFMIN( source_fps, muxer_fps );
1588                         if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1589                         {
1590                                 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1591                                 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1592                         }
1593                         else if ( muxer_fps > 0 )
1594                         {
1595                                 AVRational frame_rate = stream->r_frame_rate;
1596                                 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1597                                 // avg_frame_rate gives some approximate value that does not well match the media.
1598                                 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1599                                 // results in some very choppy output, but some value slightly different works
1600                                 // great.
1601 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1602                                 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1603                                         frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1604 #endif
1605                                 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1606                                 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1607                         }
1608                         else
1609                         {
1610                                 source_fps = mlt_producer_get_fps( self->parent );
1611                                 AVRational frame_rate = av_d2q( source_fps, 255 );
1612                                 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1613                                 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1614                         }
1615                 }
1616
1617                 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1618                 if ( source_fps > 0 )
1619                         mlt_properties_set_double( properties, "source_fps", source_fps );
1620                 else
1621                         mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1622
1623                 // Set the YUV colorspace from override or detect
1624                 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1625 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)               
1626                 if ( ! self->colorspace )
1627                 {
1628                         switch ( self->video_codec->colorspace )
1629                         {
1630                         case AVCOL_SPC_SMPTE240M:
1631                                 self->colorspace = 240;
1632                                 break;
1633                         case AVCOL_SPC_BT470BG:
1634                         case AVCOL_SPC_SMPTE170M:
1635                                 self->colorspace = 601;
1636                                 break;
1637                         case AVCOL_SPC_BT709:
1638                                 self->colorspace = 709;
1639                                 break;
1640                         default:
1641                                 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1642                                 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1643                                 break;
1644                         }
1645                 }
1646 #endif
1647                 // Let apps get chosen colorspace
1648                 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1649         }
1650         return self->video_codec && self->video_index > -1;
1651 }
1652
1653 /** Set up video handling.
1654 */
1655
1656 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1657 {
1658         // Get the producer
1659         mlt_producer producer = self->parent;
1660
1661         // Get the properties
1662         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1663
1664         // Fetch the video format context
1665         AVFormatContext *context = self->video_format;
1666
1667         // Get the video_index
1668         int index = mlt_properties_get_int( properties, "video_index" );
1669
1670         // Reopen the file if necessary
1671         if ( !context && index > -1 )
1672         {
1673                 mlt_events_block( properties, producer );
1674                 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1675                         mlt_properties_get( properties, "resource" ) );
1676                 context = self->video_format;
1677                 if ( self->dummy_context )
1678                 {
1679                         avformat_lock();
1680                         av_close_input_file( self->dummy_context );
1681                         avformat_unlock();
1682                 }
1683                 self->dummy_context = NULL;
1684                 mlt_events_unblock( properties, producer );
1685                 if ( self->audio_format )
1686                         get_audio_streams_info( self );
1687
1688                 // Process properties as AVOptions
1689                 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1690         }
1691
1692         // Exception handling for video_index
1693         if ( context && index >= (int) context->nb_streams )
1694         {
1695                 // Get the last video stream
1696                 for ( index = context->nb_streams - 1;
1697                           index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1698                           index-- );
1699                 mlt_properties_set_int( properties, "video_index", index );
1700         }
1701         if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1702         {
1703                 // Invalidate the video stream
1704                 index = -1;
1705                 mlt_properties_set_int( properties, "video_index", index );
1706         }
1707
1708         // Update the video properties if the index changed
1709         if ( index != self->video_index )
1710         {
1711                 // Reset the video properties if the index changed
1712                 self->video_index = index;
1713                 if ( self->video_codec )
1714                 {
1715                         avformat_lock();
1716                         avcodec_close( self->video_codec );
1717                         avformat_unlock();
1718                 }
1719                 self->video_codec = NULL;
1720         }
1721
1722         // Get the frame properties
1723         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1724
1725         // Get the codec
1726         if ( context && index > -1 && video_codec_init( self, index, properties ) )
1727         {
1728                 // Set the frame properties
1729                 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1730                 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1731                         force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1732
1733                 // Set the width and height
1734                 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1735                 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1736                 // real_width and real_height are deprecated in favor of meta.media.width and .height
1737                 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1738                 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1739                 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1740                 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1741                 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1742                 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1743
1744                 // Workaround 1088 encodings missing cropping info.
1745                 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1746                 {
1747                         mlt_properties_set_int( properties, "meta.media.height", 1080 );
1748                         mlt_properties_set_int( frame_properties, "real_height", 1080 );
1749                 }
1750
1751                 // Add our image operation
1752                 mlt_frame_push_service( frame, self );
1753                 mlt_frame_push_get_image( frame, producer_get_image );
1754         }
1755         else
1756         {
1757                 // If something failed, use test card image
1758                 mlt_properties_set_int( frame_properties, "test_image", 1 );
1759         }
1760 }
1761
1762 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1763 {
1764         int paused = 0;
1765
1766         // Seek if necessary
1767         if ( position != self->audio_expected )
1768         {
1769                 if ( position + 1 == self->audio_expected )
1770                 {
1771                         // We're paused - silence required
1772                         paused = 1;
1773                 }
1774                 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1775                 {
1776                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
1777                         *ignore = position - self->audio_expected;
1778                 }
1779                 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1780                 {
1781                         AVFormatContext *context = self->audio_format;
1782                         int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1783                         if ( context->start_time != AV_NOPTS_VALUE )
1784                                 timestamp += context->start_time;
1785                         if ( timestamp < 0 )
1786                                 timestamp = 0;
1787
1788                         // Set to the real timecode
1789                         avformat_lock();
1790                         if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1791                                 paused = 1;
1792                         avformat_unlock();
1793
1794                         // Clear the usage in the audio buffer
1795                         int i = MAX_AUDIO_STREAMS + 1;
1796                         while ( --i )
1797                                 self->audio_used[i - 1] = 0;
1798                 }
1799         }
1800         return paused;
1801 }
1802
1803 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1804 {
1805         // Fetch the audio_format
1806         AVFormatContext *context = self->audio_format;
1807
1808         // Get the current stream index
1809         int index = pkt.stream_index;
1810
1811         // Get codec context
1812         AVCodecContext *codec_context = self->audio_codec[ index ];
1813
1814         // Obtain the resample context if it exists (not always needed)
1815         ReSampleContext *resample = self->audio_resample[ index ];
1816
1817         // Obtain the audio buffers
1818         int16_t *audio_buffer = self->audio_buffer[ index ];
1819         int16_t *decode_buffer = self->decode_buffer[ index ];
1820
1821         int audio_used = self->audio_used[ index ];
1822         uint8_t *ptr = pkt.data;
1823         int len = pkt.size;
1824         int ret = 0;
1825
1826         while ( ptr && ret >= 0 && len > 0 )
1827         {
1828                 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1829
1830                 // Decode the audio
1831 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1832                 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, &pkt );
1833 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1834                 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1835 #else
1836                 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1837 #endif
1838                 if ( ret < 0 )
1839                 {
1840                         mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
1841                         break;
1842                 }
1843
1844                 pkt.size = len -= ret;
1845                 pkt.data = ptr += ret;
1846
1847                 // If decoded successfully
1848                 if ( data_size > 0 )
1849                 {
1850                         // Figure out how many samples will be needed after resampling
1851                         int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1852                         int samples_needed = self->resample_factor * convert_samples + 1;
1853                         
1854                         // Resize audio buffer to prevent overflow
1855                         if ( audio_used * channels + samples_needed > self->audio_buffer_size[ index ] )
1856                         {
1857                                 self->audio_buffer_size[ index ] *= 2;
1858                                 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] * sizeof(int16_t) );
1859                         }
1860                         if ( resample )
1861                         {
1862                                 // Copy to audio buffer while resampling
1863                                 int16_t *source = decode_buffer;
1864                                 int16_t *dest = &audio_buffer[ audio_used * channels ];
1865                                 avformat_lock();
1866                                 audio_used += audio_resample( resample, dest, source, convert_samples );
1867                                 avformat_unlock();
1868                         }
1869                         else
1870                         {
1871                                 // Straight copy to audio buffer
1872                                 memcpy( &audio_buffer[ audio_used * codec_context->channels ], decode_buffer, data_size );
1873                                 audio_used += convert_samples;
1874                         }
1875
1876                         // Handle ignore
1877                         while ( *ignore && audio_used > samples )
1878                         {
1879                                 *ignore -= 1;
1880                                 audio_used -= samples;
1881                                 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) ],
1882                                          audio_used * sizeof( int16_t ) );
1883                         }
1884                 }
1885         }
1886
1887         // If we're behind, ignore this packet
1888         if ( pkt.pts >= 0 )
1889         {
1890                 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
1891                 int req_position = ( int )( timecode * fps + 0.5 );
1892                 int int_position = ( int )( current_pts * fps + 0.5 );
1893                 if ( context->start_time != AV_NOPTS_VALUE )
1894                         int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1895
1896                 if ( self->seekable && *ignore == 0 )
1897                 {
1898                         if ( int_position < req_position )
1899                                 // We are behind, so skip some
1900                                 *ignore = 1;
1901                         else if ( int_position > req_position + 2 )
1902                                 // We are ahead, so seek backwards some more
1903                                 seek_audio( self, req_position, timecode - 1.0, ignore );
1904                 }
1905         }
1906
1907         self->audio_used[ index ] = audio_used;
1908
1909         return ret;
1910 }
1911
1912 /** Get the audio from a frame.
1913 */
1914
1915 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1916 {
1917         // Get the producer
1918         producer_avformat self = mlt_frame_pop_audio( frame );
1919
1920         mlt_service_lock( MLT_PRODUCER_SERVICE(self->parent) );
1921         
1922         // Obtain the frame number of this frame
1923         mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1924
1925         // Calculate the real time code
1926         double real_timecode = producer_time_of_frame( self->parent, position );
1927
1928         // Get the producer fps
1929         double fps = mlt_producer_get_fps( self->parent );
1930
1931         // Number of frames to ignore (for ffwd)
1932         int ignore = 0;
1933
1934         // Flag for paused (silence)
1935         int paused = seek_audio( self, position, real_timecode, &ignore );
1936
1937         // Fetch the audio_format
1938         AVFormatContext *context = self->audio_format;
1939         
1940         // Determine the tracks to use
1941         int index = self->audio_index;
1942         int index_max = self->audio_index + 1;
1943         if ( self->audio_index == INT_MAX )
1944         {
1945                 index = 0;
1946                 index_max = context->nb_streams;
1947                 *channels = self->total_channels;
1948                 *frequency = self->max_frequency;
1949         }
1950
1951         // Initialize the resamplers and buffers
1952         for ( ; index < index_max; index++ )
1953         {
1954                 // Get codec context
1955                 AVCodecContext *codec_context = self->audio_codec[ index ];
1956
1957                 if ( codec_context && !self->audio_buffer[ index ] )
1958                 {
1959                         // Check for resample and create if necessary
1960                         if ( codec_context->channels <= 2 )
1961                         {
1962                                 // Determine by how much resampling will increase number of samples
1963                                 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
1964                                 resample_factor *= (double) *frequency / codec_context->sample_rate;
1965                                 if ( resample_factor > self->resample_factor )
1966                                         self->resample_factor = resample_factor;
1967                                 
1968                                 // Create the resampler
1969 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1970                                 self->audio_resample[ index ] = av_audio_resample_init(
1971                                         self->audio_index == INT_MAX ? codec_context->channels : *channels,
1972                                         codec_context->channels, *frequency, codec_context->sample_rate,
1973                                         SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1974 #else
1975                                 self->audio_resample[ index ] = audio_resample_init(
1976                                         self->audio_index == INT_MAX ? codec_context->channels : *channels,
1977                                         codec_context->channels, *frequency, codec_context->sample_rate );
1978 #endif
1979                         }
1980                         else
1981                         {
1982                                 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
1983                         }
1984
1985                         // Check for audio buffer and create if necessary
1986                         self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1987                         self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] * sizeof( int16_t ) );
1988
1989                         // Check for decoder buffer and create if necessary
1990                         self->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1991                 }
1992         }
1993
1994         // Get the audio if required
1995         if ( !paused )
1996         {
1997                 int ret = 0;
1998                 int got_audio = 0;
1999                 AVPacket pkt;
2000
2001                 av_init_packet( &pkt );
2002                 
2003                 // If not resampling, give consumer more than requested.
2004                 // It requested number samples based on requested frame rate.
2005                 // Do not clean this up with a samples *= ...!
2006                 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2007                         *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2008
2009                 while ( ret >= 0 && !got_audio )
2010                 {
2011                         // Check if the buffer already contains the samples required
2012                         if ( self->audio_index != INT_MAX && self->audio_used[ self->audio_index ] >= *samples && ignore == 0 )
2013                         {
2014                                 got_audio = 1;
2015                                 break;
2016                         }
2017
2018                         // Read a packet
2019                         avformat_lock();
2020                         ret = av_read_frame( context, &pkt );
2021                         avformat_unlock();
2022
2023                         // We only deal with audio from the selected audio index
2024                         if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == self->audio_index ||
2025                                  ( self->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2026                         {
2027                                 int channels2 = self->audio_index == INT_MAX ? self->audio_codec[pkt.stream_index]->channels : *channels;
2028                                 ret = decode_audio( self, &ignore, pkt, channels2, *samples, real_timecode, fps );
2029                         }
2030                         av_free_packet( &pkt );
2031
2032                         if ( self->audio_index == INT_MAX && ret >= 0 )
2033                         {
2034                                 // Determine if there is enough audio for all streams
2035                                 got_audio = 1;
2036                                 for ( index = 0; index < context->nb_streams; index++ )
2037                                 {
2038                                         if ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples )
2039                                                 got_audio = 0;
2040                                 }
2041                         }
2042                 }
2043                 
2044                 // Allocate and set the frame's audio buffer
2045                 int size = *samples * *channels * sizeof(int16_t);
2046                 *buffer = mlt_pool_alloc( size );
2047                 *format = mlt_audio_s16;
2048                 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2049
2050                 // Interleave tracks if audio_index=all
2051                 if ( self->audio_index == INT_MAX )
2052                 {
2053                         int16_t *dest = *buffer;
2054                         int i;
2055                         for ( i = 0; i < *samples; i++ )
2056                         {
2057                                 for ( index = 0; index < index_max; index++ )
2058                                 if ( self->audio_codec[ index ] )
2059                                 {
2060                                         int current_channels = self->audio_codec[ index ]->channels;
2061                                         int16_t *src = self->audio_buffer[ index ] + i * current_channels;
2062                                         memcpy( dest, src, current_channels * sizeof(int16_t) );
2063                                         dest += current_channels;
2064                                 }
2065                         }
2066                         for ( index = 0; index < index_max; index++ )
2067                         if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2068                         {
2069                                 int current_channels = self->audio_codec[ index ]->channels;
2070                                 int16_t *src = self->audio_buffer[ index ] + *samples * current_channels;
2071                                 self->audio_used[index] -= *samples;
2072                                 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof(int16_t) );
2073                         }
2074                 }
2075                 // Copy a single track to the output buffer
2076                 else
2077                 {
2078                         index = self->audio_index;
2079
2080                         // Now handle the audio if we have enough
2081                         if ( self->audio_used[ index ] > 0 )
2082                         {
2083                                 int16_t *src = self->audio_buffer[ index ];
2084                                 *samples = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2085                                 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
2086                                 self->audio_used[ index ] -= *samples;
2087                                 memmove( src, &src[ *samples * *channels ], self->audio_used[ index ] * *channels * sizeof(int16_t) );
2088                         }
2089                         else
2090                         {
2091                                 // Otherwise fill with silence
2092                                 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
2093                         }
2094                         if ( !self->audio_resample[ index ] )
2095                         {
2096                                 // TODO: uncomment and remove following line when full multi-channel support is ready
2097                                 // *channels = codec_context->channels;
2098                                 *frequency = self->audio_codec[ index ]->sample_rate;
2099                         }
2100                 }
2101         }
2102         else
2103         {
2104                 // Get silence and don't touch the context
2105                 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2106         }
2107         
2108         // Regardless of speed (other than paused), we expect to get the next frame
2109         if ( !paused )
2110                 self->audio_expected = position + 1;
2111
2112         mlt_service_unlock( MLT_PRODUCER_SERVICE(self->parent) );
2113
2114         return 0;
2115 }
2116
2117 /** Initialize the audio codec context.
2118 */
2119
2120 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2121 {
2122         // Initialise the codec if necessary
2123         if ( !self->audio_codec[ index ] )
2124         {
2125                 // Get codec context
2126                 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2127
2128                 // Find the codec
2129                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2130
2131                 // If we don't have a codec and we can't initialise it, we can't do much more...
2132                 avformat_lock( );
2133                 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2134                 {
2135                         // Now store the codec with its destructor
2136                         if ( self->audio_codec[ index ] )
2137                                 avcodec_close( self->audio_codec[ index ] );
2138                         self->audio_codec[ index ] = codec_context;
2139                 }
2140                 else
2141                 {
2142                         // Remember that we can't use self later
2143                         self->audio_index = -1;
2144                 }
2145                 avformat_unlock( );
2146
2147                 // Process properties as AVOptions
2148                 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2149         }
2150         return self->audio_codec[ index ] && self->audio_index > -1;
2151 }
2152
2153 /** Set up audio handling.
2154 */
2155
2156 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2157 {
2158         // Get the producer
2159         mlt_producer producer = self->parent;
2160
2161         // Get the properties
2162         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2163
2164         // Fetch the audio format context
2165         AVFormatContext *context = self->audio_format;
2166
2167         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2168
2169         // Get the audio_index
2170         int index = mlt_properties_get_int( properties, "audio_index" );
2171
2172         // Handle all audio tracks
2173         if ( self->audio_index > -1 &&
2174              mlt_properties_get( properties, "audio_index" ) &&
2175              !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2176                 index = INT_MAX;
2177
2178         // Reopen the file if necessary
2179         if ( !context && self->audio_index > -1 && index > -1 )
2180         {
2181                 mlt_events_block( properties, producer );
2182                 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2183                         mlt_properties_get( properties, "resource" ) );
2184                 context = self->audio_format;
2185                 if ( self->dummy_context )
2186                 {
2187                         avformat_lock();
2188                         av_close_input_file( self->dummy_context );
2189                         avformat_unlock();
2190                 }
2191                 self->dummy_context = NULL;
2192                 mlt_events_unblock( properties, producer );
2193                 get_audio_streams_info( self );
2194         }
2195
2196         // Exception handling for audio_index
2197         if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2198         {
2199                 for ( index = context->nb_streams - 1;
2200                           index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2201                           index-- );
2202                 mlt_properties_set_int( properties, "audio_index", index );
2203         }
2204         if ( context && index > -1 && index < INT_MAX &&
2205                  context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2206         {
2207                 index = self->audio_index;
2208                 mlt_properties_set_int( properties, "audio_index", index );
2209         }
2210
2211         // Update the audio properties if the index changed
2212         if ( context && index > -1 && index != self->audio_index )
2213         {
2214                 if ( self->audio_codec[ self->audio_index ] )
2215                 {
2216                         avformat_lock();
2217                         avcodec_close( self->audio_codec[ self->audio_index ] );
2218                         avformat_unlock();
2219                 }
2220                 self->audio_codec[ self->audio_index ] = NULL;
2221         }
2222         if ( self->audio_index != -1 )
2223                 self->audio_index = index;
2224         else
2225                 index = -1;
2226
2227         // Get the codec(s)
2228         if ( context && index == INT_MAX )
2229         {
2230                 mlt_properties_set_int( frame_properties, "frequency", self->max_frequency );
2231                 mlt_properties_set_int( frame_properties, "channels", self->total_channels );
2232                 for ( index = 0; index < context->nb_streams; index++ )
2233                 {
2234                         if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2235                                 audio_codec_init( self, index, properties );
2236                 }
2237         }
2238         else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2239         {
2240                 // Set the frame properties
2241                 if ( index < INT_MAX )
2242                 {
2243                         mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2244                         mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2245                 }
2246         }
2247         if ( context && index > -1 )
2248         {
2249                 // Add our audio operation
2250                 mlt_frame_push_audio( frame, self );
2251                 mlt_frame_push_audio( frame, producer_get_audio );
2252         }
2253 }
2254
2255 /** Our get frame implementation.
2256 */
2257
2258 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2259 {
2260         // Access the private data
2261         mlt_service service = MLT_PRODUCER_SERVICE( producer );
2262         mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2263         producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2264
2265         // If cache miss
2266         if ( !self )
2267         {
2268                 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2269                 producer->child = self;
2270                 self->parent = producer;
2271                 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2272                 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2273         }
2274
2275         // Create an empty frame
2276         *frame = mlt_frame_init( service);
2277         
2278         if ( *frame )
2279         {
2280                 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2281         }
2282         else
2283         {
2284                 mlt_cache_item_close( cache_item );
2285                 return 1;
2286         }
2287
2288         // Update timecode on the frame we're creating
2289         mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2290
2291         // Set the position of this producer
2292         mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2293         
2294         // Set up the video
2295         producer_set_up_video( self, *frame );
2296
2297         // Set up the audio
2298         producer_set_up_audio( self, *frame );
2299
2300         // Calculate the next timecode
2301         mlt_producer_prepare_next( producer );
2302
2303         return 0;
2304 }
2305
2306 static void producer_avformat_close( producer_avformat self )
2307 {
2308         mlt_log_debug( NULL, "producer_avformat_close\n" );
2309         // Close the file
2310         av_free( self->av_frame );
2311         avformat_lock();
2312         int i;
2313         for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2314         {
2315                 if ( self->audio_resample[i] )
2316                         audio_resample_close( self->audio_resample[i] );
2317                 mlt_pool_release( self->audio_buffer[i] );
2318                 av_free( self->decode_buffer[i] );
2319                 if ( self->audio_codec[i] )
2320                         avcodec_close( self->audio_codec[i] );
2321         }
2322         if ( self->video_codec )
2323                 avcodec_close( self->video_codec );
2324         if ( self->dummy_context )
2325                 av_close_input_file( self->dummy_context );
2326         if ( self->audio_format )
2327                 av_close_input_file( self->audio_format );
2328         if ( self->video_format )
2329                 av_close_input_file( self->video_format );
2330         avformat_unlock();
2331 #ifdef VDPAU
2332         vdpau_producer_close( self );
2333 #endif
2334         if ( self->image_cache )
2335                 mlt_cache_close( self->image_cache );
2336         free( self );
2337 }
2338
2339 static void producer_close( mlt_producer parent )
2340 {
2341         // Close the parent
2342         parent->close = NULL;
2343         mlt_producer_close( parent );
2344
2345         // Free the memory
2346         free( parent );
2347 }