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