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