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