]> git.sesse.net Git - mlt/blob - src/modules/avformat/producer_avformat.c
Massive refactoring of image conversion.
[mlt] / src / modules / avformat / producer_avformat.c
1 /*
2  * producer_avformat.c -- avformat producer
3  * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4  * Author: Charles Yates <charles.yates@pandora.be>
5  * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 // MLT Header files
23 #include <framework/mlt_producer.h>
24 #include <framework/mlt_frame.h>
25 #include <framework/mlt_profile.h>
26 #include <framework/mlt_log.h>
27
28 // ffmpeg Header files
29 #include <avformat.h>
30 #include <opt.h>
31 #ifdef SWSCALE
32 #  include <swscale.h>
33 #endif
34 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
35 #  include "audioconvert.h"
36 #endif
37
38 // System header files
39 #include <stdlib.h>
40 #include <string.h>
41 #include <pthread.h>
42
43 #if LIBAVUTIL_VERSION_INT < (50<<16)
44 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
45 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
46 #endif
47
48 void avformat_lock( );
49 void avformat_unlock( );
50
51 // Forward references.
52 static int producer_open( mlt_producer this, mlt_profile profile, char *file );
53 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
54
55 /** Constructor for libavformat.
56 */
57
58 mlt_producer producer_avformat_init( mlt_profile profile, char *file )
59 {
60         int error = 0;
61
62         // Report information about available demuxers and codecs as YAML Tiny
63         if ( file && strstr( file, "f-list" ) )
64         {
65                 fprintf( stderr, "---\nformats:\n" );
66                 AVInputFormat *format = NULL;
67                 while ( ( format = av_iformat_next( format ) ) )
68                         fprintf( stderr, "  - %s\n", format->name );
69                 fprintf( stderr, "...\n" );
70                 error = 1;
71         }
72         if ( file && strstr( file, "acodec-list" ) )
73         {
74                 fprintf( stderr, "---\naudio_codecs:\n" );
75                 AVCodec *codec = NULL;
76                 while ( ( codec = av_codec_next( codec ) ) )
77                         if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
78                                 fprintf( stderr, "  - %s\n", codec->name );
79                 fprintf( stderr, "...\n" );
80                 error = 1;
81         }
82         if ( file && strstr( file, "vcodec-list" ) )
83         {
84                 fprintf( stderr, "---\nvideo_codecs:\n" );
85                 AVCodec *codec = NULL;
86                 while ( ( codec = av_codec_next( codec ) ) )
87                         if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
88                                 fprintf( stderr, "  - %s\n", codec->name );
89                 fprintf( stderr, "...\n" );
90                 error = 1;
91         }
92         if ( error )
93                 return NULL;
94
95         mlt_producer this = NULL;
96
97         // Check that we have a non-NULL argument
98         if ( file != NULL )
99         {
100                 // Construct the producer
101                 this = calloc( 1, sizeof( struct mlt_producer_s ) );
102
103                 // Initialise it
104                 if ( mlt_producer_init( this, NULL ) == 0 )
105                 {
106                         // Get the properties
107                         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
108
109                         // Set the resource property (required for all producers)
110                         mlt_properties_set( properties, "resource", file );
111
112                         // Register our get_frame implementation
113                         this->get_frame = producer_get_frame;
114
115                         // Open the file
116                         if ( producer_open( this, profile, file ) != 0 )
117                         {
118                                 // Clean up
119                                 mlt_producer_close( this );
120                                 this = NULL;
121                         }
122                         else
123                         {
124                                 // Close the file to release resources for large playlists - reopen later as needed
125                                 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
126                                 mlt_properties_set_data( properties, "audio_context", NULL, 0, NULL, NULL );
127                                 mlt_properties_set_data( properties, "video_context", NULL, 0, NULL, NULL );
128
129                                 // Default the user-selectable indices from the auto-detected indices
130                                 mlt_properties_set_int( properties, "audio_index",  mlt_properties_get_int( properties, "_audio_index" ) );
131                                 mlt_properties_set_int( properties, "video_index",  mlt_properties_get_int( properties, "_video_index" ) );
132                         }
133                 }
134         }
135
136         return this;
137 }
138
139 /** Find the default streams.
140 */
141
142 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
143 {
144         int i;
145         char key[200];
146
147         mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
148
149         // Allow for multiple audio and video streams in the file and select first of each (if available)
150         for( i = 0; i < context->nb_streams; i++ )
151         {
152                 // Get the codec context
153                 AVStream *stream = context->streams[ i ];
154                 if ( ! stream ) continue;
155                 AVCodecContext *codec_context = stream->codec;
156                 if ( ! codec_context ) continue;
157                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
158                 if ( ! codec ) continue;
159
160                 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
161
162                 // Determine the type and obtain the first index of each type
163                 switch( codec_context->codec_type )
164                 {
165                         case CODEC_TYPE_VIDEO:
166                                 if ( *video_index < 0 )
167                                         *video_index = i;
168                                 mlt_properties_set( meta_media, key, "video" );
169                                 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
170                                 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
171 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
172                                 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
173                                 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
174 #endif
175                                 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
176                                 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
177                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
178                                 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
179                                 break;
180                         case CODEC_TYPE_AUDIO:
181                                 if ( *audio_index < 0 )
182                                         *audio_index = i;
183                                 mlt_properties_set( meta_media, key, "audio" );
184 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
185                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
186                                 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
187 #endif
188                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
189                                 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
190                                 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
191                                 mlt_properties_set_int( meta_media, key, codec_context->channels );
192                                 break;
193                         default:
194                                 break;
195                 }
196 //              snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
197 //              mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
198                 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
199                 mlt_properties_set( meta_media, key, codec->name );
200 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
201                 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
202                 mlt_properties_set( meta_media, key, codec->long_name );
203 #endif
204                 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
205                 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
206 //              snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
207 //              mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
208                 snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
209                 mlt_properties_set_int( meta_media, key, codec_context->profile );
210                 snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
211                 mlt_properties_set_int( meta_media, key, codec_context->level );
212         }
213
214         return meta_media;
215 }
216
217 /** Producer file destructor.
218 */
219
220 static void producer_file_close( void *context )
221 {
222         if ( context != NULL )
223         {
224                 // Lock the mutex now
225                 avformat_lock( );
226
227                 // Close the file
228                 av_close_input_file( context );
229
230                 // Unlock the mutex now
231                 avformat_unlock( );
232         }
233 }
234
235 /** Producer file destructor.
236 */
237
238 static void producer_codec_close( void *codec )
239 {
240         if ( codec != NULL )
241         {
242                 // Lock the mutex now
243                 avformat_lock( );
244
245                 // Close the file
246                 avcodec_close( codec );
247
248                 // Unlock the mutex now
249                 avformat_unlock( );
250         }
251 }
252
253 static inline int dv_is_pal( AVPacket *pkt )
254 {
255         return pkt->data[3] & 0x80;
256 }
257
258 static int dv_is_wide( AVPacket *pkt )
259 {
260         int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
261
262         for ( ; i < pkt->size; i += 5 /* packet size */ )
263         {
264                 if ( pkt->data[ i ] == 0x61 )
265                 {
266                         uint8_t x = pkt->data[ i + 2 ] & 0x7;
267                         return ( x == 2 ) || ( x == 7 );
268                 }
269         }
270         return 0;
271 }
272
273 static double get_aspect_ratio( AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
274 {
275         double aspect_ratio = 1.0;
276
277         if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
278         {
279                 if ( pkt )
280                 {
281                         if ( dv_is_pal( pkt ) )
282                         {
283                                 aspect_ratio = dv_is_wide( pkt )
284                                         ? 64.0/45.0 // 16:9 PAL
285                                         : 16.0/15.0; // 4:3 PAL
286                         }
287                         else
288                         {
289                                 aspect_ratio = dv_is_wide( pkt )
290                                         ? 32.0/27.0 // 16:9 NTSC
291                                         : 8.0/9.0; // 4:3 NTSC
292                         }
293                 }
294                 else
295                 {
296                         AVRational ar =
297 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
298                                 stream->sample_aspect_ratio;
299 #else
300                                 codec_context->sample_aspect_ratio;
301 #endif
302                         // Override FFmpeg's notion of DV aspect ratios, which are
303                         // based upon a width of 704. Since we do not have a normaliser
304                         // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
305                         // we just coerce the values to facilitate a passive behaviour through
306                         // the rescale normaliser when using equivalent producers and consumers.
307                         // = display_aspect / (width * height)
308                         if ( ar.num == 10 && ar.den == 11 )
309                                 aspect_ratio = 8.0/9.0; // 4:3 NTSC
310                         else if ( ar.num == 59 && ar.den == 54 )
311                                 aspect_ratio = 16.0/15.0; // 4:3 PAL
312                         else if ( ar.num == 40 && ar.den == 33 )
313                                 aspect_ratio = 32.0/27.0; // 16:9 NTSC
314                         else if ( ar.num == 118 && ar.den == 81 )
315                                 aspect_ratio = 64.0/45.0; // 16:9 PAL
316                 }
317         }
318         else
319         {
320                 AVRational codec_sar = codec_context->sample_aspect_ratio;
321                 AVRational stream_sar =
322 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
323                         stream->sample_aspect_ratio;
324 #else
325                         { 0, 1 };
326 #endif
327                 if ( codec_sar.num > 0 )
328                         aspect_ratio = av_q2d( codec_sar );
329                 else if ( stream_sar.num > 0 )
330                         aspect_ratio = av_q2d( stream_sar );
331         }
332         return aspect_ratio;
333 }
334
335 /** Open the file.
336 */
337
338 static int producer_open( mlt_producer this, mlt_profile profile, char *file )
339 {
340         // Return an error code (0 == no error)
341         int error = 0;
342
343         // Context for avformat
344         AVFormatContext *context = NULL;
345
346         // Get the properties
347         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
348
349         // We will treat everything with the producer fps
350         double fps = mlt_profile_fps( profile );
351
352         // Lock the mutex now
353         avformat_lock( );
354
355         // If "MRL", then create AVInputFormat
356         AVInputFormat *format = NULL;
357         AVFormatParameters *params = NULL;
358         char *standard = NULL;
359         char *mrl = strchr( file, ':' );
360
361         // AV option (0 = both, 1 = video, 2 = audio)
362         int av = 0;
363
364         // Only if there is not a protocol specification that avformat can handle
365         if ( mrl && !url_exist( file ) )
366         {
367                 // 'file' becomes format abbreviation
368                 mrl[0] = 0;
369
370                 // Lookup the format
371                 format = av_find_input_format( file );
372
373                 // Eat the format designator
374                 file = ++mrl;
375
376                 if ( format )
377                 {
378                         // Allocate params
379                         params = calloc( sizeof( AVFormatParameters ), 1 );
380
381                         // These are required by video4linux (defaults)
382                         params->width = 640;
383                         params->height = 480;
384                         params->time_base= (AVRational){1,25};
385                         // params->device = file;
386                         params->channels = 2;
387                         params->sample_rate = 48000;
388                 }
389
390                 // XXX: this does not work anymore since avdevice
391                 // TODO: make producer_avddevice?
392                 // Parse out params
393                 mrl = strchr( file, '?' );
394                 while ( mrl )
395                 {
396                         mrl[0] = 0;
397                         char *name = strdup( ++mrl );
398                         char *value = strchr( name, ':' );
399                         if ( value )
400                         {
401                                 value[0] = 0;
402                                 value++;
403                                 char *t = strchr( value, '&' );
404                                 if ( t )
405                                         t[0] = 0;
406                                 if ( !strcmp( name, "frame_rate" ) )
407                                         params->time_base.den = atoi( value );
408                                 else if ( !strcmp( name, "frame_rate_base" ) )
409                                         params->time_base.num = atoi( value );
410                                 else if ( !strcmp( name, "sample_rate" ) )
411                                         params->sample_rate = atoi( value );
412                                 else if ( !strcmp( name, "channels" ) )
413                                         params->channels = atoi( value );
414                                 else if ( !strcmp( name, "width" ) )
415                                         params->width = atoi( value );
416                                 else if ( !strcmp( name, "height" ) )
417                                         params->height = atoi( value );
418                                 else if ( !strcmp( name, "standard" ) )
419                                 {
420                                         standard = strdup( value );
421                                         params->standard = standard;
422                                 }
423                                 else if ( !strcmp( name, "av" ) )
424                                         av = atoi( value );
425                         }
426                         free( name );
427                         mrl = strchr( mrl, '&' );
428                 }
429         }
430
431         // Now attempt to open the file
432         error = av_open_input_file( &context, file, format, 0, params ) < 0;
433
434         // Cleanup AVFormatParameters
435         free( standard );
436         free( params );
437
438         // If successful, then try to get additional info
439         if ( error == 0 )
440         {
441                 // Get the stream info
442                 error = av_find_stream_info( context ) < 0;
443
444                 // Continue if no error
445                 if ( error == 0 )
446                 {
447                         // We will default to the first audio and video streams found
448                         int audio_index = -1;
449                         int video_index = -1;
450                         int av_bypass = 0;
451
452                         // Now set properties where we can (use default unknowns if required)
453                         if ( context->duration != AV_NOPTS_VALUE )
454                         {
455                                 // This isn't going to be accurate for all formats
456                                 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + 0.5 );
457                                 mlt_properties_set_position( properties, "out", frames - 1 );
458                                 mlt_properties_set_position( properties, "length", frames );
459                         }
460
461                         // Find default audio and video streams
462                         find_default_streams( properties, context, &audio_index, &video_index );
463
464                         if ( context->start_time != AV_NOPTS_VALUE )
465                                 mlt_properties_set_double( properties, "_start_time", context->start_time );
466
467                         // Check if we're seekable (something funny about mpeg here :-/)
468                         if ( strcmp( file, "pipe:" ) && strncmp( file, "http://", 6 )  && strncmp( file, "udp:", 4 )  && strncmp( file, "tcp:", 4 ) && strncmp( file, "rtsp:", 5 )  && strncmp( file, "rtp:", 4 ) )
469                         {
470                                 mlt_properties_set_int( properties, "seekable", av_seek_frame( context, -1, mlt_properties_get_double( properties, "_start_time" ), AVSEEK_FLAG_BACKWARD ) >= 0 );
471                                 mlt_properties_set_data( properties, "dummy_context", context, 0, producer_file_close, NULL );
472                                 av_open_input_file( &context, file, NULL, 0, NULL );
473                                 av_find_stream_info( context );
474                         }
475                         else
476                                 av_bypass = 1;
477
478                         // Store selected audio and video indexes on properties
479                         mlt_properties_set_int( properties, "_audio_index", audio_index );
480                         mlt_properties_set_int( properties, "_video_index", video_index );
481                         mlt_properties_set_int( properties, "_last_position", -1 );
482
483                         // Fetch the width, height and aspect ratio
484                         if ( video_index != -1 )
485                         {
486                                 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
487                                 mlt_properties_set_int( properties, "width", codec_context->width );
488                                 mlt_properties_set_int( properties, "height", codec_context->height );
489
490                                 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
491                                 {
492                                         // Fetch the first frame of DV so we can read it directly
493                                         AVPacket pkt;
494                                         int ret = 0;
495                                         while ( ret >= 0 )
496                                         {
497                                                 ret = av_read_frame( context, &pkt );
498                                                 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
499                                                 {
500                                                         mlt_properties_set_double( properties, "aspect_ratio",
501                                                                 get_aspect_ratio( context->streams[ video_index ], codec_context, &pkt ) );
502                                                         break;
503                                                 }
504                                         }
505                                 }
506                                 else
507                                 {
508                                         mlt_properties_set_double( properties, "aspect_ratio",
509                                                 get_aspect_ratio( context->streams[ video_index ], codec_context, NULL ) );
510                                 }
511                         }
512
513                         // Read Metadata
514                         if (context->title != NULL)
515                                 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
516                         if (context->author != NULL)
517                                 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
518                         if (context->copyright != NULL)
519                                 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
520                         if (context->comment != NULL)
521                                 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
522                         if (context->album != NULL)
523                                 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
524                         if (context->year != 0)
525                                 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
526                         if (context->track != 0)
527                                 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
528
529                         // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
530                         if ( av == 0 && audio_index != -1 && video_index != -1 )
531                         {
532                                 // We'll use the open one as our video_context
533                                 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
534
535                                 // And open again for our audio context
536                                 av_open_input_file( &context, file, NULL, 0, NULL );
537                                 av_find_stream_info( context );
538
539                                 // Audio context
540                                 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
541                         }
542                         else if ( av != 2 && video_index != -1 )
543                         {
544                                 // We only have a video context
545                                 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
546                         }
547                         else if ( audio_index != -1 )
548                         {
549                                 // We only have an audio context
550                                 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
551                         }
552                         else
553                         {
554                                 // Something has gone wrong
555                                 error = -1;
556                         }
557
558                         mlt_properties_set_int( properties, "av_bypass", av_bypass );
559                 }
560         }
561
562         // Unlock the mutex now
563         avformat_unlock( );
564
565         return error;
566 }
567
568 /** Convert a frame position to a time code.
569 */
570
571 static double producer_time_of_frame( mlt_producer this, mlt_position position )
572 {
573         return ( double )position / mlt_producer_get_fps( this );
574 }
575
576 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format *format, int width, int height )
577 {
578 #ifdef SWSCALE
579         if ( pix_fmt == PIX_FMT_RGB32 )
580         {
581                 *format = mlt_image_rgb24a;
582                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
583                         width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
584                 AVPicture output;
585                 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
586                 sws_scale( context, frame->data, frame->linesize, 0, height,
587                         output.data, output.linesize);
588                 sws_freeContext( context );
589         }
590         else if ( *format == mlt_image_yuv420p )
591         {
592                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
593                         width, height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
594                 AVPicture output;
595                 output.data[0] = buffer;
596                 output.data[1] = buffer + width * height;
597                 output.data[2] = buffer + ( 3 * width * height ) / 2;
598                 output.linesize[0] = width;
599                 output.linesize[1] = width >> 1;
600                 output.linesize[2] = width >> 1;
601                 sws_scale( context, frame->data, frame->linesize, 0, height,
602                         output.data, output.linesize);
603                 sws_freeContext( context );
604         }
605         else if ( *format == mlt_image_rgb24 )
606         {
607                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
608                         width, height, PIX_FMT_RGB24, SWS_FAST_BILINEAR, NULL, NULL, NULL);
609                 AVPicture output;
610                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
611                 sws_scale( context, frame->data, frame->linesize, 0, height,
612                         output.data, output.linesize);
613                 sws_freeContext( context );
614         }
615         else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
616         {
617                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
618                         width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
619                 AVPicture output;
620                 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
621                 sws_scale( context, frame->data, frame->linesize, 0, height,
622                         output.data, output.linesize);
623                 sws_freeContext( context );
624         }
625         else
626         {
627                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
628                         width, height, PIX_FMT_YUYV422, SWS_FAST_BILINEAR, NULL, NULL, NULL);
629                 AVPicture output;
630                 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
631                 sws_scale( context, frame->data, frame->linesize, 0, height,
632                         output.data, output.linesize);
633                 sws_freeContext( context );
634         }
635 #else
636         if ( *format == mlt_image_yuv420p )
637         {
638                 AVPicture pict;
639                 pict.data[0] = buffer;
640                 pict.data[1] = buffer + width * height;
641                 pict.data[2] = buffer + ( 3 * width * height ) / 2;
642                 pict.linesize[0] = width;
643                 pict.linesize[1] = width >> 1;
644                 pict.linesize[2] = width >> 1;
645                 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
646         }
647         else if ( *format == mlt_image_rgb24 )
648         {
649                 AVPicture output;
650                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
651                 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
652         }
653         else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
654         {
655                 AVPicture output;
656                 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
657                 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
658         }
659         else
660         {
661                 AVPicture output;
662                 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
663                 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
664         }
665 #endif
666 }
667
668 /** Allocate the image buffer and set it on the frame.
669 */
670
671 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
672 {
673         int size = 0;
674
675         if ( codec_context->width == 0 || codec_context->height == 0 )
676                 return size;
677
678         *width = codec_context->width;
679         *height = codec_context->height;
680         mlt_properties_set_int( frame_properties, "width", *width );
681         mlt_properties_set_int( frame_properties, "height", *height );
682
683         if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
684                 size = *width * ( *height + 1 ) * 4;
685         else switch ( *format )
686         {
687                 case mlt_image_yuv420p:
688                         size = *width * 3 * ( *height + 1 ) / 2;
689                         break;
690                 case mlt_image_rgb24:
691                         size = *width * ( *height + 1 ) * 3;
692                         break;
693                 case mlt_image_rgb24a:
694                 case mlt_image_opengl:
695                         size = *width * ( *height + 1 ) * 4;
696                         break;
697                 default:
698                         *format = mlt_image_yuv422;
699                         size = *width * ( *height + 1 ) * 2;
700                         break;
701         }
702
703         // Construct the output image
704         *buffer = mlt_pool_alloc( size );
705         if ( *buffer )
706                 mlt_properties_set_data( frame_properties, "image", *buffer, size, (mlt_destructor)mlt_pool_release, NULL );
707         else
708                 size = 0;
709
710         return size;
711 }
712
713 /** Get an image from a frame.
714 */
715
716 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
717 {
718         // Get the properties from the frame
719         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
720
721         // Obtain the frame number of this frame
722         mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
723
724         // Get the producer
725         mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
726
727         // Get the producer properties
728         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
729
730         // Fetch the video_context
731         AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
732
733         // Get the video_index
734         int index = mlt_properties_get_int( properties, "video_index" );
735
736         // Obtain the expected frame numer
737         mlt_position expected = mlt_properties_get_position( properties, "_video_expected" );
738
739         // Get the video stream
740         AVStream *stream = context->streams[ index ];
741
742         // Get codec context
743         AVCodecContext *codec_context = stream->codec;
744
745         // Packet
746         AVPacket pkt;
747
748         // Get the conversion frame
749         AVFrame *av_frame = mlt_properties_get_data( properties, "av_frame", NULL );
750
751         // Special case pause handling flag
752         int paused = 0;
753
754         // Special case ffwd handling
755         int ignore = 0;
756
757         // We may want to use the source fps if available
758         double source_fps = mlt_properties_get_double( properties, "source_fps" );
759         double fps = mlt_producer_get_fps( this );
760
761         // This is the physical frame position in the source
762         int req_position = ( int )( position / fps * source_fps + 0.5 );
763
764         // Get the seekable status
765         int seekable = mlt_properties_get_int( properties, "seekable" );
766
767         // Hopefully provide better support for streams...
768         int av_bypass = mlt_properties_get_int( properties, "av_bypass" );
769
770         // Determines if we have to decode all frames in a sequence
771         int must_decode = 1;
772
773         // Temporary hack to improve intra frame only
774         must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
775                                   strcmp( codec_context->codec->name, "dvvideo" ) &&
776                                   strcmp( codec_context->codec->name, "huffyuv" ) &&
777                                   strcmp( codec_context->codec->name, "mjpeg" ) &&
778                                   strcmp( codec_context->codec->name, "rawvideo" );
779
780         int last_position = mlt_properties_get_int( properties, "_last_position" );
781
782         // Seek if necessary
783         if ( position != expected || last_position == -1 )
784         {
785                 if ( av_frame != NULL && position + 1 == expected )
786                 {
787                         // We're paused - use last image
788                         paused = 1;
789                 }
790                 else if ( !seekable && position > expected && ( position - expected ) < 250 )
791                 {
792                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
793                         ignore = ( int )( ( position - expected ) / fps * source_fps );
794                 }
795                 else if ( seekable && ( position < expected || position - expected >= 12 || last_position == -1 ) )
796                 {
797                         // Calculate the timestamp for the requested frame
798                         int64_t timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
799                         if ( ( uint64_t )context->start_time != AV_NOPTS_VALUE )
800                                 timestamp += context->start_time;
801                         if ( must_decode )
802                                 timestamp -= AV_TIME_BASE;
803                         if ( timestamp < 0 )
804                                 timestamp = 0;
805
806                         // Set to the timestamp
807                         mlt_log_debug( MLT_PRODUCER_SERVICE( this ), "seeking timestamp %lld position %d expected %d last_pos %d\n",
808                                 timestamp, position, expected, last_position );
809                         av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
810
811                         // Remove the cached info relating to the previous position
812                         mlt_properties_set_int( properties, "_current_position", -1 );
813                         mlt_properties_set_int( properties, "_last_position", -1 );
814                         mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
815                         av_frame = NULL;
816                 }
817         }
818
819         // Duplicate the last image if necessary (see comment on rawvideo below)
820         int current_position = mlt_properties_get_int( properties, "_current_position" );
821         int got_picture = mlt_properties_get_int( properties, "_got_picture" );
822         if ( av_frame != NULL && got_picture && ( paused || current_position >= req_position ) && av_bypass == 0 )
823         {
824                 // Duplicate it
825                 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
826                         convert_image( av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
827                 else
828                         mlt_frame_get_image( frame, buffer, format, width, height, writable );
829         }
830         else
831         {
832                 int ret = 0;
833                 int int_position = 0;
834                 got_picture = 0;
835
836                 av_init_packet( &pkt );
837
838                 // Construct an AVFrame for YUV422 conversion
839                 if ( av_frame == NULL )
840                         av_frame = avcodec_alloc_frame( );
841
842                 while( ret >= 0 && !got_picture )
843                 {
844                         // Read a packet
845                         ret = av_read_frame( context, &pkt );
846
847                         // We only deal with video from the selected video_index
848                         if ( ret >= 0 && pkt.stream_index == index && pkt.size > 0 )
849                         {
850                                 // Determine time code of the packet
851                                 if (pkt.dts != AV_NOPTS_VALUE)
852                                 {
853                                         int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
854                                         if ( context->start_time != AV_NOPTS_VALUE )
855                                                 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
856                                         last_position = mlt_properties_get_int( properties, "_last_position" );
857                                         if ( int_position == last_position )
858                                                 int_position = last_position + 1;
859                                 }
860                                 else
861                                 {
862                                         int_position = req_position;
863                                 }
864                                 // Make a dumb assumption on streams that contain wild timestamps
865                                 if ( (unsigned) req_position - (unsigned) int_position > 999 )
866                                         int_position = req_position;
867                                 mlt_properties_set_int( properties, "_last_position", int_position );
868
869                                 // Decode the image
870                                 if ( must_decode || int_position >= req_position )
871                                         ret = avcodec_decode_video( codec_context, av_frame, &got_picture, pkt.data, pkt.size );
872
873                                 if ( got_picture )
874                                 {
875                                         // Handle ignore
876                                         if ( int_position < req_position )
877                                         {
878                                                 ignore = 0;
879                                                 got_picture = 0;
880                                         }
881                                         else if ( int_position >= req_position )
882                                         {
883                                                 ignore = 0;
884                                         }
885                                         else if ( ignore -- )
886                                         {
887                                                 got_picture = 0;
888                                         }
889                                 }
890                                 mlt_log_debug( MLT_PRODUCER_SERVICE(this), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d got_pic %d key %d\n",
891                                         pkt.dts, req_position, current_position, int_position, got_picture, pkt.flags & PKT_FLAG_KEY );
892                                 av_free_packet( &pkt );
893                         }
894                         else if ( ret >= 0 )
895                         {
896                                 av_free_packet( &pkt );
897                         }
898
899                         // Now handle the picture if we have one
900                         if ( got_picture )
901                         {
902                                 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
903                                 {
904                                         convert_image( av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
905                                         if ( !mlt_properties_get( properties, "force_progressive" ) )
906                                                 mlt_properties_set_int( frame_properties, "progressive", !av_frame->interlaced_frame );
907                                         mlt_properties_set_int( properties, "top_field_first", av_frame->top_field_first );
908                                         mlt_properties_set_int( properties, "_current_position", int_position );
909                                         mlt_properties_set_int( properties, "_got_picture", 1 );
910                                         mlt_properties_set_data( properties, "av_frame", av_frame, 0, av_free, NULL );
911                                 }
912                                 else
913                                 {
914                                         got_picture = 0;
915                                 }
916                         }
917                 }
918                 if ( !got_picture )
919                         mlt_frame_get_image( frame, buffer, format, width, height, writable );
920         }
921
922         // Very untidy - for rawvideo, the packet contains the frame, hence the free packet
923         // above will break the pause behaviour - so we wipe the frame now
924         if ( !strcmp( codec_context->codec->name, "rawvideo" ) )
925                 mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
926
927         // Set the field order property for this frame
928         mlt_properties_set_int( frame_properties, "top_field_first", mlt_properties_get_int( properties, "top_field_first" ) );
929
930         // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
931         mlt_properties_set_position( properties, "_video_expected", position + 1 );
932
933         return 0;
934 }
935
936 /** Process properties as AVOptions and apply to AV context obj
937 */
938
939 static void apply_properties( void *obj, mlt_properties properties, int flags )
940 {
941         int i;
942         int count = mlt_properties_count( properties );
943         for ( i = 0; i < count; i++ )
944         {
945                 const char *opt_name = mlt_properties_get_name( properties, i );
946                 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
947                 if ( opt != NULL )
948 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
949                         av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
950 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
951                         av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
952 #else
953                         av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
954 #endif
955         }
956 }
957
958 /** Set up video handling.
959 */
960
961 static void producer_set_up_video( mlt_producer this, mlt_frame frame )
962 {
963         // Get the properties
964         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
965
966         // Fetch the video_context
967         AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
968
969         // Get the video_index
970         int index = mlt_properties_get_int( properties, "video_index" );
971
972         // Reopen the file if necessary
973         if ( !context && index > -1 )
974         {
975                 mlt_events_block( properties, this );
976                 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(this) ),
977                         mlt_properties_get( properties, "resource" ) );
978                 context = mlt_properties_get_data( properties, "video_context", NULL );
979                 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
980                 mlt_events_unblock( properties, this );
981
982                 // Process properties as AVOptions
983                 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
984         }
985
986         // Exception handling for video_index
987         if ( context && index >= (int) context->nb_streams )
988         {
989                 // Get the last video stream
990                 for ( index = context->nb_streams - 1; index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO; --index );
991                 mlt_properties_set_int( properties, "video_index", index );
992         }
993         if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
994         {
995                 // Invalidate the video stream
996                 index = -1;
997                 mlt_properties_set_int( properties, "video_index", index );
998         }
999
1000         // Get the frame properties
1001         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1002
1003         if ( context && index > -1 )
1004         {
1005                 // Get the video stream
1006                 AVStream *stream = context->streams[ index ];
1007
1008                 // Get codec context
1009                 AVCodecContext *codec_context = stream->codec;
1010
1011                 // Get the codec
1012                 AVCodec *codec = mlt_properties_get_data( properties, "video_codec", NULL );
1013
1014                 // Update the video properties if the index changed
1015                 if ( index != mlt_properties_get_int( properties, "_video_index" ) )
1016                 {
1017                         // Reset the video properties if the index changed
1018                         mlt_properties_set_int( properties, "_video_index", index );
1019                         mlt_properties_set_data( properties, "video_codec", NULL, 0, NULL, NULL );
1020                         mlt_properties_set_int( properties, "width", codec_context->width );
1021                         mlt_properties_set_int( properties, "height", codec_context->height );
1022                         // TODO: get the first usable AVPacket and reset the stream position
1023                         mlt_properties_set_double( properties, "aspect_ratio",
1024                                 get_aspect_ratio( context->streams[ index ], codec_context, NULL ) );
1025                         codec = NULL;
1026                 }
1027
1028                 // Initialise the codec if necessary
1029                 if ( codec == NULL )
1030                 {
1031                         // Initialise multi-threading
1032                         int thread_count = mlt_properties_get_int( properties, "threads" );
1033                         if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1034                                 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1035                         if ( thread_count > 1 )
1036                         {
1037                                 avcodec_thread_init( codec_context, thread_count );
1038                                 codec_context->thread_count = thread_count;
1039                         }
1040
1041                         // Find the codec
1042                         codec = avcodec_find_decoder( codec_context->codec_id );
1043
1044                         // If we don't have a codec and we can't initialise it, we can't do much more...
1045                         avformat_lock( );
1046                         if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
1047                         {
1048                                 // Now store the codec with its destructor
1049                                 mlt_properties_set_data( properties, "video_codec", codec_context, 0, producer_codec_close, NULL );
1050                         }
1051                         else
1052                         {
1053                                 // Remember that we can't use this later
1054                                 mlt_properties_set_int( properties, "video_index", -1 );
1055                                 index = -1;
1056                         }
1057                         avformat_unlock( );
1058
1059                         // Process properties as AVOptions
1060                         apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1061                 }
1062
1063                 // No codec, no show...
1064                 if ( codec && index > -1 )
1065                 {
1066                         double source_fps = 0;
1067                         double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1068                         double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1069                                 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1070
1071                         // Determine the fps
1072                         source_fps = ( double )codec_context->time_base.den / ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num );
1073
1074                         // We'll use fps if it's available
1075                         if ( source_fps > 0 )
1076                                 mlt_properties_set_double( properties, "source_fps", source_fps );
1077                         else
1078                                 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( this ) );
1079                         mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
1080
1081                         // Set the width and height
1082                         mlt_properties_set_int( frame_properties, "width", codec_context->width );
1083                         mlt_properties_set_int( frame_properties, "height", codec_context->height );
1084                         mlt_properties_set_int( frame_properties, "real_width", codec_context->width );
1085                         mlt_properties_set_int( frame_properties, "real_height", codec_context->height );
1086                         mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1087                         if ( mlt_properties_get( properties, "force_progressive" ) )
1088                                 mlt_properties_set_int( frame_properties, "progressive", mlt_properties_get_int( properties, "force_progressive" ) );
1089
1090                         mlt_frame_push_get_image( frame, producer_get_image );
1091                         mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
1092                 }
1093                 else
1094                 {
1095                         mlt_properties_set_int( frame_properties, "test_image", 1 );
1096                 }
1097         }
1098         else
1099         {
1100                 mlt_properties_set_int( frame_properties, "test_image", 1 );
1101         }
1102 }
1103
1104 /** Get the audio from a frame.
1105 */
1106
1107 static int producer_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1108 {
1109         // Get the properties from the frame
1110         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1111
1112         // Obtain the frame number of this frame
1113         mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1114
1115         // Get the producer
1116         mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
1117
1118         // Get the producer properties
1119         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
1120
1121         // Fetch the audio_context
1122         AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
1123
1124         // Get the audio_index
1125         int index = mlt_properties_get_int( properties, "audio_index" );
1126
1127         // Get the seekable status
1128         int seekable = mlt_properties_get_int( properties, "seekable" );
1129
1130         // Obtain the expected frame numer
1131         mlt_position expected = mlt_properties_get_position( properties, "_audio_expected" );
1132
1133         // Obtain the resample context if it exists (not always needed)
1134         ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
1135
1136         // Obtain the audio buffers
1137         int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
1138         int16_t *decode_buffer = mlt_properties_get_data( properties, "decode_buffer", NULL );
1139
1140         // Get amount of audio used
1141         int audio_used =  mlt_properties_get_int( properties, "_audio_used" );
1142
1143         // Calculate the real time code
1144         double real_timecode = producer_time_of_frame( this, position );
1145
1146         // Get the audio stream
1147         AVStream *stream = context->streams[ index ];
1148
1149         // Get codec context
1150         AVCodecContext *codec_context = stream->codec;
1151
1152         // Packet
1153         AVPacket pkt;
1154
1155         // Number of frames to ignore (for ffwd)
1156         int ignore = 0;
1157
1158         // Flag for paused (silence)
1159         int paused = 0;
1160
1161         // Check for resample and create if necessary
1162         if ( resample == NULL && codec_context->channels <= 2 )
1163         {
1164                 // Create the resampler
1165 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1166                 resample = av_audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate,
1167                         SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1168 #else
1169                 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
1170 #endif
1171
1172                 // And store it on properties
1173                 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
1174         }
1175         else if ( resample == NULL )
1176         {
1177                 // TODO: uncomment and remove following line when full multi-channel support is ready
1178                 // *channels = codec_context->channels;
1179                 codec_context->request_channels = *channels;
1180
1181                 *frequency = codec_context->sample_rate;
1182         }
1183
1184         // Check for audio buffer and create if necessary
1185         if ( audio_buffer == NULL )
1186         {
1187                 // Allocate the audio buffer
1188                 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1189
1190                 // And store it on properties for reuse
1191                 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
1192         }
1193
1194         // Check for decoder buffer and create if necessary
1195         if ( decode_buffer == NULL )
1196         {
1197                 // Allocate the audio buffer
1198                 decode_buffer = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1199
1200                 // And store it on properties for reuse
1201                 mlt_properties_set_data( properties, "decode_buffer", decode_buffer, 0, ( mlt_destructor )av_free, NULL );
1202         }
1203
1204         // Seek if necessary
1205         if ( position != expected )
1206         {
1207                 if ( position + 1 == expected )
1208                 {
1209                         // We're paused - silence required
1210                         paused = 1;
1211                 }
1212                 else if ( !seekable && position > expected && ( position - expected ) < 250 )
1213                 {
1214                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
1215                         ignore = position - expected;
1216                 }
1217                 else if ( position < expected || position - expected >= 12 )
1218                 {
1219                         int64_t timestamp = ( int64_t )( real_timecode * AV_TIME_BASE + 0.5 );
1220                         if ( context->start_time != AV_NOPTS_VALUE )
1221                                 timestamp += context->start_time;
1222                         if ( timestamp < 0 )
1223                                 timestamp = 0;
1224
1225                         // Set to the real timecode
1226                         if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1227                                 paused = 1;
1228
1229                         // Clear the usage in the audio buffer
1230                         audio_used = 0;
1231                 }
1232         }
1233
1234         // Get the audio if required
1235         if ( !paused )
1236         {
1237                 int ret = 0;
1238                 int got_audio = 0;
1239
1240                 av_init_packet( &pkt );
1241
1242                 while( ret >= 0 && !got_audio )
1243                 {
1244                         // Check if the buffer already contains the samples required
1245                         if ( audio_used >= *samples && ignore == 0 )
1246                         {
1247                                 got_audio = 1;
1248                                 break;
1249                         }
1250
1251                         // Read a packet
1252                         ret = av_read_frame( context, &pkt );
1253
1254                         int len = pkt.size;
1255                         uint8_t *ptr = pkt.data;
1256
1257                         // We only deal with audio from the selected audio_index
1258                         while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
1259                         {
1260                                 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1261
1262                                 // Decode the audio
1263 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1264                                 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1265 #else
1266                                 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1267 #endif
1268                                 if ( ret < 0 )
1269                                 {
1270                                         ret = 0;
1271                                         break;
1272                                 }
1273
1274                                 len -= ret;
1275                                 ptr += ret;
1276
1277                                 if ( data_size > 0 && ( audio_used * *channels + data_size < AVCODEC_MAX_AUDIO_FRAME_SIZE ) )
1278                                 {
1279                                         if ( resample )
1280                                         {
1281                                                 int16_t *source = decode_buffer;
1282                                                 int16_t *dest = &audio_buffer[ audio_used * *channels ];
1283                                                 int convert_samples = data_size / av_get_bits_per_sample_format( codec_context->sample_fmt ) * 8 / codec_context->channels;
1284
1285                                                 audio_used += audio_resample( resample, dest, source, convert_samples );
1286                                         }
1287                                         else
1288                                         {
1289                                                 memcpy( &audio_buffer[ audio_used * *channels ], decode_buffer, data_size );
1290                                                 audio_used += data_size / *channels / av_get_bits_per_sample_format( codec_context->sample_fmt ) * 8;
1291                                         }
1292
1293                                         // Handle ignore
1294                                         while ( ignore && audio_used > *samples )
1295                                         {
1296                                                 ignore --;
1297                                                 audio_used -= *samples;
1298                                                 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
1299                                         }
1300                                 }
1301
1302                                 // If we're behind, ignore this packet
1303                                 if ( pkt.pts >= 0 )
1304                                 {
1305                                         double current_pts = av_q2d( stream->time_base ) * pkt.pts;
1306                                         double source_fps = mlt_properties_get_double( properties, "source_fps" );
1307                                         int req_position = ( int )( real_timecode * source_fps + 0.5 );
1308                                         int int_position = ( int )( current_pts * source_fps + 0.5 );
1309
1310                                         if ( context->start_time != AV_NOPTS_VALUE )
1311                                                 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1312                                         if ( seekable && !ignore && int_position < req_position )
1313                                                 ignore = 1;
1314                                 }
1315                         }
1316
1317                         // We're finished with this packet regardless
1318                         av_free_packet( &pkt );
1319                 }
1320
1321                 *buffer = mlt_pool_alloc( *samples * *channels * sizeof( int16_t ) );
1322                 mlt_properties_set_data( frame_properties, "audio", *buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
1323
1324                 // Now handle the audio if we have enough
1325                 if ( audio_used >= *samples )
1326                 {
1327                         memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
1328                         audio_used -= *samples;
1329                         memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
1330                 }
1331                 else
1332                 {
1333                         memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
1334                 }
1335
1336                 // Store the number of audio samples still available
1337                 mlt_properties_set_int( properties, "_audio_used", audio_used );
1338         }
1339         else
1340         {
1341                 // Get silence and don't touch the context
1342                 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1343         }
1344
1345         // Regardless of speed (other than paused), we expect to get the next frame
1346         if ( !paused )
1347                 mlt_properties_set_position( properties, "_audio_expected", position + 1 );
1348
1349         return 0;
1350 }
1351
1352 /** Set up audio handling.
1353 */
1354
1355 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
1356 {
1357         // Get the properties
1358         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
1359
1360         // Fetch the audio_context
1361         AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
1362
1363         // Get the audio_index
1364         int index = mlt_properties_get_int( properties, "audio_index" );
1365
1366         // Reopen the file if necessary
1367         if ( !context && index > -1 )
1368         {
1369                 mlt_events_block( properties, this );
1370                 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(this) ),
1371                         mlt_properties_get( properties, "resource" ) );
1372                 context = mlt_properties_get_data( properties, "audio_context", NULL );
1373                 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
1374                 mlt_events_unblock( properties, this );
1375         }
1376
1377         // Exception handling for audio_index
1378         if ( context && index >= (int) context->nb_streams )
1379         {
1380                 for ( index = context->nb_streams - 1; index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO; --index );
1381                 mlt_properties_set_int( properties, "audio_index", index );
1382         }
1383         if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1384         {
1385                 index = -1;
1386                 mlt_properties_set_int( properties, "audio_index", index );
1387         }
1388
1389         // Update the audio properties if the index changed
1390         if ( index > -1 && index != mlt_properties_get_int( properties, "_audio_index" ) )
1391         {
1392                 mlt_properties_set_int( properties, "_audio_index", index );
1393                 mlt_properties_set_data( properties, "audio_codec", NULL, 0, NULL, NULL );
1394         }
1395
1396         // Deal with audio context
1397         if ( context != NULL && index > -1 )
1398         {
1399                 // Get the frame properties
1400                 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1401
1402                 // Get the audio stream
1403                 AVStream *stream = context->streams[ index ];
1404
1405                 // Get codec context
1406                 AVCodecContext *codec_context = stream->codec;
1407
1408                 // Get the codec
1409                 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
1410
1411                 // Initialise the codec if necessary
1412                 if ( codec == NULL )
1413                 {
1414                         // Find the codec
1415                         codec = avcodec_find_decoder( codec_context->codec_id );
1416
1417                         // If we don't have a codec and we can't initialise it, we can't do much more...
1418                         avformat_lock( );
1419                         if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
1420                         {
1421                                 // Now store the codec with its destructor
1422                                 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
1423
1424                         }
1425                         else
1426                         {
1427                                 // Remember that we can't use this later
1428                                 mlt_properties_set_int( properties, "audio_index", -1 );
1429                                 index = -1;
1430                         }
1431                         avformat_unlock( );
1432
1433                         // Process properties as AVOptions
1434                         apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1435                 }
1436
1437                 // No codec, no show...
1438                 if ( codec && index > -1 )
1439                 {
1440                         mlt_frame_push_audio( frame, producer_get_audio );
1441                         mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
1442                         mlt_properties_set_int( frame_properties, "frequency", codec_context->sample_rate );
1443                         mlt_properties_set_int( frame_properties, "channels", codec_context->channels );
1444                 }
1445         }
1446 }
1447
1448 /** Our get frame implementation.
1449 */
1450
1451 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
1452 {
1453         // Create an empty frame
1454         *frame = mlt_frame_init( MLT_PRODUCER_SERVICE( this ) );
1455
1456         // Update timecode on the frame we're creating
1457         mlt_frame_set_position( *frame, mlt_producer_position( this ) );
1458
1459         // Set the position of this producer
1460         mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( this ) );
1461
1462         // Set up the video
1463         producer_set_up_video( this, *frame );
1464
1465         // Set up the audio
1466         producer_set_up_audio( this, *frame );
1467
1468         // Set the aspect_ratio
1469         mlt_properties_set_double( MLT_FRAME_PROPERTIES( *frame ), "aspect_ratio", mlt_properties_get_double( MLT_PRODUCER_PROPERTIES( this ), "aspect_ratio" ) );
1470
1471         // Calculate the next timecode
1472         mlt_producer_prepare_next( this );
1473
1474         return 0;
1475 }