]> git.sesse.net Git - mlt/blob - src/modules/avformat/producer_avformat.c
818206f646f3fcd3077fe055ec5cb4e04de46e87
[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_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_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_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_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_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         // Fetch the video format context
835         AVFormatContext *context = this->video_format;
836
837         // Get the video stream
838         AVStream *stream = context->streams[ this->video_index ];
839
840         // Get codec context
841         AVCodecContext *codec_context = stream->codec;
842
843         // Get the image cache
844         if ( ! this->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
845                 this->image_cache = mlt_cache_init();
846         if ( this->image_cache )
847         {
848                 mlt_cache_item item = mlt_cache_get( this->image_cache, (void*) position );
849                 *buffer = mlt_cache_item_data( item, format );
850                 if ( *buffer )
851                 {
852                         // Set the resolution
853                         *width = codec_context->width;
854                         *height = codec_context->height;
855                         mlt_properties_set_int( frame_properties, "width", *width );
856                         mlt_properties_set_int( frame_properties, "height", *height );
857
858                         // Cache hit
859                         int size;
860                         switch ( *format )
861                         {
862                                 case mlt_image_yuv420p:
863                                         size = *width * 3 * ( *height + 1 ) / 2;
864                                         break;
865                                 case mlt_image_rgb24:
866                                         size = *width * ( *height + 1 ) * 3;
867                                         break;
868                                 case mlt_image_rgb24a:
869                                 case mlt_image_opengl:
870                                         size = *width * ( *height + 1 ) * 4;
871                                         break;
872                                 default:
873                                         *format = mlt_image_yuv422;
874                                         size = *width * ( *height + 1 ) * 2;
875                                         break;
876                         }
877                         mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
878                         mlt_properties_set_data( frame_properties, "image", *buffer, size, NULL, NULL );
879                         this->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
880                         this->got_picture = 1;
881
882                         goto exit_get_image;
883                 }
884         }
885         // Cache miss
886         int image_size = 0;
887
888         avformat_lock();
889
890         // Packet
891         AVPacket pkt;
892
893         // Special case pause handling flag
894         int paused = 0;
895
896         // Special case ffwd handling
897         int ignore = 0;
898
899         // We may want to use the source fps if available
900         double source_fps = mlt_properties_get_double( properties, "source_fps" );
901         double fps = mlt_producer_get_fps( producer );
902
903         // This is the physical frame position in the source
904         int req_position = ( int )( position / fps * source_fps + 0.5 );
905
906         // Determines if we have to decode all frames in a sequence
907         // Temporary hack to improve intra frame only
908         int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
909                                   strcmp( codec_context->codec->name, "dvvideo" ) &&
910                                   strcmp( codec_context->codec->name, "huffyuv" ) &&
911                                   strcmp( codec_context->codec->name, "mjpeg" ) &&
912                                   strcmp( codec_context->codec->name, "rawvideo" );
913
914         int last_position = this->last_position;
915
916         // Turn on usage of new seek API and PTS for seeking
917         int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
918         if ( mlt_properties_get( properties, "new_seek" ) )
919                 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
920
921         // Seek if necessary
922         if ( position != this->video_expected || last_position < 0 )
923         {
924                 if ( this->av_frame && position + 1 == this->video_expected )
925                 {
926                         // We're paused - use last image
927                         paused = 1;
928                 }
929                 else if ( !this->seekable && position > this->video_expected && ( position - this->video_expected ) < 250 )
930                 {
931                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
932                         ignore = ( int )( ( position - this->video_expected ) / fps * source_fps );
933                         codec_context->skip_loop_filter = AVDISCARD_NONREF;
934                 }
935                 else if ( this->seekable && ( position < this->video_expected || position - this->video_expected >= 12 || last_position < 0 ) )
936                 {
937                         if ( use_new_seek && last_position == POSITION_INITIAL )
938                         {
939                                 // find first key frame
940                                 int ret = 0;
941                                 int toscan = 100;
942
943                                 while ( ret >= 0 && toscan-- > 0 )
944                                 {
945                                         ret = av_read_frame( context, &pkt );
946                                         if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == this->video_index )
947                                         {
948                                                 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) );
949                                                 this->first_pts = pkt.pts;
950                                                 toscan = 0;
951                                         }
952                                         av_free_packet( &pkt );
953                                 }
954                                 // Rewind
955                                 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
956                         }
957
958                         // Calculate the timestamp for the requested frame
959                         int64_t timestamp;
960                         if ( use_new_seek )
961                         {
962                                 timestamp = ( req_position - 0.1 / source_fps ) /
963                                         ( av_q2d( stream->time_base ) * source_fps );
964                                 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
965                                 if ( this->first_pts > 0 )
966                                         timestamp += this->first_pts;
967                                 else if ( context->start_time != AV_NOPTS_VALUE )
968                                         timestamp += context->start_time;
969                         }
970                         else
971                         {
972                                 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
973                                 if ( context->start_time != AV_NOPTS_VALUE )
974                                         timestamp += context->start_time;
975                         }
976                         if ( must_decode )
977                                 timestamp -= AV_TIME_BASE;
978                         if ( timestamp < 0 )
979                                 timestamp = 0;
980                         mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
981                                 timestamp, position, this->video_expected, last_position );
982
983                         // Seek to the timestamp
984                         if ( use_new_seek )
985                         {
986                                 codec_context->skip_loop_filter = AVDISCARD_NONREF;
987                                 av_seek_frame( context, this->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
988                         }
989                         else
990                         {
991                                 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
992                         }
993
994                         // Remove the cached info relating to the previous position
995                         this->current_position = POSITION_INVALID;
996                         this->last_position = POSITION_INVALID;
997                         av_freep( &this->av_frame );
998
999                         if ( use_new_seek )
1000                         {
1001                                 // flush any pictures still in decode buffer
1002                                 avcodec_flush_buffers( codec_context );
1003                         }
1004                 }
1005         }
1006
1007         // Duplicate the last image if necessary (see comment on rawvideo below)
1008         if ( this->av_frame && this->got_picture && this->seekable
1009                  && ( paused
1010                           || this->current_position == req_position
1011                           || ( !use_new_seek && this->current_position > req_position ) ) )
1012         {
1013                 // Duplicate it
1014                 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1015 #ifdef VDPAU
1016                         if ( this->vdpau && this->vdpau->buffer )
1017                         {
1018                                 AVPicture picture;
1019                                 picture.data[0] = this->vdpau->buffer;
1020                                 picture.data[2] = this->vdpau->buffer + codec_context->width * codec_context->height;
1021                                 picture.data[1] = this->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1022                                 picture.linesize[0] = codec_context->width;
1023                                 picture.linesize[1] = codec_context->width / 2;
1024                                 picture.linesize[2] = codec_context->width / 2;
1025                                 convert_image( (AVFrame*) &picture, *buffer, PIX_FMT_YUV420P, format, *width, *height );
1026                         }
1027                         else
1028 #endif
1029                         convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1030                 else
1031                         mlt_frame_get_image( frame, buffer, format, width, height, writable );
1032         }
1033         else
1034         {
1035                 int ret = 0;
1036                 int int_position = 0;
1037                 int decode_errors = 0;
1038                 int got_picture = 0;
1039
1040                 av_init_packet( &pkt );
1041
1042                 // Construct an AVFrame for YUV422 conversion
1043                 if ( !this->av_frame )
1044                         this->av_frame = avcodec_alloc_frame( );
1045
1046                 while( ret >= 0 && !got_picture )
1047                 {
1048                         // Read a packet
1049                         ret = av_read_frame( context, &pkt );
1050
1051                         // We only deal with video from the selected video_index
1052                         if ( ret >= 0 && pkt.stream_index == this->video_index && pkt.size > 0 )
1053                         {
1054                                 // Determine time code of the packet
1055                                 if ( use_new_seek )
1056                                 {
1057                                         int64_t pts = pkt.pts;
1058                                         if ( this->first_pts > 0 )
1059                                                 pts -= this->first_pts;
1060                                         else if ( context->start_time != AV_NOPTS_VALUE )
1061                                                 pts -= context->start_time;
1062                                         int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1063                                         if ( pkt.pts == AV_NOPTS_VALUE )
1064                                         {
1065                                                 this->invalid_pts_counter++;
1066                                                 if ( this->invalid_pts_counter > 20 )
1067                                                 {
1068                                                         mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1069                                                         mlt_properties_set_int( properties, "new_seek", 0 );
1070                                                         int_position = req_position;
1071                                                         use_new_seek = 0;
1072                                                 }
1073                                         }
1074                                         else
1075                                         {
1076                                                 this->invalid_pts_counter = 0;
1077                                         }
1078                                         mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1079                                                 pkt.pts, req_position, this->current_position, int_position );
1080                                 }
1081                                 else
1082                                 {
1083                                         if ( pkt.dts != AV_NOPTS_VALUE )
1084                                         {
1085                                                 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1086                                                 if ( context->start_time != AV_NOPTS_VALUE )
1087                                                         int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1088                                                 last_position = this->last_position;
1089                                                 if ( int_position == last_position )
1090                                                         int_position = last_position + 1;
1091                                         }
1092                                         else
1093                                         {
1094                                                 int_position = req_position;
1095                                         }
1096                                         mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1097                                                 pkt.dts, req_position, this->current_position, int_position );
1098                                         // Make a dumb assumption on streams that contain wild timestamps
1099                                         if ( abs( req_position - int_position ) > 999 )
1100                                         {
1101                                                 int_position = req_position;
1102                                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1103                                         }
1104                                 }
1105                                 this->last_position = int_position;
1106
1107                                 // Decode the image
1108                                 if ( must_decode || int_position >= req_position )
1109                                 {
1110 #ifdef VDPAU
1111                                         if ( g_vdpau && this->vdpau )
1112                                         {
1113                                                 if ( g_vdpau->producer != this )
1114                                                 {
1115                                                         vdpau_decoder_close();
1116                                                         vdpau_decoder_init( this );
1117                                                 }
1118                                                 if ( this->vdpau )
1119                                                         this->vdpau->is_decoded = 0;
1120                                         }
1121 #endif
1122                                         codec_context->reordered_opaque = pkt.pts;
1123                                         if ( int_position >= req_position )
1124                                                 codec_context->skip_loop_filter = AVDISCARD_NONE;
1125 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1126                                         ret = avcodec_decode_video2( codec_context, this->av_frame, &got_picture, &pkt );
1127 #else
1128                                         ret = avcodec_decode_video( codec_context, this->av_frame, &got_picture, pkt.data, pkt.size );
1129 #endif
1130                                         // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1131                                         if ( ret < 0 )
1132                                         {
1133                                                 if ( ++decode_errors <= 10 )
1134                                                         ret = 0;
1135                                         }
1136                                         else
1137                                         {
1138                                                 decode_errors = 0;
1139                                         }
1140                                 }
1141
1142                                 if ( got_picture )
1143                                 {
1144                                         if ( use_new_seek )
1145                                         {
1146                                                 // Determine time code of the packet
1147                                                 int64_t pts = this->av_frame->reordered_opaque;
1148                                                 if ( this->first_pts > 0 )
1149                                                         pts -= this->first_pts;
1150                                                 else if ( context->start_time != AV_NOPTS_VALUE )
1151                                                         pts -= context->start_time;
1152                                                 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1153                                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, this->av_frame->key_frame );
1154                                         }
1155                                         // Handle ignore
1156                                         if ( int_position < req_position )
1157                                         {
1158                                                 ignore = 0;
1159                                                 got_picture = 0;
1160                                         }
1161                                         else if ( int_position >= req_position )
1162                                         {
1163                                                 ignore = 0;
1164                                                 codec_context->skip_loop_filter = AVDISCARD_NONE;
1165                                         }
1166                                         else if ( ignore -- )
1167                                         {
1168                                                 got_picture = 0;
1169                                         }
1170                                 }
1171                                 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1172                                 av_free_packet( &pkt );
1173                         }
1174                         else if ( ret >= 0 )
1175                         {
1176                                 av_free_packet( &pkt );
1177                         }
1178
1179                         // Now handle the picture if we have one
1180                         if ( got_picture )
1181                         {
1182                                 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1183                                 {
1184 #ifdef VDPAU
1185                                         if ( this->vdpau )
1186                                         {
1187                                                 if ( this->vdpau->is_decoded )
1188                                                 {
1189                                                         struct vdpau_render_state *render = (struct vdpau_render_state*) this->av_frame->data[0];
1190                                                         void *planes[3];
1191                                                         uint32_t pitches[3];
1192                                                         VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1193                                                         AVPicture picture;
1194                                                         
1195                                                         if ( !this->vdpau->buffer )
1196                                                                 this->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1197                                                         picture.data[0] = planes[0] = this->vdpau->buffer;
1198                                                         picture.data[2] = planes[1] = this->vdpau->buffer + codec_context->width * codec_context->height;
1199                                                         picture.data[1] = planes[2] = this->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1200                                                         picture.linesize[0] = pitches[0] = codec_context->width;
1201                                                         picture.linesize[1] = pitches[1] = codec_context->width / 2;
1202                                                         picture.linesize[2] = pitches[2] = codec_context->width / 2;
1203
1204                                                         VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1205                                                         if ( status == VDP_STATUS_OK )
1206                                                         {
1207                                                                 convert_image( (AVFrame*) &picture, *buffer, PIX_FMT_YUV420P, format, *width, *height );
1208                                                         }
1209                                                         else
1210                                                         {
1211                                                                 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1212                                                                 this->vdpau->is_decoded = 0;
1213                                                         }
1214                                                 }
1215                                                 else
1216                                                 {
1217                                                         mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1218                                                         got_picture = 0;
1219                                                 }
1220                                         }
1221                                         else
1222 #endif
1223                                         convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1224                                         this->top_field_first |= this->av_frame->top_field_first;
1225                                         this->current_position = int_position;
1226                                         this->got_picture = 1;
1227                                 }
1228                                 else
1229                                 {
1230                                         got_picture = 0;
1231                                 }
1232                         }
1233                 }
1234         }
1235
1236         avformat_unlock();
1237
1238         if ( this->got_picture && image_size > 0 && this->image_cache )
1239         {
1240                 // Copy buffer to image cache   
1241                 uint8_t *image = mlt_pool_alloc( image_size );
1242                 memcpy( image, *buffer, image_size );
1243                 mlt_cache_put( this->image_cache, (void*) position, image, *format, mlt_pool_release );
1244         }
1245
1246 exit_get_image:
1247         // Set the progressive flag
1248         if ( mlt_properties_get( properties, "force_progressive" ) )
1249                 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1250         else if ( this->av_frame )
1251                 mlt_properties_set_int( frame_properties, "progressive", !this->av_frame->interlaced_frame );
1252
1253         // Set the field order property for this frame
1254         mlt_properties_set_int( frame_properties, "top_field_first", this->top_field_first );
1255
1256         // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1257         this->video_expected = position + 1;
1258
1259         return !this->got_picture;
1260 }
1261
1262 /** Process properties as AVOptions and apply to AV context obj
1263 */
1264
1265 static void apply_properties( void *obj, mlt_properties properties, int flags )
1266 {
1267         int i;
1268         int count = mlt_properties_count( properties );
1269         for ( i = 0; i < count; i++ )
1270         {
1271                 const char *opt_name = mlt_properties_get_name( properties, i );
1272                 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1273                 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1274                 {
1275                         if ( opt )
1276 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1277                                 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1278 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1279                                 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1280 #else
1281                                 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1282 #endif
1283                 }
1284         }
1285 }
1286
1287 /** Initialize the video codec context.
1288  */
1289
1290 static int video_codec_init( producer_avformat this, int index, mlt_properties properties )
1291 {
1292         // Initialise the codec if necessary
1293         if ( !this->video_codec )
1294         {
1295                 // Get the video stream
1296                 AVStream *stream = this->video_format->streams[ index ];
1297
1298                 // Get codec context
1299                 AVCodecContext *codec_context = stream->codec;
1300
1301                 // Find the codec
1302                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1303 #ifdef VDPAU
1304                 if ( codec_context->codec_id == CODEC_ID_H264 )
1305                 {
1306                         if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1307                         {
1308                                 if ( vdpau_init( this ) )
1309                                 {
1310                                         this->video_codec = codec_context;
1311                                         if ( !vdpau_decoder_init( this ) )
1312                                                 vdpau_decoder_close();
1313                                 }
1314                         }
1315                         if ( !this->vdpau )
1316                                 codec = avcodec_find_decoder( codec_context->codec_id );
1317                 }
1318 #endif
1319
1320                 // Initialise multi-threading
1321                 int thread_count = mlt_properties_get_int( properties, "threads" );
1322                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1323                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1324                 if ( thread_count > 1 )
1325                 {
1326                         avcodec_thread_init( codec_context, thread_count );
1327                         codec_context->thread_count = thread_count;
1328                 }
1329
1330                 // If we don't have a codec and we can't initialise it, we can't do much more...
1331                 avformat_lock( );
1332                 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1333                 {
1334                         // Now store the codec with its destructor
1335                         this->video_codec = codec_context;
1336                 }
1337                 else
1338                 {
1339                         // Remember that we can't use this later
1340                         this->video_index = -1;
1341                 }
1342                 avformat_unlock( );
1343
1344                 // Process properties as AVOptions
1345                 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1346
1347                 // Reset some image properties
1348                 mlt_properties_set_int( properties, "width", this->video_codec->width );
1349                 mlt_properties_set_int( properties, "height", this->video_codec->height );
1350                 // For DV, we'll just use the saved aspect ratio
1351                 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1352                         mlt_properties_set_double( properties, "aspect_ratio", get_aspect_ratio( stream, this->video_codec, NULL ) );
1353
1354                 // Determine the fps first from the codec
1355                 double source_fps = (double) this->video_codec->time_base.den /
1356                                                                    ( this->video_codec->time_base.num == 0 ? 1 : this->video_codec->time_base.num );
1357                 
1358                 if ( mlt_properties_get( properties, "force_fps" ) )
1359                 {
1360                         source_fps = mlt_properties_get_double( properties, "force_fps" );
1361                         stream->time_base = av_d2q( source_fps, 255 );
1362                 }
1363                 else
1364                 {
1365                         // If the muxer reports a frame rate different than the codec
1366                         double muxer_fps = av_q2d( stream->r_frame_rate );
1367                         // Choose the lesser - the wrong tends to be off by some multiple of 10
1368                         source_fps = FFMIN( source_fps, muxer_fps );
1369                 }
1370
1371                 // We'll use fps if it's available
1372                 if ( source_fps > 0 )
1373                         mlt_properties_set_double( properties, "source_fps", source_fps );
1374                 else
1375                         mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( this->parent ) );
1376         }
1377         return this->video_codec && this->video_index > -1;
1378 }
1379
1380 /** Set up video handling.
1381 */
1382
1383 static void producer_set_up_video( producer_avformat this, mlt_frame frame )
1384 {
1385         // Get the producer
1386         mlt_producer producer = this->parent;
1387
1388         // Get the properties
1389         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1390
1391         // Fetch the video format context
1392         AVFormatContext *context = this->video_format;
1393
1394         // Get the video_index
1395         int index = mlt_properties_get_int( properties, "video_index" );
1396
1397         // Reopen the file if necessary
1398         if ( !context && index > -1 )
1399         {
1400                 mlt_events_block( properties, producer );
1401                 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1402                         mlt_properties_get( properties, "resource" ) );
1403                 context = this->video_format;
1404                 if ( this->dummy_context )
1405                 {
1406                         avformat_lock();
1407                         av_close_input_file( this->dummy_context );
1408                         avformat_unlock();
1409                 }
1410                 this->dummy_context = NULL;
1411                 mlt_events_unblock( properties, producer );
1412                 if ( this->audio_format )
1413                         get_audio_streams_info( this );
1414
1415                 // Process properties as AVOptions
1416                 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1417         }
1418
1419         // Exception handling for video_index
1420         if ( context && index >= (int) context->nb_streams )
1421         {
1422                 // Get the last video stream
1423                 for ( index = context->nb_streams - 1;
1424                           index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1425                           index-- );
1426                 mlt_properties_set_int( properties, "video_index", index );
1427         }
1428         if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1429         {
1430                 // Invalidate the video stream
1431                 index = -1;
1432                 mlt_properties_set_int( properties, "video_index", index );
1433         }
1434
1435         // Update the video properties if the index changed
1436         if ( index != this->video_index )
1437         {
1438                 // Reset the video properties if the index changed
1439                 this->video_index = index;
1440                 if ( this->video_codec )
1441                 {
1442                         avformat_lock();
1443                         avcodec_close( this->video_codec );
1444                         avformat_unlock();
1445                 }
1446                 this->video_codec = NULL;
1447         }
1448
1449         // Get the frame properties
1450         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1451
1452         // Get the codec
1453         if ( context && index > -1 && video_codec_init( this, index, properties ) )
1454         {
1455                 // Set the frame properties
1456                 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1457                 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1458                         force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1459
1460                 // Set the width and height
1461                 mlt_properties_set_int( frame_properties, "width", this->video_codec->width );
1462                 mlt_properties_set_int( frame_properties, "height", this->video_codec->height );
1463                 mlt_properties_set_int( frame_properties, "real_width", this->video_codec->width );
1464                 mlt_properties_set_int( frame_properties, "real_height", this->video_codec->height );
1465                 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1466
1467                 // Add our image operation
1468                 mlt_frame_push_service( frame, this );
1469                 mlt_frame_push_get_image( frame, producer_get_image );
1470         }
1471         else
1472         {
1473                 // If something failed, use test card image
1474                 mlt_properties_set_int( frame_properties, "test_image", 1 );
1475         }
1476 }
1477
1478 static int seek_audio( producer_avformat this, mlt_position position, double timecode, int *ignore )
1479 {
1480         int paused = 0;
1481
1482         // Seek if necessary
1483         if ( position != this->audio_expected )
1484         {
1485                 if ( position + 1 == this->audio_expected )
1486                 {
1487                         // We're paused - silence required
1488                         paused = 1;
1489                 }
1490                 else if ( !this->seekable && position > this->audio_expected && ( position - this->audio_expected ) < 250 )
1491                 {
1492                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
1493                         *ignore = position - this->audio_expected;
1494                 }
1495                 else if ( position < this->audio_expected || position - this->audio_expected >= 12 )
1496                 {
1497                         AVFormatContext *context = this->audio_format;
1498                         int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1499                         if ( context->start_time != AV_NOPTS_VALUE )
1500                                 timestamp += context->start_time;
1501                         if ( timestamp < 0 )
1502                                 timestamp = 0;
1503
1504                         // Set to the real timecode
1505                         if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1506                                 paused = 1;
1507
1508                         // Clear the usage in the audio buffer
1509                         int i = MAX_AUDIO_STREAMS + 1;
1510                         while ( --i )
1511                                 this->audio_used[i - 1] = 0;
1512                 }
1513         }
1514         return paused;
1515 }
1516
1517 static int decode_audio( producer_avformat this, int *ignore, AVPacket *pkt, int channels, int samples, double timecode, double fps )
1518 {
1519         // Fetch the audio_format
1520         AVFormatContext *context = this->audio_format;
1521
1522         // Get the current stream index
1523         int index = pkt->stream_index;
1524
1525         // Get codec context
1526         AVCodecContext *codec_context = this->audio_codec[ index ];
1527
1528         // Obtain the resample context if it exists (not always needed)
1529         ReSampleContext *resample = this->audio_resample[ index ];
1530
1531         // Obtain the audio buffers
1532         int16_t *audio_buffer = this->audio_buffer[ index ];
1533         int16_t *decode_buffer = this->decode_buffer[ index ];
1534
1535         int audio_used = this->audio_used[ index ];
1536         uint8_t *ptr = pkt->data;
1537         int len = pkt->size;
1538         int ret = 0;
1539
1540         while ( ptr && ret >= 0 && len > 0 )
1541         {
1542                 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1543
1544                 // Decode the audio
1545 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1546                 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, pkt );
1547 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1548                 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1549 #else
1550                 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1551 #endif
1552                 if ( ret < 0 )
1553                 {
1554                         ret = 0;
1555                         break;
1556                 }
1557
1558                 len -= ret;
1559                 ptr += ret;
1560
1561                 // If decoded successfully
1562                 if ( data_size > 0 )
1563                 {
1564                         // Figure out how many samples will be needed after resampling
1565                         int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1566                         int samples_needed = this->resample_factor * convert_samples + 1;
1567                         
1568                         // Resize audio buffer to prevent overflow
1569                         if ( audio_used * channels + samples_needed > this->audio_buffer_size[ index ] )
1570                         {
1571                                 this->audio_buffer_size[ index ] *= 2;
1572                                 audio_buffer = this->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, this->audio_buffer_size[ index ] * sizeof(int16_t) );
1573                         }
1574                         if ( resample )
1575                         {
1576                                 // Copy to audio buffer while resampling
1577                                 int16_t *source = decode_buffer;
1578                                 int16_t *dest = &audio_buffer[ audio_used * channels ];
1579                                 audio_used += audio_resample( resample, dest, source, convert_samples );
1580                         }
1581                         else
1582                         {
1583                                 // Straight copy to audio buffer
1584                                 memcpy( &audio_buffer[ audio_used * codec_context->channels ], decode_buffer, data_size );
1585                                 audio_used += convert_samples;
1586                         }
1587
1588                         // Handle ignore
1589                         while ( *ignore && audio_used > samples )
1590                         {
1591                                 *ignore -= 1;
1592                                 audio_used -= samples;
1593                                 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) ],
1594                                          audio_used * sizeof( int16_t ) );
1595                         }
1596                 }
1597         }
1598
1599         // If we're behind, ignore this packet
1600         if ( pkt->pts >= 0 )
1601         {
1602                 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt->pts;
1603                 int req_position = ( int )( timecode * fps + 0.5 );
1604                 int int_position = ( int )( current_pts * fps + 0.5 );
1605                 if ( context->start_time != AV_NOPTS_VALUE )
1606                         int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1607
1608                 if ( this->seekable && *ignore == 0 )
1609                 {
1610                         if ( int_position < req_position )
1611                                 // We are behind, so skip some
1612                                 *ignore = 1;
1613                         else if ( int_position > req_position + 2 )
1614                                 // We are ahead, so seek backwards some more
1615                                 seek_audio( this, req_position, timecode - 1.0, ignore );
1616                 }
1617         }
1618
1619         this->audio_used[ index ] = audio_used;
1620
1621         return ret;
1622 }
1623
1624 /** Get the audio from a frame.
1625 */
1626
1627 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1628 {
1629         // Get the producer
1630         producer_avformat this = mlt_frame_pop_audio( frame );
1631
1632         // Obtain the frame number of this frame
1633         mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1634
1635         // Calculate the real time code
1636         double real_timecode = producer_time_of_frame( this->parent, position );
1637
1638         // Get the producer fps
1639         double fps = mlt_producer_get_fps( this->parent );
1640
1641         // Number of frames to ignore (for ffwd)
1642         int ignore = 0;
1643
1644         // Flag for paused (silence)
1645         int paused = seek_audio( this, position, real_timecode, &ignore );
1646
1647         // Fetch the audio_format
1648         AVFormatContext *context = this->audio_format;
1649         
1650         // Determine the tracks to use
1651         int index = this->audio_index;
1652         int index_max = this->audio_index + 1;
1653         if ( this->audio_index == INT_MAX )
1654         {
1655                 index = 0;
1656                 index_max = context->nb_streams;
1657                 *channels = this->total_channels;
1658                 *frequency = this->max_frequency;
1659         }
1660
1661         // Initialize the resamplers and buffers
1662         for ( ; index < index_max; index++ )
1663         {
1664                 // Get codec context
1665                 AVCodecContext *codec_context = this->audio_codec[ index ];
1666
1667                 if ( codec_context && !this->audio_buffer[ index ] )
1668                 {
1669                         // Check for resample and create if necessary
1670                         if ( codec_context->channels <= 2 )
1671                         {
1672                                 // Determine by how much resampling will increase number of samples
1673                                 double resample_factor = this->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
1674                                 resample_factor *= (double) *frequency / codec_context->sample_rate;
1675                                 if ( resample_factor > this->resample_factor )
1676                                         this->resample_factor = resample_factor;
1677                                 
1678                                 // Create the resampler
1679 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1680                                 this->audio_resample[ index ] = av_audio_resample_init(
1681                                         this->audio_index == INT_MAX ? codec_context->channels : *channels,
1682                                         codec_context->channels, *frequency, codec_context->sample_rate,
1683                                         SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1684 #else
1685                                 this->audio_resample[ index ] = audio_resample_init(
1686                                         this->audio_index == INT_MAX ? codec_context->channels : *channels,
1687                                         codec_context->channels, *frequency, codec_context->sample_rate );
1688 #endif
1689                         }
1690                         else
1691                         {
1692                                 codec_context->request_channels = this->audio_index == INT_MAX ? codec_context->channels : *channels;
1693                         }
1694
1695                         // Check for audio buffer and create if necessary
1696                         this->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1697                         this->audio_buffer[ index ] = mlt_pool_alloc( this->audio_buffer_size[ index ] * sizeof( int16_t ) );
1698
1699                         // Check for decoder buffer and create if necessary
1700                         this->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1701                 }
1702         }
1703
1704         // Get the audio if required
1705         if ( !paused )
1706         {
1707                 int ret = 0;
1708                 int got_audio = 0;
1709                 AVPacket pkt;
1710
1711                 av_init_packet( &pkt );
1712                 
1713                 // If not resampling, give consumer more than requested.
1714                 // It requested number samples based on requested frame rate.
1715                 // Do not clean this up with a samples *= ...!
1716                 if ( this->audio_index != INT_MAX && ! this->audio_resample[ this->audio_index ] )
1717                         *samples = *samples * this->audio_codec[ this->audio_index ]->sample_rate / *frequency;
1718
1719                 while ( ret >= 0 && !got_audio )
1720                 {
1721                         // Check if the buffer already contains the samples required
1722                         if ( this->audio_index != INT_MAX && this->audio_used[ this->audio_index ] >= *samples && ignore == 0 )
1723                         {
1724                                 got_audio = 1;
1725                                 break;
1726                         }
1727
1728                         // Read a packet
1729                         ret = av_read_frame( context, &pkt );
1730
1731                         // We only deal with audio from the selected audio index
1732                         if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == this->audio_index ||
1733                                  ( this->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
1734                         {
1735                                 int channels2 = this->audio_index == INT_MAX ? this->audio_codec[pkt.stream_index]->channels : *channels;
1736                                 ret = decode_audio( this, &ignore, &pkt, channels2, *samples, real_timecode, fps );
1737                         }
1738                         av_free_packet( &pkt );
1739
1740                         if ( this->audio_index == INT_MAX && ret >= 0 )
1741                         {
1742                                 // Determine if there is enough audio for all streams
1743                                 got_audio = 1;
1744                                 for ( index = 0; index < context->nb_streams; index++ )
1745                                 {
1746                                         if ( this->audio_codec[ index ] && this->audio_used[ index ] < *samples )
1747                                                 got_audio = 0;
1748                                 }
1749                         }
1750                 }
1751                 
1752                 // Allocate and set the frame's audio buffer
1753                 int size = *samples * *channels * sizeof(int16_t);
1754                 *buffer = mlt_pool_alloc( size );
1755                 *format = mlt_audio_s16;
1756                 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
1757
1758                 // Interleave tracks if audio_index=all
1759                 if ( this->audio_index == INT_MAX )
1760                 {
1761                         int16_t *dest = *buffer;
1762                         int i;
1763                         for ( i = 0; i < *samples; i++ )
1764                         {
1765                                 for ( index = 0; index < index_max; index++ )
1766                                 if ( this->audio_codec[ index ] )
1767                                 {
1768                                         int current_channels = this->audio_codec[ index ]->channels;
1769                                         int16_t *src = this->audio_buffer[ index ] + i * current_channels;
1770                                         memcpy( dest, src, current_channels * sizeof(int16_t) );
1771                                         dest += current_channels;
1772                                 }
1773                         }
1774                         for ( index = 0; index < index_max; index++ )
1775                         if ( this->audio_codec[ index ] && this->audio_used[ index ] >= *samples )
1776                         {
1777                                 int current_channels = this->audio_codec[ index ]->channels;
1778                                 int16_t *src = this->audio_buffer[ index ] + *samples * current_channels;
1779                                 this->audio_used[index] -= *samples;
1780                                 memmove( this->audio_buffer[ index ], src, this->audio_used[ index ] * current_channels * sizeof(int16_t) );
1781                         }
1782                 }
1783                 // Copy a single track to the output buffer
1784                 else
1785                 {
1786                         index = this->audio_index;
1787
1788                         // Now handle the audio if we have enough
1789                         if ( this->audio_used[ index ] >= *samples )
1790                         {
1791                                 int16_t *src = this->audio_buffer[ index ];
1792                                 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
1793                                 this->audio_used[ index ] -= *samples;
1794                                 memmove( src, &src[ *samples * *channels ], this->audio_used[ index ] * *channels * sizeof(int16_t) );
1795                         }
1796                         else
1797                         {
1798                                 // Otherwise fill with silence
1799                                 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
1800                         }
1801                         if ( !this->audio_resample[ index ] )
1802                         {
1803                                 // TODO: uncomment and remove following line when full multi-channel support is ready
1804                                 // *channels = codec_context->channels;
1805                                 *frequency = this->audio_codec[ index ]->sample_rate;
1806                         }
1807                 }
1808         }
1809         else
1810         {
1811                 // Get silence and don't touch the context
1812                 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1813         }
1814         
1815         // Regardless of speed (other than paused), we expect to get the next frame
1816         if ( !paused )
1817                 this->audio_expected = position + 1;
1818
1819         return 0;
1820 }
1821
1822 /** Initialize the audio codec context.
1823 */
1824
1825 static int audio_codec_init( producer_avformat this, int index, mlt_properties properties )
1826 {
1827         // Initialise the codec if necessary
1828         if ( !this->audio_codec[ index ] )
1829         {
1830                 // Get codec context
1831                 AVCodecContext *codec_context = this->audio_format->streams[index]->codec;
1832
1833                 // Find the codec
1834                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1835
1836                 // If we don't have a codec and we can't initialise it, we can't do much more...
1837                 avformat_lock( );
1838                 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1839                 {
1840                         // Now store the codec with its destructor
1841                         if ( this->audio_codec[ index ] )
1842                                 avcodec_close( this->audio_codec[ index ] );
1843                         this->audio_codec[ index ] = codec_context;
1844                 }
1845                 else
1846                 {
1847                         // Remember that we can't use this later
1848                         this->audio_index = -1;
1849                 }
1850                 avformat_unlock( );
1851
1852                 // Process properties as AVOptions
1853                 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1854         }
1855         return this->audio_codec[ index ] && this->audio_index > -1;
1856 }
1857
1858 /** Set up audio handling.
1859 */
1860
1861 static void producer_set_up_audio( producer_avformat this, mlt_frame frame )
1862 {
1863         // Get the producer
1864         mlt_producer producer = this->parent;
1865
1866         // Get the properties
1867         mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1868
1869         // Fetch the audio format context
1870         AVFormatContext *context = this->audio_format;
1871
1872         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1873
1874         // Get the audio_index
1875         int index = mlt_properties_get_int( properties, "audio_index" );
1876
1877         // Handle all audio tracks
1878         if ( this->audio_index > -1 &&
1879              mlt_properties_get( properties, "audio_index" ) &&
1880              !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
1881                 index = INT_MAX;
1882
1883         // Reopen the file if necessary
1884         if ( !context && this->audio_index > -1 && index > -1 )
1885         {
1886                 mlt_events_block( properties, producer );
1887                 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1888                         mlt_properties_get( properties, "resource" ) );
1889                 context = this->audio_format;
1890                 if ( this->dummy_context )
1891                 {
1892                         avformat_lock();
1893                         av_close_input_file( this->dummy_context );
1894                         avformat_unlock();
1895                 }
1896                 this->dummy_context = NULL;
1897                 mlt_events_unblock( properties, producer );
1898                 get_audio_streams_info( this );
1899         }
1900
1901         // Exception handling for audio_index
1902         if ( context && index >= (int) context->nb_streams && index < INT_MAX )
1903         {
1904                 for ( index = context->nb_streams - 1;
1905                           index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
1906                           index-- );
1907                 mlt_properties_set_int( properties, "audio_index", index );
1908         }
1909         if ( context && index > -1 && index < INT_MAX &&
1910                  context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1911         {
1912                 index = this->audio_index;
1913                 mlt_properties_set_int( properties, "audio_index", index );
1914         }
1915
1916         // Update the audio properties if the index changed
1917         if ( context && index > -1 && index != this->audio_index )
1918         {
1919                 if ( this->audio_codec[ this->audio_index ] )
1920                 {
1921                         avformat_lock();
1922                         avcodec_close( this->audio_codec[ this->audio_index ] );
1923                         avformat_unlock();
1924                 }
1925                 this->audio_codec[ this->audio_index ] = NULL;
1926         }
1927         if ( this->audio_index != -1 )
1928                 this->audio_index = index;
1929         else
1930                 index = -1;
1931
1932         // Get the codec(s)
1933         if ( context && index == INT_MAX )
1934         {
1935                 mlt_properties_set_int( frame_properties, "frequency", this->max_frequency );
1936                 mlt_properties_set_int( frame_properties, "channels", this->total_channels );
1937                 for ( index = 0; index < context->nb_streams; index++ )
1938                 {
1939                         if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
1940                                 audio_codec_init( this, index, properties );
1941                 }
1942         }
1943         else if ( context && index > -1 && audio_codec_init( this, index, properties ) )
1944         {
1945                 // Set the frame properties
1946                 if ( index < INT_MAX )
1947                 {
1948                         mlt_properties_set_int( frame_properties, "frequency", this->audio_codec[ index ]->sample_rate );
1949                         mlt_properties_set_int( frame_properties, "channels", this->audio_codec[ index ]->channels );
1950                 }
1951         }
1952         if ( context && index > -1 )
1953         {
1954                 // Add our audio operation
1955                 mlt_frame_push_audio( frame, this );
1956                 mlt_frame_push_audio( frame, producer_get_audio );
1957         }
1958 }
1959
1960 /** Our get frame implementation.
1961 */
1962
1963 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
1964 {
1965         // Access the private data
1966         mlt_service service = MLT_PRODUCER_SERVICE( producer );
1967         mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
1968         producer_avformat this = mlt_cache_item_data( cache_item, NULL );
1969
1970         // If cache miss
1971         if ( !this )
1972         {
1973                 this = calloc( 1, sizeof( struct producer_avformat_s ) );
1974                 producer->child = this;
1975                 this->parent = producer;
1976                 mlt_service_cache_put( service, "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
1977                 cache_item = mlt_service_cache_get( service, "producer_avformat" );
1978         }
1979
1980         // Create an empty frame
1981         *frame = mlt_frame_init( service);
1982         
1983         if ( *frame )
1984         {
1985                 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
1986         }
1987         else
1988         {
1989                 mlt_cache_item_close( cache_item );
1990                 return 1;
1991         }
1992
1993         // Update timecode on the frame we're creating
1994         mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
1995
1996         // Set the position of this producer
1997         mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
1998         
1999         // Set up the video
2000         producer_set_up_video( this, *frame );
2001
2002         // Set up the audio
2003         producer_set_up_audio( this, *frame );
2004
2005         // Calculate the next timecode
2006         mlt_producer_prepare_next( producer );
2007
2008         return 0;
2009 }
2010
2011 static void producer_avformat_close( producer_avformat this )
2012 {
2013         mlt_log_debug( NULL, "producer_avformat_close\n" );
2014         // Close the file
2015         av_free( this->av_frame );
2016         avformat_lock();
2017         int i;
2018         for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2019         {
2020                 if ( this->audio_resample[i] )
2021                         audio_resample_close( this->audio_resample[i] );
2022                 mlt_pool_release( this->audio_buffer[i] );
2023                 av_free( this->decode_buffer[i] );
2024                 if ( this->audio_codec[i] )
2025                         avcodec_close( this->audio_codec[i] );
2026         }
2027         if ( this->video_codec )
2028                 avcodec_close( this->video_codec );
2029         if ( this->dummy_context )
2030                 av_close_input_file( this->dummy_context );
2031         if ( this->audio_format )
2032                 av_close_input_file( this->audio_format );
2033         if ( this->video_format )
2034                 av_close_input_file( this->video_format );
2035         avformat_unlock();
2036 #ifdef VDPAU
2037         vdpau_producer_close( this );
2038 #endif
2039         if ( this->image_cache )
2040                 mlt_cache_close( this->image_cache );
2041         free( this );
2042 }
2043
2044 static void producer_close( mlt_producer parent )
2045 {
2046         // Close the parent
2047         parent->close = NULL;
2048         mlt_producer_close( parent );
2049
2050         // Free the memory
2051         free( parent );
2052 }