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