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