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