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