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