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