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