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