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