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