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