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