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