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