]> git.sesse.net Git - mlt/blob - src/modules/avformat/producer_avformat.c
add luma to composite.
[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  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  */
20
21 // Local header files
22 #include "producer_avformat.h"
23
24 // MLT Header files
25 #include <framework/mlt_frame.h>
26
27 // ffmpeg Header files
28 #include <ffmpeg/avformat.h>
29
30 // System header files
31 #include <stdlib.h>
32 #include <string.h>
33 #include <pthread.h>
34 #include <math.h>
35
36 // Forward references.
37 static int producer_open( mlt_producer this, char *file );
38 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
39
40 // A static flag used to determine if avformat has been initialised
41 static int avformat_initialised = 0;
42 static pthread_mutex_t avformat_mutex;
43
44 void *av_malloc( unsigned int size )
45 {
46         return mlt_pool_alloc( size );
47 }
48
49 void *av_realloc( void *ptr, unsigned int size )
50 {
51         return mlt_pool_realloc( ptr, size );
52 }
53
54 void av_free( void *ptr )
55 {
56         return mlt_pool_release( ptr );
57 }
58
59 /** Constructor for libavformat.
60 */
61
62 mlt_producer producer_avformat_init( char *file )
63 {
64         mlt_producer this = NULL;
65
66         // Check that we have a non-NULL argument
67         if ( file != NULL )
68         {
69                 // Construct the producer
70                 this = calloc( 1, sizeof( struct mlt_producer_s ) );
71
72                 // Initialise it
73                 if ( mlt_producer_init( this, NULL ) == 0 )
74                 {
75                         // Get the properties
76                         mlt_properties properties = mlt_producer_properties( this );
77
78                         // Set the resource property (required for all producers)
79                         mlt_properties_set( properties, "resource", file );
80
81                         // TEST: audio sync tweaking
82                         mlt_properties_set_double( properties, "discrepancy", 1 );
83
84                         // Register our get_frame implementation
85                         this->get_frame = producer_get_frame;
86
87                         // Initialise avformat if necessary
88                         if ( avformat_initialised == 0 )
89                         {
90                                 avformat_initialised = 1;
91                                 pthread_mutex_init( &avformat_mutex, NULL );
92                                 av_register_all( );
93                         }
94
95                         // Open the file
96                         if ( producer_open( this, file ) != 0 )
97                         {
98                                 // Clean up
99                                 mlt_producer_close( this );
100                                 this = NULL;
101                         }
102                 }
103         }
104
105         return this;
106 }
107
108 /** Find the default streams.
109 */
110
111 static void find_default_streams( AVFormatContext *context, int *audio_index, int *video_index )
112 {
113         int i;
114
115         // Allow for multiple audio and video streams in the file and select first of each (if available)
116         for( i = 0; i < context->nb_streams; i++ ) 
117         {
118                 // Get the codec context
119                 AVCodecContext *codec_context = &context->streams[ i ]->codec;
120
121                 // Determine the type and obtain the first index of each type
122                 switch( codec_context->codec_type ) 
123                 {
124                         case CODEC_TYPE_VIDEO:
125                                 if ( *video_index < 0 )
126                                         *video_index = i;
127                                 break;
128                         case CODEC_TYPE_AUDIO:
129                                 if ( *audio_index < 0 )
130                                         *audio_index = i;
131                                 break;
132                         default:
133                                 break;
134                 }
135         }
136 }
137
138 /** Producer file destructor.
139 */
140
141 static void producer_file_close( void *context )
142 {
143         if ( context != NULL )
144         {
145                 // Lock the mutex now
146                 pthread_mutex_lock( &avformat_mutex );
147
148                 // Close the file
149                 av_close_input_file( context );
150
151                 // Unlock the mutex now
152                 pthread_mutex_unlock( &avformat_mutex );
153         }
154 }
155
156 /** Producer file destructor.
157 */
158
159 static void producer_codec_close( void *codec )
160 {
161         if ( codec != NULL )
162         {
163                 // Lock the mutex now
164                 pthread_mutex_lock( &avformat_mutex );
165
166                 // Close the file
167                 avcodec_close( codec );
168
169                 // Unlock the mutex now
170                 pthread_mutex_unlock( &avformat_mutex );
171         }
172 }
173
174 /** Open the file.
175 */
176
177 static int producer_open( mlt_producer this, char *file )
178 {
179         // Return an error code (0 == no error)
180         int error = 0;
181
182         // Context for avformat
183         AVFormatContext *context = NULL;
184
185         // Get the properties
186         mlt_properties properties = mlt_producer_properties( this );
187
188         // We will treat everything with the producer fps
189         double fps = mlt_properties_get_double( properties, "fps" );
190
191         // Lock the mutex now
192         pthread_mutex_lock( &avformat_mutex );
193
194         // Now attempt to open the file
195         error = av_open_input_file( &context, file, NULL, 0, NULL );
196         error = error < 0;
197
198         // If successful, then try to get additional info
199         if ( error == 0 )
200         {
201                 // Get the stream info
202                 error = av_find_stream_info( context ) < 0;
203
204                 // Continue if no error
205                 if ( error == 0 )
206                 {
207                         // We will default to the first audio and video streams found
208                         int audio_index = -1;
209                         int video_index = -1;
210
211                         // Now set properties where we can (use default unknowns if required)
212                         if ( context->duration != AV_NOPTS_VALUE ) 
213                         {
214                                 // This isn't going to be accurate for all formats
215                                 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps );
216                                 mlt_properties_set_position( properties, "out", frames - 2 );
217                                 mlt_properties_set_position( properties, "length", frames - 1 );
218                         }
219
220                         // Find default audio and video streams
221                         find_default_streams( context, &audio_index, &video_index );
222
223                         // Store selected audio and video indexes on properties
224                         mlt_properties_set_int( properties, "audio_index", audio_index );
225                         mlt_properties_set_int( properties, "video_index", video_index );
226
227                         // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
228                         if ( audio_index != -1 && video_index != -1 )
229                         {
230                                 // We'll use the open one as our video_context
231                                 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
232
233                                 // And open again for our audio context
234                                 av_open_input_file( &context, file, NULL, 0, NULL );
235                                 av_find_stream_info( context );
236
237                                 // Audio context
238                                 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
239                         }
240                         else if ( video_index != -1 )
241                         {
242                                 // We only have a video context
243                                 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
244                         }
245                         else if ( audio_index != -1 )
246                         {
247                                 // We only have an audio context
248                                 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
249                         }
250                         else
251                         {
252                                 // Something has gone wrong
253                                 error = -1;
254                         }
255                 }
256         }
257
258         // Unlock the mutex now
259         pthread_mutex_unlock( &avformat_mutex );
260
261         return error;
262 }
263
264 /** Convert a frame position to a time code.
265 */
266
267 static double producer_time_of_frame( mlt_producer this, mlt_position position )
268 {
269         // Get the properties
270         mlt_properties properties = mlt_producer_properties( this );
271
272         // Obtain the fps
273         double fps = mlt_properties_get_double( properties, "fps" );
274
275         // Do the calc
276         return ( double )position / fps;
277 }
278
279 /** Get an image from a frame.
280 */
281
282 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
283 {
284         // Get the properties from the frame
285         mlt_properties frame_properties = mlt_frame_properties( frame );
286
287         // Obtain the frame number of this frame
288         mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
289
290         // Get the producer 
291         mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
292
293         // Get the producer properties
294         mlt_properties properties = mlt_producer_properties( this );
295
296         // Fetch the video_context
297         AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
298
299         // Get the video_index
300         int index = mlt_properties_get_int( properties, "video_index" );
301
302         // Obtain the expected frame numer
303         mlt_position expected = mlt_properties_get_position( properties, "video_expected" );
304
305         // Calculate the real time code
306         double real_timecode = producer_time_of_frame( this, position );
307
308         // Get the video stream
309         AVStream *stream = context->streams[ index ];
310
311         // Get codec context
312         AVCodecContext *codec_context = &stream->codec;
313
314         // Packet
315         AVPacket pkt;
316
317         // Get the conversion frame
318         AVPicture *output = mlt_properties_get_data( properties, "video_output_frame", NULL );
319
320         // Special case pause handling flag
321         int paused = 0;
322
323         // Special case ffwd handling
324         int ignore = 0;
325
326         // Current time calcs
327         double current_time = mlt_properties_get_double( properties, "current_time" );
328
329         // We may want to use the source fps if available
330         double source_fps = mlt_properties_get_double( properties, "source_fps" );
331
332         // Set the result arguments that we know here (only *buffer is now required)
333         *format = mlt_image_yuv422;
334         *width = codec_context->width;
335         *height = codec_context->height;
336
337         // Set this on the frame properties
338         mlt_properties_set_int( frame_properties, "width", *width );
339         mlt_properties_set_int( frame_properties, "height", *height );
340
341         // Lock the mutex now
342         pthread_mutex_lock( &avformat_mutex );
343
344         // Construct an AVFrame for YUV422 conversion
345         if ( output == NULL )
346         {
347                 int size = avpicture_get_size( PIX_FMT_YUV422, *width, *height );
348                 size += *width * 2;
349                 uint8_t *buf = mlt_pool_alloc( size );
350                 output = mlt_pool_alloc( sizeof( AVPicture ) );
351                 //memset( output, 0, sizeof( AVPicture ) );
352                 avpicture_fill( output, buf, PIX_FMT_YUV422, *width, *height );
353                 mlt_properties_set_data( properties, "video_output_frame", output, 0, ( mlt_destructor )mlt_pool_release, NULL );
354                 mlt_properties_set_data( properties, "video_output_buffer", buf, 0, ( mlt_destructor )mlt_pool_release, NULL );
355         }
356
357         // Seek if necessary
358         if ( position != expected )
359         {
360                 if ( position + 1 == expected )
361                 {
362                         // We're paused - use last image
363                         paused = 1;
364                 }
365                 else if ( position > expected && ( position - expected ) < 250 )
366                 {
367                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
368                         ignore = position - expected;
369                 }
370                 else
371                 {
372                         // Set to the real timecode
373                         av_seek_frame( context, -1, real_timecode * 1000000.0 );
374         
375                         // Remove the cached info relating to the previous position
376                         mlt_properties_set_double( properties, "current_time", real_timecode );
377                         mlt_properties_set_data( properties, "current_image", NULL, 0, NULL, NULL );
378                 }
379         }
380         
381         // Duplicate the last image if necessary
382         if ( mlt_properties_get_data( properties, "current_image", NULL ) != NULL &&
383                  ( paused || mlt_properties_get_double( properties, "current_time" ) >= real_timecode ) )
384         {
385                 // Get current image and size
386                 int size = 0;
387                 uint8_t *image = mlt_properties_get_data( properties, "current_image", &size );
388
389                 // Duplicate it
390                 *buffer = mlt_pool_alloc( size );
391                 memcpy( *buffer, image, size );
392
393                 // Set this on the frame properties
394                 mlt_properties_set_data( frame_properties, "image", *buffer, size, ( mlt_destructor )mlt_pool_release, NULL );
395         }
396         else
397         {
398                 int ret = 0;
399                 int got_picture = 0;
400                 AVFrame frame;
401
402                 memset( &pkt, 0, sizeof( pkt ) );
403                 memset( &frame, 0, sizeof( frame ) );
404
405                 while( ret >= 0 && !got_picture )
406                 {
407                         // Read a packet
408                         ret = av_read_frame( context, &pkt );
409
410                         // We only deal with video from the selected video_index
411                         if ( ret >= 0 && pkt.stream_index == index && pkt.size > 0 )
412                         {
413                                 // Decode the image
414                                 ret = avcodec_decode_video( codec_context, &frame, &got_picture, pkt.data, pkt.size );
415
416                                 if ( got_picture )
417                                 {
418                                         if ( pkt.pts != AV_NOPTS_VALUE && pkt.pts != 0  )
419                                                 current_time = ( double )pkt.pts / 1000000.0;
420                                         else
421                                                 current_time = real_timecode;
422
423                                         // Handle ignore
424                                         if ( current_time < real_timecode )
425                                         {
426                                                 ignore = 0;
427                                                 got_picture = 0;
428                                         }
429                                         else if ( current_time >= real_timecode )
430                                         {
431                                                 //current_time = real_timecode;
432                                                 ignore = 0;
433                                         }
434                                         else if ( ignore -- )
435                                         {
436                                                 got_picture = 0;
437                                         }
438                                 }
439                         }
440
441                         // We're finished with this packet regardless
442                         av_free_packet( &pkt );
443                 }
444
445                 // Now handle the picture if we have one
446                 if ( got_picture )
447                 {
448                         // Get current image and size
449                         int size = 0;
450                         uint8_t *image = mlt_properties_get_data( properties, "current_image", &size );
451
452                         if ( image == NULL || size != *width * *height * 2 )
453                         {
454                                 size = *width * ( *height + 1 ) * 2;
455                                 image = mlt_pool_alloc( size );
456                                 mlt_properties_set_data( properties, "current_image", image, size, ( mlt_destructor )mlt_pool_release, NULL );
457                         }
458
459                         *buffer = mlt_pool_alloc( size );
460
461                         // EXPERIMENTAL IMAGE NORMALISATIONS
462                         if ( codec_context->pix_fmt == PIX_FMT_YUV420P )
463                         {
464                                 register int i, j;
465                                 register int half = *width >> 1;
466                                 register uint8_t *Y = ( ( AVPicture * )&frame )->data[ 0 ];
467                                 register uint8_t *U = ( ( AVPicture * )&frame )->data[ 1 ];
468                                 register uint8_t *V = ( ( AVPicture * )&frame )->data[ 2 ];
469                                 register uint8_t *d = *buffer;
470                                 register uint8_t *y, *u, *v;
471
472                                 i = *height >> 1;
473                                 while ( i -- )
474                                 {
475                                         y = Y;
476                                         u = U;
477                                         v = V;
478                                         j = half;
479                                         while ( j -- )
480                                         {
481                                                 *d ++ = *y ++;
482                                                 *d ++ = *u ++;
483                                                 *d ++ = *y ++;
484                                                 *d ++ = *v ++;
485                                         }
486
487                                         Y += ( ( AVPicture * )&frame )->linesize[ 0 ];
488                                         y = Y;
489                                         u = U;
490                                         v = V;
491                                         j = half;
492                                         while ( j -- )
493                                         {
494                                                 *d ++ = *y ++;
495                                                 *d ++ = *u ++;
496                                                 *d ++ = *y ++;
497                                                 *d ++ = *v ++;
498                                         }
499
500                                         Y += ( ( AVPicture * )&frame )->linesize[ 0 ];
501                                         U += ( ( AVPicture * )&frame )->linesize[ 1 ];
502                                         V += ( ( AVPicture * )&frame )->linesize[ 2 ];
503                                 }
504                         }
505                         else
506                         {
507                                 img_convert( output, PIX_FMT_YUV422, (AVPicture *)&frame, codec_context->pix_fmt, *width, *height );
508                                 memcpy( *buffer, output->data[ 0 ], size );
509                         }
510
511                         memcpy( image, *buffer, size );
512                         mlt_properties_set_data( frame_properties, "image", *buffer, size, ( mlt_destructor )mlt_pool_release, NULL );
513
514                         if ( current_time == 0 && source_fps != 0 )
515                         {
516                                 double fps = mlt_properties_get_double( properties, "fps" );
517                                 current_time = ceil( source_fps * ( double )position / fps ) * ( 1 / source_fps );
518                                 mlt_properties_set_double( properties, "current_time", current_time );
519                         }
520                         else
521                         {
522                                 mlt_properties_set_double( properties, "current_time", current_time );
523                         }
524                 }
525         }
526
527         // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
528         mlt_properties_set_position( properties, "video_expected", position + 1 );
529
530         // Unlock the mutex now
531         pthread_mutex_unlock( &avformat_mutex );
532
533         return 0;
534 }
535
536 /** Set up video handling.
537 */
538
539 static void producer_set_up_video( mlt_producer this, mlt_frame frame )
540 {
541         // Get the properties
542         mlt_properties properties = mlt_producer_properties( this );
543
544         // Fetch the video_context
545         AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
546
547         // Get the video_index
548         int index = mlt_properties_get_int( properties, "video_index" );
549
550         // Get the frame properties
551         mlt_properties frame_properties = mlt_frame_properties( frame );
552
553         // Lock the mutex now
554         pthread_mutex_lock( &avformat_mutex );
555
556         if ( context != NULL && index != -1 )
557         {
558                 // Get the video stream
559                 AVStream *stream = context->streams[ index ];
560
561                 // Get codec context
562                 AVCodecContext *codec_context = &stream->codec;
563
564                 // Get the codec
565                 AVCodec *codec = mlt_properties_get_data( properties, "video_codec", NULL );
566
567                 // Initialise the codec if necessary
568                 if ( codec == NULL )
569                 {
570                         // Find the codec
571                         codec = avcodec_find_decoder( codec_context->codec_id );
572
573                         // If we don't have a codec and we can't initialise it, we can't do much more...
574                         if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
575                         {
576                                 // Now store the codec with its destructor
577                                 mlt_properties_set_data( properties, "video_codec", codec_context, 0, producer_codec_close, NULL );
578                         }
579                         else
580                         {
581                                 // Remember that we can't use this later
582                                 mlt_properties_set_int( properties, "video_index", -1 );
583                         }
584                 }
585
586                 // No codec, no show...
587                 if ( codec != NULL )
588                 {
589                         double aspect_ratio = 1;
590                         double source_fps = 0;
591
592                         // Set aspect ratio
593                         if ( codec_context->sample_aspect_ratio.num > 0 )
594                                 aspect_ratio = av_q2d( codec_context->sample_aspect_ratio );
595
596                         mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
597                         //fprintf( stderr, "AVFORMAT: sample aspect %f %dx%d\n", av_q2d( codec_context->sample_aspect_ratio ), codec_context->width, codec_context->height );
598
599                         // Determine the fps
600                         source_fps = ( double )codec_context->frame_rate / codec_context->frame_rate_base;
601
602                         // We'll use fps if it's available
603                         if ( source_fps > 0 && source_fps < 30 )
604                                 mlt_properties_set_double( properties, "source_fps", source_fps );
605                         
606                         // Set the width and height
607                         mlt_properties_set_int( frame_properties, "width", codec_context->width );
608                         mlt_properties_set_int( frame_properties, "height", codec_context->height );
609
610                         mlt_frame_push_get_image( frame, producer_get_image );
611                         mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
612                 }
613                 else
614                 {
615                         mlt_properties_set_int( frame_properties, "test_image", 1 );
616                 }
617         }
618         else
619         {
620                 mlt_properties_set_int( frame_properties, "test_image", 1 );
621         }
622
623         // Unlock the mutex now
624         pthread_mutex_unlock( &avformat_mutex );
625 }
626
627 /** Get the audio from a frame.
628 */
629
630 static int producer_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
631 {
632         // Get the properties from the frame
633         mlt_properties frame_properties = mlt_frame_properties( frame );
634
635         // Obtain the frame number of this frame
636         mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
637
638         // Get the producer 
639         mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
640
641         // Get the producer properties
642         mlt_properties properties = mlt_producer_properties( this );
643
644         // Fetch the audio_context
645         AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
646
647         // Get the audio_index
648         int index = mlt_properties_get_int( properties, "audio_index" );
649
650         // Obtain the expected frame numer
651         mlt_position expected = mlt_properties_get_position( properties, "audio_expected" );
652
653         // Obtain the resample context if it exists (not always needed)
654         ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
655
656         // Obtain the audio buffer
657         int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
658
659         // Get amount of audio used
660         int audio_used =  mlt_properties_get_int( properties, "audio_used" );
661
662         // Calculate the real time code
663         double real_timecode = producer_time_of_frame( this, position );
664
665         // Get the audio stream
666         AVStream *stream = context->streams[ index ];
667
668         // Get codec context
669         AVCodecContext *codec_context = &stream->codec;
670
671         // Packet
672         AVPacket pkt;
673
674         // Number of frames to ignore (for ffwd)
675         int ignore = 0;
676
677         // Flag for paused (silence) 
678         int paused = 0;
679         int locked = 0;
680
681         // Lock the mutex now
682         pthread_mutex_lock( &avformat_mutex );
683
684         // Check for resample and create if necessary
685         if ( resample == NULL )
686         {
687                 // Create the resampler
688                 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
689
690                 // And store it on properties
691                 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
692         }
693
694         // Check for audio buffer and create if necessary
695         if ( audio_buffer == NULL )
696         {
697                 // Allocate the audio buffer
698                 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
699
700                 // And store it on properties for reuse
701                 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
702         }
703
704         // Seek if necessary
705         if ( position != expected )
706         {
707                 if ( position + 1 == expected )
708                 {
709                         // We're paused - silence required
710                         paused = 1;
711                 }
712                 else if ( position > expected && ( position - expected ) < 250 )
713                 {
714                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
715                         ignore = position - expected;
716                 }
717                 else
718                 {
719                         // Set to the real timecode
720                         av_seek_frame( context, -1, real_timecode * 1000000.0 );
721
722                         // Clear the usage in the audio buffer
723                         audio_used = 0;
724
725                         locked = 1;
726                 }
727         }
728
729         // Get the audio if required
730         if ( !paused )
731         {
732                 int ret = 0;
733                 int got_audio = 0;
734                 int16_t *temp = mlt_pool_alloc( sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE );
735
736                 memset( &pkt, 0, sizeof( pkt ) );
737
738                 while( ret >= 0 && !got_audio )
739                 {
740                         // Check if the buffer already contains the samples required
741                         if ( audio_used >= *samples && ignore == 0 )
742                         {
743                                 got_audio = 1;
744                                 break;
745                         }
746
747                         // Read a packet
748                         ret = av_read_frame( context, &pkt );
749
750                 int len = pkt.size;
751                 uint8_t *ptr = pkt.data;
752                         int data_size;
753
754                         // We only deal with video from the selected video_index
755                         while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
756                         {
757                                 // Decode the audio
758                                 ret = avcodec_decode_audio( codec_context, temp, &data_size, ptr, len );
759
760                                 if ( ret < 0 )
761                                 {
762                                         ret = 0;
763                                         break;
764                                 }
765
766                                 len -= ret;
767                                 ptr += ret;
768
769                                 if ( data_size > 0 )
770                                 {
771                                         int size_out = audio_resample( resample, &audio_buffer[ audio_used * *channels ], temp, data_size / ( codec_context->channels * sizeof( int16_t ) ) );
772
773                                         audio_used += size_out;
774
775                                         // Handle ignore
776                                         while ( ignore && audio_used > *samples )
777                                         {
778                                                 ignore --;
779                                                 audio_used -= *samples;
780                                                 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
781                                         }
782                                 }
783
784                                 // If we're behind, ignore this packet
785                                 float current_pts = (float)pkt.pts / 1000000.0;
786                                 double discrepancy = mlt_properties_get_double( properties, "discrepancy" );
787                                 if ( current_pts != 0 && real_timecode != 0 )
788                                 {
789                                         if ( discrepancy != 1 )
790                                                 discrepancy = ( discrepancy + ( real_timecode / current_pts ) ) / 2;
791                                         else
792                                                 discrepancy = real_timecode / current_pts;
793                                         if ( discrepancy > 0.9 && discrepancy < 1.1 )
794                                                 discrepancy = 1.0;
795                                         else
796                                                 discrepancy = floor( discrepancy + 0.5 );
797
798                                         if ( discrepancy == 0 )
799                                                 discrepancy = 1.0;
800
801                                         mlt_properties_set_double( properties, "discrepancy", discrepancy );
802                                 }
803
804                                 if ( !ignore && discrepancy * current_pts <= ( real_timecode - 0.02 ) )
805                                         ignore = 1;
806                         }
807
808                         // We're finished with this packet regardless
809                         av_free_packet( &pkt );
810                 }
811
812                 *buffer = mlt_pool_alloc( *samples * *channels * sizeof( int16_t ) );
813                 mlt_properties_set_data( frame_properties, "audio", *buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
814
815                 // Now handle the audio if we have enough
816                 if ( audio_used >= *samples )
817                 {
818                         memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
819                         audio_used -= *samples;
820                         memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
821                 }
822                 else
823                 {
824                         memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
825                 }
826                 
827                 // Store the number of audio samples still available
828                 mlt_properties_set_int( properties, "audio_used", audio_used );
829
830                 // Release the temporary audio
831                 mlt_pool_release( temp );
832         }
833         else
834         {
835                 // Get silence and don't touch the context
836                 frame->get_audio = NULL;
837                 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
838         }
839
840         // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
841         mlt_properties_set_position( properties, "audio_expected", position + 1 );
842
843         // Unlock the mutex now
844         pthread_mutex_unlock( &avformat_mutex );
845
846         return 0;
847 }
848
849 /** Set up audio handling.
850 */
851
852 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
853 {
854         // Get the properties
855         mlt_properties properties = mlt_producer_properties( this );
856
857         // Fetch the audio_context
858         AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
859
860         // Get the audio_index
861         int index = mlt_properties_get_int( properties, "audio_index" );
862
863         // Lock the mutex now
864         pthread_mutex_lock( &avformat_mutex );
865
866         // Deal with audio context
867         if ( context != NULL && index != -1 )
868         {
869                 // Get the frame properties
870                 mlt_properties frame_properties = mlt_frame_properties( frame );
871
872                 // Get the audio stream
873                 AVStream *stream = context->streams[ index ];
874
875                 // Get codec context
876                 AVCodecContext *codec_context = &stream->codec;
877
878                 // Get the codec
879                 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
880
881                 // Initialise the codec if necessary
882                 if ( codec == NULL )
883                 {
884                         // Find the codec
885                         codec = avcodec_find_decoder( codec_context->codec_id );
886
887                         // If we don't have a codec and we can't initialise it, we can't do much more...
888                         if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
889                         {
890                                 // Now store the codec with its destructor
891                                 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
892
893                         }
894                         else
895                         {
896                                 // Remember that we can't use this later
897                                 mlt_properties_set_int( properties, "audio_index", -1 );
898                         }
899                 }
900
901                 // No codec, no show...
902                 if ( codec != NULL )
903                 {
904                         frame->get_audio = producer_get_audio;
905                         mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
906                 }
907         }
908
909         // Unlock the mutex now
910         pthread_mutex_unlock( &avformat_mutex );
911 }
912
913 /** Our get frame implementation.
914 */
915
916 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
917 {
918         // Create an empty frame
919         *frame = mlt_frame_init( );
920
921         // Update timecode on the frame we're creating
922         mlt_frame_set_position( *frame, mlt_producer_position( this ) );
923
924         // Set the position of this producer
925         mlt_properties_set_position( mlt_frame_properties( *frame ), "avformat_position", mlt_producer_get_in( this ) + mlt_producer_position( this ) );
926
927         // Set up the video
928         producer_set_up_video( this, *frame );
929
930         // Set up the audio
931         producer_set_up_audio( this, *frame );
932
933         // Set the aspect_ratio
934         mlt_properties_set_double( mlt_frame_properties( *frame ), "aspect_ratio", mlt_properties_get_double( mlt_producer_properties( this ), "aspect_ratio" ) );
935
936         // Calculate the next timecode
937         mlt_producer_prepare_next( this );
938
939         return 0;
940 }