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