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