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