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