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