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