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