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