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