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