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