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