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