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