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