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