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