2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
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.
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.
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.
22 #include "producer_avformat.h"
25 #include <framework/mlt_frame.h>
27 // ffmpeg Header files
28 #include <ffmpeg/avformat.h>
30 // System header files
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 );
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;
44 /** Constructor for libavformat.
47 mlt_producer producer_avformat_init( char *file )
49 mlt_producer this = NULL;
51 // Check that we have a non-NULL argument
54 // Construct the producer
55 this = calloc( 1, sizeof( struct mlt_producer_s ) );
58 if ( mlt_producer_init( this, NULL ) == 0 )
61 mlt_properties properties = mlt_producer_properties( this );
63 // Set the resource property (required for all producers)
64 mlt_properties_set( properties, "resource", file );
66 // TEST: audio sync tweaking
67 mlt_properties_set_double( properties, "discrepancy", 1 );
69 // Register our get_frame implementation
70 this->get_frame = producer_get_frame;
72 // Initialise avformat if necessary
73 if ( avformat_initialised == 0 )
75 pthread_mutex_init( &avformat_mutex, NULL );
76 avformat_initialised = 1;
81 if ( producer_open( this, file ) != 0 )
84 mlt_producer_close( this );
93 /** Find the default streams.
96 static void find_default_streams( AVFormatContext *context, int *audio_index, int *video_index )
100 // Allow for multiple audio and video streams in the file and select first of each (if available)
101 for( i = 0; i < context->nb_streams; i++ )
103 // Get the codec context
104 AVCodecContext *codec_context = &context->streams[ i ]->codec;
106 // Determine the type and obtain the first index of each type
107 switch( codec_context->codec_type )
109 case CODEC_TYPE_VIDEO:
110 if ( *video_index < 0 )
113 case CODEC_TYPE_AUDIO:
114 if ( *audio_index < 0 )
123 /** Producer file destructor.
126 static void producer_file_close( void *context )
128 if ( context != NULL )
130 // Lock the mutex now
131 pthread_mutex_lock( &avformat_mutex );
134 av_close_input_file( context );
136 // Unlock the mutex now
137 pthread_mutex_unlock( &avformat_mutex );
141 /** Producer file destructor.
144 static void producer_codec_close( void *codec )
148 // Lock the mutex now
149 pthread_mutex_lock( &avformat_mutex );
152 avcodec_close( codec );
154 // Unlock the mutex now
155 pthread_mutex_unlock( &avformat_mutex );
162 static int producer_open( mlt_producer this, char *file )
164 // Return an error code (0 == no error)
167 // Context for avformat
168 AVFormatContext *context = NULL;
170 // Get the properties
171 mlt_properties properties = mlt_producer_properties( this );
173 // We will treat everything with the producer fps
174 double fps = mlt_properties_get_double( properties, "fps" );
176 // Lock the mutex now
177 pthread_mutex_lock( &avformat_mutex );
179 // Now attempt to open the file
180 error = av_open_input_file( &context, file, NULL, 0, NULL );
183 // If successful, then try to get additional info
186 // Get the stream info
187 error = av_find_stream_info( context ) < 0;
189 // Continue if no error
192 // We will default to the first audio and video streams found
193 int audio_index = -1;
194 int video_index = -1;
196 // Now set properties where we can (use default unknowns if required)
197 if ( context->duration != AV_NOPTS_VALUE )
199 // This isn't going to be accurate for all formats
200 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps );
201 mlt_properties_set_position( properties, "out", frames - 2 );
202 mlt_properties_set_position( properties, "length", frames - 1 );
205 // Find default audio and video streams
206 find_default_streams( context, &audio_index, &video_index );
208 // Store selected audio and video indexes on properties
209 mlt_properties_set_int( properties, "audio_index", audio_index );
210 mlt_properties_set_int( properties, "video_index", video_index );
212 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
213 if ( audio_index != -1 && video_index != -1 )
215 // We'll use the open one as our video_context
216 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
218 // And open again for our audio context
219 av_open_input_file( &context, file, NULL, 0, NULL );
220 av_find_stream_info( context );
223 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
225 else if ( video_index != -1 )
227 // We only have a video context
228 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
230 else if ( audio_index != -1 )
232 // We only have an audio context
233 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
237 // Something has gone wrong
243 // Unlock the mutex now
244 pthread_mutex_unlock( &avformat_mutex );
249 /** Convert a frame position to a time code.
252 static double producer_time_of_frame( mlt_producer this, mlt_position position )
254 // Get the properties
255 mlt_properties properties = mlt_producer_properties( this );
258 double fps = mlt_properties_get_double( properties, "fps" );
261 return ( double )position / fps;
264 /** Get an image from a frame.
267 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
269 // Get the properties from the frame
270 mlt_properties frame_properties = mlt_frame_properties( frame );
272 // Obtain the frame number of this frame
273 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
276 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
278 // Get the producer properties
279 mlt_properties properties = mlt_producer_properties( this );
281 // Fetch the video_context
282 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
284 // Get the video_index
285 int index = mlt_properties_get_int( properties, "video_index" );
287 // Obtain the expected frame numer
288 mlt_position expected = mlt_properties_get_position( properties, "video_expected" );
290 // Calculate the real time code
291 double real_timecode = producer_time_of_frame( this, position );
293 // Get the video stream
294 AVStream *stream = context->streams[ index ];
297 AVCodecContext *codec_context = &stream->codec;
302 // Get the conversion frame
303 AVPicture *output = mlt_properties_get_data( properties, "video_output_frame", NULL );
305 // Special case pause handling flag
308 // Special case ffwd handling
311 // Current time calcs
312 double current_time = mlt_properties_get_double( properties, "current_time" );
314 // We may want to use the source fps if available
315 double source_fps = mlt_properties_get_double( properties, "source_fps" );
317 // Set the result arguments that we know here (only *buffer is now required)
318 *format = mlt_image_yuv422;
319 *width = codec_context->width;
320 *height = codec_context->height;
322 // Set this on the frame properties
323 mlt_properties_set_int( frame_properties, "width", *width );
324 mlt_properties_set_int( frame_properties, "height", *height );
326 // Lock the mutex now
327 pthread_mutex_lock( &avformat_mutex );
329 // Construct an AVFrame for YUV422 conversion
330 if ( output == NULL )
332 int size = avpicture_get_size( PIX_FMT_YUV422, *width, *height );
334 uint8_t *buf = mlt_pool_alloc( size );
335 output = mlt_pool_alloc( sizeof( AVPicture ) );
336 //memset( output, 0, sizeof( AVPicture ) );
337 avpicture_fill( output, buf, PIX_FMT_YUV422, *width, *height );
338 mlt_properties_set_data( properties, "video_output_frame", output, 0, ( mlt_destructor )mlt_pool_release, NULL );
339 mlt_properties_set_data( properties, "video_output_buffer", buf, 0, ( mlt_destructor )mlt_pool_release, NULL );
343 if ( position != expected )
345 if ( position + 1 == expected )
347 // We're paused - use last image
350 else if ( position > expected && ( position - expected ) < 250 )
352 // Fast forward - seeking is inefficient for small distances - just ignore following frames
353 ignore = position - expected;
357 // Set to the real timecode
358 av_seek_frame( context, -1, real_timecode * 1000000.0 );
360 // Remove the cached info relating to the previous position
361 mlt_properties_set_double( properties, "current_time", real_timecode );
362 mlt_properties_set_data( properties, "current_image", NULL, 0, NULL, NULL );
366 // Duplicate the last image if necessary
367 if ( mlt_properties_get_data( properties, "current_image", NULL ) != NULL &&
368 ( paused || mlt_properties_get_double( properties, "current_time" ) >= real_timecode ) )
370 // Get current image and size
372 uint8_t *image = mlt_properties_get_data( properties, "current_image", &size );
375 *buffer = mlt_pool_alloc( size );
376 memcpy( *buffer, image, size );
378 // Set this on the frame properties
379 mlt_properties_set_data( frame_properties, "image", *buffer, size, ( mlt_destructor )mlt_pool_release, NULL );
387 memset( &pkt, 0, sizeof( pkt ) );
388 memset( &frame, 0, sizeof( frame ) );
390 while( ret >= 0 && !got_picture )
393 ret = av_read_frame( context, &pkt );
395 // We only deal with video from the selected video_index
396 if ( ret >= 0 && pkt.stream_index == index && pkt.size > 0 )
399 ret = avcodec_decode_video( codec_context, &frame, &got_picture, pkt.data, pkt.size );
403 if ( pkt.pts != AV_NOPTS_VALUE && pkt.pts != 0 )
404 current_time = ( double )pkt.pts / 1000000.0;
406 current_time = real_timecode;
409 if ( current_time < real_timecode )
414 else if ( current_time >= real_timecode )
416 //current_time = real_timecode;
419 else if ( ignore -- )
426 // We're finished with this packet regardless
427 av_free_packet( &pkt );
430 // Now handle the picture if we have one
433 // Get current image and size
435 uint8_t *image = mlt_properties_get_data( properties, "current_image", &size );
437 if ( image == NULL || size != *width * *height * 2 )
439 size = *width * ( *height + 1 ) * 2;
440 image = mlt_pool_alloc( size );
441 mlt_properties_set_data( properties, "current_image", image, size, ( mlt_destructor )mlt_pool_release, NULL );
444 *buffer = mlt_pool_alloc( size );
446 // EXPERIMENTAL IMAGE NORMALISATIONS
447 if ( codec_context->pix_fmt == PIX_FMT_YUV420P )
450 register int half = *width >> 1;
451 register uint8_t *Y = ( ( AVPicture * )&frame )->data[ 0 ];
452 register uint8_t *U = ( ( AVPicture * )&frame )->data[ 1 ];
453 register uint8_t *V = ( ( AVPicture * )&frame )->data[ 2 ];
454 register uint8_t *d = *buffer;
455 register uint8_t *y, *u, *v;
472 Y += ( ( AVPicture * )&frame )->linesize[ 0 ];
485 Y += ( ( AVPicture * )&frame )->linesize[ 0 ];
486 U += ( ( AVPicture * )&frame )->linesize[ 1 ];
487 V += ( ( AVPicture * )&frame )->linesize[ 2 ];
492 img_convert( output, PIX_FMT_YUV422, (AVPicture *)&frame, codec_context->pix_fmt, *width, *height );
493 memcpy( *buffer, output->data[ 0 ], size );
496 memcpy( image, *buffer, size );
497 mlt_properties_set_data( frame_properties, "image", *buffer, size, ( mlt_destructor )mlt_pool_release, NULL );
499 if ( current_time == 0 && source_fps != 0 )
501 double fps = mlt_properties_get_double( properties, "fps" );
502 current_time = ceil( source_fps * ( double )position / fps ) * ( 1 / source_fps );
503 mlt_properties_set_double( properties, "current_time", current_time );
507 mlt_properties_set_double( properties, "current_time", current_time );
512 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
513 mlt_properties_set_position( properties, "video_expected", position + 1 );
515 // Unlock the mutex now
516 pthread_mutex_unlock( &avformat_mutex );
521 /** Set up video handling.
524 static void producer_set_up_video( mlt_producer this, mlt_frame frame )
526 // Get the properties
527 mlt_properties properties = mlt_producer_properties( this );
529 // Fetch the video_context
530 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
532 // Get the video_index
533 int index = mlt_properties_get_int( properties, "video_index" );
535 // Get the frame properties
536 mlt_properties frame_properties = mlt_frame_properties( frame );
538 // Lock the mutex now
539 pthread_mutex_lock( &avformat_mutex );
541 if ( context != NULL && index != -1 )
543 // Get the video stream
544 AVStream *stream = context->streams[ index ];
547 AVCodecContext *codec_context = &stream->codec;
550 AVCodec *codec = mlt_properties_get_data( properties, "video_codec", NULL );
552 // Initialise the codec if necessary
556 codec = avcodec_find_decoder( codec_context->codec_id );
558 // If we don't have a codec and we can't initialise it, we can't do much more...
559 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
561 // Now store the codec with its destructor
562 mlt_properties_set_data( properties, "video_codec", codec_context, 0, producer_codec_close, NULL );
566 // Remember that we can't use this later
567 mlt_properties_set_int( properties, "video_index", -1 );
571 // No codec, no show...
574 double aspect_ratio = 0;
575 double source_fps = 0;
578 if ( codec_context->sample_aspect_ratio.num == 0 )
581 aspect_ratio = av_q2d( codec_context->sample_aspect_ratio ) * codec_context->width / codec_context->height;
583 // XXX: This assumes square pixels!
584 if (aspect_ratio <= 0.0)
585 aspect_ratio = ( double )codec_context->width / ( double )codec_context->height;
587 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
588 //fprintf( stderr, "AVFORMAT: sample aspect %f computed display aspect %f\n", av_q2d( codec_context->sample_aspect_ratio ), aspect_ratio );
591 source_fps = ( double )codec_context->frame_rate / codec_context->frame_rate_base;
593 // We'll use fps if it's available
594 if ( source_fps > 0 && source_fps < 30 )
595 mlt_properties_set_double( properties, "source_fps", source_fps );
597 mlt_frame_push_get_image( frame, producer_get_image );
598 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
603 mlt_properties_set_int( frame_properties, "test_image", 1 );
608 mlt_properties_set_int( frame_properties, "test_image", 1 );
611 // Unlock the mutex now
612 pthread_mutex_unlock( &avformat_mutex );
615 /** Get the audio from a frame.
618 static int producer_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
620 // Get the properties from the frame
621 mlt_properties frame_properties = mlt_frame_properties( frame );
623 // Obtain the frame number of this frame
624 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
627 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
629 // Get the producer properties
630 mlt_properties properties = mlt_producer_properties( this );
632 // Fetch the audio_context
633 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
635 // Get the audio_index
636 int index = mlt_properties_get_int( properties, "audio_index" );
638 // Obtain the expected frame numer
639 mlt_position expected = mlt_properties_get_position( properties, "audio_expected" );
641 // Obtain the resample context if it exists (not always needed)
642 ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
644 // Obtain the audio buffer
645 int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
647 // Get amount of audio used
648 int audio_used = mlt_properties_get_int( properties, "audio_used" );
650 // Calculate the real time code
651 double real_timecode = producer_time_of_frame( this, position );
653 // Get the audio stream
654 AVStream *stream = context->streams[ index ];
657 AVCodecContext *codec_context = &stream->codec;
662 // Number of frames to ignore (for ffwd)
665 // Flag for paused (silence)
669 // Lock the mutex now
670 pthread_mutex_lock( &avformat_mutex );
672 // Check for resample and create if necessary
673 if ( resample == NULL )
675 // Create the resampler
676 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
678 // And store it on properties
679 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
682 // Check for audio buffer and create if necessary
683 if ( audio_buffer == NULL )
685 // Allocate the audio buffer
686 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
688 // And store it on properties for reuse
689 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
693 if ( position != expected )
695 if ( position + 1 == expected )
697 // We're paused - silence required
700 else if ( position > expected && ( position - expected ) < 250 )
702 // Fast forward - seeking is inefficient for small distances - just ignore following frames
703 ignore = position - expected;
707 // Set to the real timecode
708 av_seek_frame( context, -1, real_timecode * 1000000.0 );
710 // Clear the usage in the audio buffer
717 // Get the audio if required
722 int16_t *temp = mlt_pool_alloc( sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE );
724 memset( &pkt, 0, sizeof( pkt ) );
726 while( ret >= 0 && !got_audio )
728 // Check if the buffer already contains the samples required
729 if ( audio_used >= *samples && ignore == 0 )
736 ret = av_read_frame( context, &pkt );
739 uint8_t *ptr = pkt.data;
742 // We only deal with video from the selected video_index
743 while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
746 ret = avcodec_decode_audio( codec_context, temp, &data_size, ptr, len );
759 int size_out = audio_resample( resample, &audio_buffer[ audio_used * *channels ], temp, data_size / ( codec_context->channels * sizeof( int16_t ) ) );
761 audio_used += size_out;
764 while ( ignore && audio_used > *samples )
767 audio_used -= *samples;
768 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
772 // If we're behind, ignore this packet
773 float current_pts = (float)pkt.pts / 1000000.0;
774 double discrepancy = mlt_properties_get_double( properties, "discrepancy" );
775 if ( current_pts != 0 && real_timecode != 0 )
777 if ( discrepancy != 1 )
778 discrepancy = ( discrepancy + ( real_timecode / current_pts ) ) / 2;
780 discrepancy = real_timecode / current_pts;
781 if ( discrepancy > 0.9 && discrepancy < 1.1 )
784 discrepancy = floor( discrepancy + 0.5 );
786 if ( discrepancy == 0 )
789 mlt_properties_set_double( properties, "discrepancy", discrepancy );
792 if ( !ignore && discrepancy * current_pts <= ( real_timecode - 0.02 ) )
796 // We're finished with this packet regardless
797 av_free_packet( &pkt );
800 *buffer = mlt_pool_alloc( *samples * *channels * sizeof( int16_t ) );
801 mlt_properties_set_data( frame_properties, "audio", *buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
803 // Now handle the audio if we have enough
804 if ( audio_used >= *samples )
806 memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
807 audio_used -= *samples;
808 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
812 memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
815 // Store the number of audio samples still available
816 mlt_properties_set_int( properties, "audio_used", audio_used );
818 // Release the temporary audio
819 mlt_pool_release( temp );
823 // Get silence and don't touch the context
824 frame->get_audio = NULL;
825 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
828 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
829 mlt_properties_set_position( properties, "audio_expected", position + 1 );
831 // Unlock the mutex now
832 pthread_mutex_unlock( &avformat_mutex );
837 /** Set up audio handling.
840 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
842 // Get the properties
843 mlt_properties properties = mlt_producer_properties( this );
845 // Fetch the audio_context
846 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
848 // Get the audio_index
849 int index = mlt_properties_get_int( properties, "audio_index" );
851 // Lock the mutex now
852 pthread_mutex_lock( &avformat_mutex );
854 // Deal with audio context
855 if ( context != NULL && index != -1 )
857 // Get the frame properties
858 mlt_properties frame_properties = mlt_frame_properties( frame );
860 // Get the audio stream
861 AVStream *stream = context->streams[ index ];
864 AVCodecContext *codec_context = &stream->codec;
867 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
869 // Initialise the codec if necessary
873 codec = avcodec_find_decoder( codec_context->codec_id );
875 // If we don't have a codec and we can't initialise it, we can't do much more...
876 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
878 // Now store the codec with its destructor
879 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
884 // Remember that we can't use this later
885 mlt_properties_set_int( properties, "audio_index", -1 );
889 // No codec, no show...
892 frame->get_audio = producer_get_audio;
893 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
897 // Unlock the mutex now
898 pthread_mutex_unlock( &avformat_mutex );
901 /** Our get frame implementation.
904 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
906 // Create an empty frame
907 *frame = mlt_frame_init( );
909 // Update timecode on the frame we're creating
910 mlt_frame_set_position( *frame, mlt_producer_position( this ) );
912 // Set the position of this producer
913 mlt_properties_set_position( mlt_frame_properties( *frame ), "avformat_position", mlt_producer_get_in( this ) + mlt_producer_position( this ) );
916 producer_set_up_video( this, *frame );
919 producer_set_up_audio( this, *frame );
921 // Set the aspect_ratio
922 mlt_properties_set_double( mlt_frame_properties( *frame ), "aspect_ratio", mlt_properties_get_double( mlt_producer_properties( this ), "aspect_ratio" ) );
924 // Calculate the next timecode
925 mlt_producer_prepare_next( this );