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