]> git.sesse.net Git - mlt/blob - src/modules/avformat/producer_avformat.c
src/framework/mlt_frame.c
[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 <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 void avformat_lock( );
37 void avformat_unlock( );
38
39 // Forward references.
40 static int producer_open( mlt_producer this, char *file );
41 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
42
43 /** Constructor for libavformat.
44 */
45
46 mlt_producer producer_avformat_init( char *file )
47 {
48         mlt_producer this = NULL;
49
50         // Check that we have a non-NULL argument
51         if ( file != NULL )
52         {
53                 // Construct the producer
54                 this = calloc( 1, sizeof( struct mlt_producer_s ) );
55
56                 // Initialise it
57                 if ( mlt_producer_init( this, NULL ) == 0 )
58                 {
59                         // Get the properties
60                         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
61
62                         // Set the resource property (required for all producers)
63                         mlt_properties_set( properties, "resource", file );
64
65                         // Register our get_frame implementation
66                         this->get_frame = producer_get_frame;
67
68                         // Open the file
69                         if ( producer_open( this, file ) != 0 )
70                         {
71                                 // Clean up
72                                 mlt_producer_close( this );
73                                 this = NULL;
74                         }
75                 }
76         }
77
78         return this;
79 }
80
81 /** Find the default streams.
82 */
83
84 static void find_default_streams( AVFormatContext *context, int *audio_index, int *video_index )
85 {
86         int i;
87
88         // Allow for multiple audio and video streams in the file and select first of each (if available)
89         for( i = 0; i < context->nb_streams; i++ ) 
90         {
91                 // Get the codec context
92                 AVCodecContext *codec_context = context->streams[ i ]->codec;
93
94                 // Determine the type and obtain the first index of each type
95                 switch( codec_context->codec_type ) 
96                 {
97                         case CODEC_TYPE_VIDEO:
98                                 if ( *video_index < 0 )
99                                         *video_index = i;
100                                 break;
101                         case CODEC_TYPE_AUDIO:
102                                 if ( *audio_index < 0 )
103                                         *audio_index = i;
104                                 break;
105                         default:
106                                 break;
107                 }
108         }
109 }
110
111 /** Producer file destructor.
112 */
113
114 static void producer_file_close( void *context )
115 {
116         if ( context != NULL )
117         {
118                 // Lock the mutex now
119                 avformat_lock( );
120
121                 // Close the file
122                 av_close_input_file( context );
123
124                 // Unlock the mutex now
125                 avformat_unlock( );
126         }
127 }
128
129 /** Producer file destructor.
130 */
131
132 static void producer_codec_close( void *codec )
133 {
134         if ( codec != NULL )
135         {
136                 // Lock the mutex now
137                 avformat_lock( );
138
139                 // Close the file
140                 avcodec_close( codec );
141
142                 // Unlock the mutex now
143                 avformat_unlock( );
144         }
145 }
146
147 /** Open the file.
148 */
149
150 static int producer_open( mlt_producer this, char *file )
151 {
152         // Return an error code (0 == no error)
153         int error = 0;
154
155         // Context for avformat
156         AVFormatContext *context = NULL;
157
158         // Get the properties
159         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
160
161         // We will treat everything with the producer fps
162         double fps = mlt_properties_get_double( properties, "fps" );
163
164         // Lock the mutex now
165         avformat_lock( );
166         
167         // If "MRL", then create AVInputFormat
168         AVInputFormat *format = NULL;
169         AVFormatParameters *params = NULL;
170         char *standard = NULL;
171         char *mrl = strchr( file, ':' );
172
173         // AV option (0 = both, 1 = video, 2 = audio)
174         int av = 0;
175         
176         // Setting lowest log level
177         av_log_set_level( -1 );
178
179         // Only if there is not a protocol specification that avformat can handle
180         if ( mrl && !url_exist( file ) )
181         {
182                 // 'file' becomes format abbreviation
183                 mrl[0] = 0;
184         
185                 // Lookup the format
186                 format = av_find_input_format( file );
187                 
188                 // Eat the format designator
189                 file = ++mrl;
190                 
191                 if ( format )
192                 {
193                         // Allocate params
194                         params = calloc( sizeof( AVFormatParameters ), 1 );
195                         
196                         // These are required by video4linux (defaults)
197                         params->width = 640;
198                         params->height = 480;
199                         params->time_base= (AVRational){1,25};
200                         params->device = file;
201                         params->channels = 2;
202                         params->sample_rate = 48000;
203                 }
204                 
205                 // Parse out params
206                 mrl = strchr( file, '?' );
207                 while ( mrl )
208                 {
209                         mrl[0] = 0;
210                         char *name = strdup( ++mrl );
211                         char *value = strchr( name, ':' );
212                         if ( value )
213                         {
214                                 value[0] = 0;
215                                 value++;
216                                 char *t = strchr( value, '&' );
217                                 if ( t )
218                                         t[0] = 0;
219                                 if ( !strcmp( name, "frame_rate" ) )
220                                         params->time_base.den = atoi( value );
221                                 else if ( !strcmp( name, "frame_rate_base" ) )
222                                         params->time_base.num = atoi( value );
223                                 else if ( !strcmp( name, "sample_rate" ) )
224                                         params->sample_rate = atoi( value );
225                                 else if ( !strcmp( name, "channels" ) )
226                                         params->channels = atoi( value );
227                                 else if ( !strcmp( name, "width" ) )
228                                         params->width = atoi( value );
229                                 else if ( !strcmp( name, "height" ) )
230                                         params->height = atoi( value );
231                                 else if ( !strcmp( name, "standard" ) )
232                                 {
233                                         standard = strdup( value );
234                                         params->standard = standard;
235                                 }
236                                 else if ( !strcmp( name, "av" ) )
237                                         av = atoi( value );
238                         }
239                         free( name );
240                         mrl = strchr( mrl, '&' );
241                 }
242         }
243
244         // Now attempt to open the file
245         error = av_open_input_file( &context, file, format, 0, params );
246         error = error < 0;
247         
248         // Cleanup AVFormatParameters
249         free( standard );
250         free( params );
251
252         // If successful, then try to get additional info
253         if ( error == 0 )
254         {
255                 // Get the stream info
256                 error = av_find_stream_info( context ) < 0;
257
258                 // Continue if no error
259                 if ( error == 0 )
260                 {
261                         // We will default to the first audio and video streams found
262                         int audio_index = -1;
263                         int video_index = -1;
264                         int av_bypass = 0;
265
266                         // Now set properties where we can (use default unknowns if required)
267                         if ( context->duration != AV_NOPTS_VALUE ) 
268                         {
269                                 // This isn't going to be accurate for all formats
270                                 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps );
271                                 mlt_properties_set_position( properties, "out", frames - 2 );
272                                 mlt_properties_set_position( properties, "length", frames - 1 );
273                         }
274
275                         // Find default audio and video streams
276                         find_default_streams( context, &audio_index, &video_index );
277
278             if ( context->start_time != AV_NOPTS_VALUE )
279                 mlt_properties_set_double( properties, "_start_time", context->start_time );
280                         
281                         // Check if we're seekable (something funny about mpeg here :-/)
282                         if ( strcmp( file, "pipe:" ) && strncmp( file, "http://", 6 ) )
283                                 mlt_properties_set_int( properties, "seekable", av_seek_frame( context, -1, mlt_properties_get_double( properties, "_start_time" ), AVSEEK_FLAG_BACKWARD ) >= 0 );
284                         else
285                                 av_bypass = 1;
286
287                         // Store selected audio and video indexes on properties
288                         mlt_properties_set_int( properties, "audio_index", audio_index );
289                         mlt_properties_set_int( properties, "video_index", video_index );
290                         
291                         // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
292                         if ( av == 0 && !av_bypass && audio_index != -1 && video_index != -1 )
293                         {
294                                 // We'll use the open one as our video_context
295                                 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
296
297                                 // And open again for our audio context
298                                 av_open_input_file( &context, file, NULL, 0, NULL );
299                                 av_find_stream_info( context );
300
301                                 // Audio context
302                                 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
303                         }
304                         else if ( av != 2 && video_index != -1 )
305                         {
306                                 // We only have a video context
307                                 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
308                         }
309                         else if ( audio_index != -1 )
310                         {
311                                 // We only have an audio context
312                                 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
313                         }
314                         else
315                         {
316                                 // Something has gone wrong
317                                 error = -1;
318                         }
319
320                         mlt_properties_set_int( properties, "av_bypass", av_bypass );
321                 }
322         }
323
324         // Unlock the mutex now
325         avformat_unlock( );
326
327         return error;
328 }
329
330 /** Convert a frame position to a time code.
331 */
332
333 static double producer_time_of_frame( mlt_producer this, mlt_position position )
334 {
335         // Get the properties
336         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
337
338         // Obtain the fps
339         double fps = mlt_properties_get_double( properties, "fps" );
340
341         // Do the calc
342         return ( double )position / fps;
343 }
344
345 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format format, int width, int height )
346 {
347         // EXPERIMENTAL IMAGE NORMALISATIONS
348         if ( pix_fmt == PIX_FMT_YUV420P && format == mlt_image_yuv422 )
349         {
350                 register int i, j;
351                 register int half = width >> 1;
352                 register uint8_t *Y = ( ( AVPicture * )frame )->data[ 0 ];
353                 register uint8_t *U = ( ( AVPicture * )frame )->data[ 1 ];
354                 register uint8_t *V = ( ( AVPicture * )frame )->data[ 2 ];
355                 register uint8_t *d = buffer;
356                 register uint8_t *y, *u, *v;
357
358                 i = height >> 1;
359                 while ( i -- )
360                 {
361                         y = Y;
362                         u = U;
363                         v = V;
364                         j = half;
365                         while ( j -- )
366                         {
367                                 *d ++ = *y ++;
368                                 *d ++ = *u ++;
369                                 *d ++ = *y ++;
370                                 *d ++ = *v ++;
371                         }
372
373                         Y += ( ( AVPicture * )frame )->linesize[ 0 ];
374                         y = Y;
375                         u = U;
376                         v = V;
377                         j = half;
378                         while ( j -- )
379                         {
380                                 *d ++ = *y ++;
381                                 *d ++ = *u ++;
382                                 *d ++ = *y ++;
383                                 *d ++ = *v ++;
384                         }
385
386                         Y += ( ( AVPicture * )frame )->linesize[ 0 ];
387                         U += ( ( AVPicture * )frame )->linesize[ 1 ];
388                         V += ( ( AVPicture * )frame )->linesize[ 2 ];
389                 }
390         }
391         else if ( format == mlt_image_yuv420p )
392         {
393                 AVPicture pict;
394                 pict.data[0] = buffer;
395                 pict.data[1] = buffer + width * height;
396                 pict.data[2] = buffer + ( 3 * width * height ) / 2;
397                 pict.linesize[0] = width;
398                 pict.linesize[1] = width >> 1;
399                 pict.linesize[2] = width >> 1;
400                 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
401         }
402         else if ( format == mlt_image_rgb24 )
403         {
404                 AVPicture output;
405                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
406                 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
407         }
408         else
409         {
410                 AVPicture output;
411                 avpicture_fill( &output, buffer, PIX_FMT_YUV422, width, height );
412                 img_convert( &output, PIX_FMT_YUV422, (AVPicture *)frame, pix_fmt, width, height );
413         }
414 }
415
416 /** Get an image from a frame.
417 */
418
419 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
420 {
421         // Get the properties from the frame
422         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
423
424         // Obtain the frame number of this frame
425         mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
426
427         // Get the producer 
428         mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
429
430         // Get the producer properties
431         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
432
433         // Fetch the video_context
434         AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
435
436         // Get the video_index
437         int index = mlt_properties_get_int( properties, "video_index" );
438
439         // Obtain the expected frame numer
440         mlt_position expected = mlt_properties_get_position( properties, "_video_expected" );
441
442         // Calculate the real time code
443         double real_timecode = producer_time_of_frame( this, position );
444
445         // Get the video stream
446         AVStream *stream = context->streams[ index ];
447
448         // Get codec context
449         AVCodecContext *codec_context = stream->codec;
450
451         // Packet
452         AVPacket pkt;
453
454         // Get the conversion frame
455         AVFrame *av_frame = mlt_properties_get_data( properties, "av_frame", NULL );
456
457         // Special case pause handling flag
458         int paused = 0;
459
460         // Special case ffwd handling
461         int ignore = 0;
462
463         // Current time calcs
464         double current_time = mlt_properties_get_double( properties, "_current_time" );
465
466         // We may want to use the source fps if available
467         double source_fps = mlt_properties_get_double( properties, "source_fps" );
468
469         // Get the seekable status
470         int seekable = mlt_properties_get_int( properties, "seekable" );
471
472         // Generate the size in bytes
473         int size = 0; 
474
475         // Hopefully provide better support for streams...
476         int av_bypass = mlt_properties_get_int( properties, "av_bypass" );
477
478         // Set the result arguments that we know here (only *buffer is now required)
479         *width = codec_context->width;
480         *height = codec_context->height;
481
482         switch ( *format )
483         {
484                 case mlt_image_yuv420p:
485                         size = *width * 3 * ( *height + 1 ) / 2;
486                         break;
487                 case mlt_image_rgb24:
488                         size = *width * ( *height + 1 ) * 3;
489                         break;
490                 default:
491                         *format = mlt_image_yuv422;
492                         size = *width * ( *height + 1 ) * 2;
493                         break;
494         }
495
496         // Set this on the frame properties
497         mlt_properties_set_int( frame_properties, "width", *width );
498         mlt_properties_set_int( frame_properties, "height", *height );
499
500         // Construct the output image
501         *buffer = mlt_pool_alloc( size );
502
503         // Seek if necessary
504         if ( position != expected )
505         {
506                 if ( position + 1 == expected )
507                 {
508                         // We're paused - use last image
509                         paused = 1;
510                 }
511                 else if ( !seekable && position > expected && ( position - expected ) < 250 )
512                 {
513                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
514                         ignore = position - expected;
515                 }
516                 else if ( seekable && ( position < expected || position - expected >= 12 ) )
517                 {
518                         // Set to the real timecode
519                         av_seek_frame( context, -1, mlt_properties_get_double( properties, "_start_time" ) + real_timecode * 1000000.0, AVSEEK_FLAG_BACKWARD );
520         
521                         // Remove the cached info relating to the previous position
522                         mlt_properties_set_double( properties, "_current_time", real_timecode );
523
524                         mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
525                         av_frame = NULL;
526                 }
527         }
528         
529         // Duplicate the last image if necessary
530         if ( av_frame != NULL && ( paused || mlt_properties_get_double( properties, "_current_time" ) >= real_timecode ) &&
531                  av_bypass == 0 )
532         {
533                 // Duplicate it
534                 convert_image( av_frame, *buffer, codec_context->pix_fmt, *format, *width, *height );
535
536                 // Set this on the frame properties
537                 mlt_properties_set_data( frame_properties, "image", *buffer, size, ( mlt_destructor )mlt_pool_release, NULL );
538         }
539         else
540         {
541                 int ret = 0;
542                 int got_picture = 0;
543                 int must_decode = 1;
544
545                 // Temporary hack to improve intra frame only
546                 if ( !strcmp( codec_context->codec->name, "mjpeg" ) )
547                         must_decode = 0;
548
549                 memset( &pkt, 0, sizeof( pkt ) );
550
551                 // Construct an AVFrame for YUV422 conversion
552                 if ( av_frame == NULL )
553                 {
554                         av_frame = calloc( 1, sizeof( AVFrame ) );
555                         mlt_properties_set_data( properties, "av_frame", av_frame, 0, free, NULL );
556                 }
557
558                 while( ret >= 0 && !got_picture )
559                 {
560                         // Read a packet
561                         ret = av_read_frame( context, &pkt );
562
563                         // We only deal with video from the selected video_index
564                         if ( ret >= 0 && pkt.stream_index == index && pkt.size > 0 )
565                         {
566                                 // Determine time code of the packet
567                                 if ( pkt.dts != AV_NOPTS_VALUE )
568                                         current_time = av_q2d( stream->time_base ) * pkt.dts;
569                                 else
570                                         current_time = real_timecode;
571
572                                 // Decode the image
573                                 if ( must_decode || current_time >= real_timecode )
574                                         ret = avcodec_decode_video( codec_context, av_frame, &got_picture, pkt.data, pkt.size );
575
576                                 if ( got_picture )
577                                 {
578                                         // Handle ignore
579                                         if ( ( int )( current_time * 100 ) < ( int )( real_timecode * 100 ) - 7 )
580                                         {
581                                                 ignore = 0;
582                                                 got_picture = 0;
583                                         }
584                                         else if ( current_time >= real_timecode )
585                                         {
586                                                 ignore = 0;
587                                         }
588                                         else if ( ignore -- )
589                                         {
590                                                 got_picture = 0;
591                                         }
592                                         mlt_properties_set_int( properties, "top_field_first", av_frame->top_field_first );
593                                 }
594                         }
595
596                         // We're finished with this packet regardless
597                         av_free_packet( &pkt );
598                 }
599
600                 // Now handle the picture if we have one
601                 if ( got_picture )
602                 {
603                         convert_image( av_frame, *buffer, codec_context->pix_fmt, *format, *width, *height );
604
605                         mlt_properties_set_data( frame_properties, "image", *buffer, size, (mlt_destructor)mlt_pool_release, NULL );
606
607                         if ( current_time == 0 && source_fps != 0 )
608                         {
609                                 double fps = mlt_properties_get_double( properties, "fps" );
610                                 current_time = ceil( source_fps * ( double )position / fps ) * ( 1 / source_fps );
611                                 mlt_properties_set_double( properties, "_current_time", current_time );
612                         }
613                         else
614                         {
615                                 mlt_properties_set_double( properties, "_current_time", current_time );
616                         }
617                 }
618         }
619         
620         // Set the field order property for this frame
621         mlt_properties_set_int( frame_properties, "top_field_first", 
622                 mlt_properties_get_int( properties, "top_field_first" ) );
623
624         // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
625         mlt_properties_set_position( properties, "_video_expected", position + 1 );
626
627         return 0;
628 }
629
630 /** Set up video handling.
631 */
632
633 static void producer_set_up_video( mlt_producer this, mlt_frame frame )
634 {
635         // Get the properties
636         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
637
638         // Fetch the video_context
639         AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
640
641         // Get the video_index
642         int index = mlt_properties_get_int( properties, "video_index" );
643
644         // Get the frame properties
645         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
646
647         if ( context != NULL && index != -1 )
648         {
649                 // Get the video stream
650                 AVStream *stream = context->streams[ index ];
651
652                 // Get codec context
653                 AVCodecContext *codec_context = stream->codec;
654
655                 // Get the codec
656                 AVCodec *codec = mlt_properties_get_data( properties, "video_codec", NULL );
657
658                 // Initialise the codec if necessary
659                 if ( codec == NULL )
660                 {
661                         // Find the codec
662                         codec = avcodec_find_decoder( codec_context->codec_id );
663
664                         // If we don't have a codec and we can't initialise it, we can't do much more...
665                         if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
666                         {
667                                 // Now store the codec with its destructor
668                                 mlt_properties_set_data( properties, "video_codec", codec_context, 0, producer_codec_close, NULL );
669                         }
670                         else
671                         {
672                                 // Remember that we can't use this later
673                                 mlt_properties_set_int( properties, "video_index", -1 );
674                         }
675                 }
676
677                 // No codec, no show...
678                 if ( codec != NULL )
679                 {
680                         double source_fps = 0;
681                         int norm_aspect_ratio = mlt_properties_get_int( properties, "norm_aspect_ratio" );
682                         double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
683                         double aspect_ratio;
684
685                         // XXX: We won't know the real aspect ratio until an image is decoded
686                         // but we do need it now (to satisfy filter_resize) - take a guess based
687                         // on pal/ntsc
688                         if ( force_aspect_ratio > 0.0 )
689                         {
690                                 aspect_ratio = force_aspect_ratio;
691                         }
692                         else if ( !norm_aspect_ratio && codec_context->sample_aspect_ratio.num > 0 )
693                         {
694                                 aspect_ratio = av_q2d( codec_context->sample_aspect_ratio );
695                         }
696                         else
697                         {
698                                 int is_pal = mlt_properties_get_double( properties, "fps" ) == 25.0;
699                                 aspect_ratio = is_pal ? 59.0/54.0 : 10.0/11.0;
700                         }
701
702                         // Determine the fps
703                         source_fps = ( double )codec_context->time_base.den / ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num );
704
705                         // We'll use fps if it's available
706                         if ( source_fps > 0 && source_fps < 30 )
707                                 mlt_properties_set_double( properties, "source_fps", source_fps );
708                         mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
709                         
710                         // Set the width and height
711                         mlt_properties_set_int( frame_properties, "width", codec_context->width );
712                         mlt_properties_set_int( frame_properties, "height", codec_context->height );
713                         mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
714
715                         mlt_frame_push_get_image( frame, producer_get_image );
716                         mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
717                 }
718                 else
719                 {
720                         mlt_properties_set_int( frame_properties, "test_image", 1 );
721                 }
722         }
723         else
724         {
725                 mlt_properties_set_int( frame_properties, "test_image", 1 );
726         }
727 }
728
729 /** Get the audio from a frame.
730 */
731
732 static int producer_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
733 {
734         // Get the properties from the frame
735         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
736
737         // Obtain the frame number of this frame
738         mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
739
740         // Get the producer 
741         mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
742
743         // Get the producer properties
744         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
745
746         // Fetch the audio_context
747         AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
748
749         // Get the audio_index
750         int index = mlt_properties_get_int( properties, "audio_index" );
751
752         // Get the seekable status
753         int seekable = mlt_properties_get_int( properties, "seekable" );
754
755         // Obtain the expected frame numer
756         mlt_position expected = mlt_properties_get_position( properties, "_audio_expected" );
757
758         // Obtain the resample context if it exists (not always needed)
759         ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
760
761         // Obtain the audio buffer
762         int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
763
764         // Get amount of audio used
765         int audio_used =  mlt_properties_get_int( properties, "_audio_used" );
766
767         // Calculate the real time code
768         double real_timecode = producer_time_of_frame( this, position );
769
770         // Get the audio stream
771         AVStream *stream = context->streams[ index ];
772
773         // Get codec context
774         AVCodecContext *codec_context = stream->codec;
775
776         // Packet
777         AVPacket pkt;
778
779         // Number of frames to ignore (for ffwd)
780         int ignore = 0;
781
782         // Flag for paused (silence) 
783         int paused = 0;
784
785         // Check for resample and create if necessary
786         if ( resample == NULL && codec_context->channels <= 2 )
787         {
788                 // Create the resampler
789                 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
790
791                 // And store it on properties
792                 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
793         }
794         else if ( resample == NULL )
795         {
796                 *channels = codec_context->channels;
797                 *frequency = codec_context->sample_rate;
798         }
799
800         // Check for audio buffer and create if necessary
801         if ( audio_buffer == NULL )
802         {
803                 // Allocate the audio buffer
804                 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
805
806                 // And store it on properties for reuse
807                 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
808         }
809
810         // Seek if necessary
811         if ( position != expected )
812         {
813                 if ( position + 1 == expected )
814                 {
815                         // We're paused - silence required
816                         paused = 1;
817                 }
818                 else if ( !seekable && position > expected && ( position - expected ) < 250 )
819                 {
820                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
821                         ignore = position - expected;
822                 }
823                 else if ( position < expected || position - expected >= 12 )
824                 {
825                         // Set to the real timecode
826                         if ( av_seek_frame( context, -1, mlt_properties_get_double( properties, "_start_time" ) + real_timecode * 1000000.0, AVSEEK_FLAG_BACKWARD ) != 0 )
827                                 paused = 1;
828
829                         // Clear the usage in the audio buffer
830                         audio_used = 0;
831                 }
832         }
833
834         // Get the audio if required
835         if ( !paused )
836         {
837                 int ret = 0;
838                 int got_audio = 0;
839                 int16_t *temp = mlt_pool_alloc( sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE );
840
841                 memset( &pkt, 0, sizeof( pkt ) );
842
843                 while( ret >= 0 && !got_audio )
844                 {
845                         // Check if the buffer already contains the samples required
846                         if ( audio_used >= *samples && ignore == 0 )
847                         {
848                                 got_audio = 1;
849                                 break;
850                         }
851
852                         // Read a packet
853                         ret = av_read_frame( context, &pkt );
854
855                 int len = pkt.size;
856                 uint8_t *ptr = pkt.data;
857                         int data_size;
858
859                         // We only deal with audio from the selected audio_index
860                         while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
861                         {
862                                 // Decode the audio
863                                 ret = avcodec_decode_audio( codec_context, temp, &data_size, ptr, len );
864
865                                 if ( ret < 0 )
866                                 {
867                                         ret = 0;
868                                         break;
869                                 }
870
871                                 len -= ret;
872                                 ptr += ret;
873
874                                 if ( data_size > 0 )
875                                 {
876                                         if ( resample != NULL )
877                                         {
878                                                 audio_used += audio_resample( resample, &audio_buffer[ audio_used * *channels ], temp, data_size / ( codec_context->channels * sizeof( int16_t ) ) );
879                                         }
880                                         else
881                                         {
882                                                 memcpy( &audio_buffer[ audio_used * *channels ], temp, data_size );
883                                                 audio_used += data_size / ( codec_context->channels * sizeof( int16_t ) );
884                                         }
885
886                                         // Handle ignore
887                                         while ( ignore && audio_used > *samples )
888                                         {
889                                                 ignore --;
890                                                 audio_used -= *samples;
891                                                 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
892                                         }
893                                 }
894
895                                 // If we're behind, ignore this packet
896                                 float current_pts = av_q2d( stream->time_base ) * pkt.pts;
897                                 if ( seekable && ( !ignore && current_pts <= ( real_timecode - 0.02 ) ) )
898                                         ignore = 1;
899                         }
900
901                         // We're finished with this packet regardless
902                         av_free_packet( &pkt );
903                 }
904
905                 *buffer = mlt_pool_alloc( *samples * *channels * sizeof( int16_t ) );
906                 mlt_properties_set_data( frame_properties, "audio", *buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
907
908                 // Now handle the audio if we have enough
909                 if ( audio_used >= *samples )
910                 {
911                         memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
912                         audio_used -= *samples;
913                         memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
914                 }
915                 else
916                 {
917                         memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
918                 }
919                 
920                 // Store the number of audio samples still available
921                 mlt_properties_set_int( properties, "_audio_used", audio_used );
922
923                 // Release the temporary audio
924                 mlt_pool_release( temp );
925         }
926         else
927         {
928                 // Get silence and don't touch the context
929                 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
930         }
931
932         // Regardless of speed (other than paused), we expect to get the next frame
933         if ( !paused )
934                 mlt_properties_set_position( properties, "_audio_expected", position + 1 );
935
936         return 0;
937 }
938
939 /** Set up audio handling.
940 */
941
942 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
943 {
944         // Get the properties
945         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
946
947         // Fetch the audio_context
948         AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
949
950         // Get the audio_index
951         int index = mlt_properties_get_int( properties, "audio_index" );
952
953         // Deal with audio context
954         if ( context != NULL && index != -1 )
955         {
956                 // Get the frame properties
957                 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
958
959                 // Get the audio stream
960                 AVStream *stream = context->streams[ index ];
961
962                 // Get codec context
963                 AVCodecContext *codec_context = stream->codec;
964
965                 // Get the codec
966                 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
967
968                 // Initialise the codec if necessary
969                 if ( codec == NULL )
970                 {
971                         // Find the codec
972                         codec = avcodec_find_decoder( codec_context->codec_id );
973
974                         // If we don't have a codec and we can't initialise it, we can't do much more...
975                         if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
976                         {
977                                 // Now store the codec with its destructor
978                                 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
979
980                         }
981                         else
982                         {
983                                 // Remember that we can't use this later
984                                 mlt_properties_set_int( properties, "audio_index", -1 );
985                         }
986                 }
987
988                 // No codec, no show...
989                 if ( codec != NULL )
990                 {
991                         mlt_frame_push_audio( frame, producer_get_audio );
992                         mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
993                 }
994         }
995 }
996
997 /** Our get frame implementation.
998 */
999
1000 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
1001 {
1002         // Create an empty frame
1003         *frame = mlt_frame_init( );
1004
1005         // Update timecode on the frame we're creating
1006         mlt_frame_set_position( *frame, mlt_producer_position( this ) );
1007
1008         // Set the position of this producer
1009         mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( this ) );
1010
1011         // Set up the video
1012         producer_set_up_video( this, *frame );
1013
1014         // Set up the audio
1015         producer_set_up_audio( this, *frame );
1016
1017         // Set the aspect_ratio
1018         mlt_properties_set_double( MLT_FRAME_PROPERTIES( *frame ), "aspect_ratio", mlt_properties_get_double( MLT_PRODUCER_PROPERTIES( this ), "aspect_ratio" ) );
1019
1020         // Calculate the next timecode
1021         mlt_producer_prepare_next( this );
1022
1023         return 0;
1024 }