2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include <framework/mlt_producer.h>
24 #include <framework/mlt_frame.h>
25 #include <framework/mlt_profile.h>
27 // ffmpeg Header files
33 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
34 # include "audioconvert.h"
37 // System header files
42 #if LIBAVUTIL_VERSION_INT < (50<<16)
43 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
46 void avformat_lock( );
47 void avformat_unlock( );
49 // Forward references.
50 static int producer_open( mlt_producer this, mlt_profile profile, char *file );
51 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
53 /** Constructor for libavformat.
56 mlt_producer producer_avformat_init( mlt_profile profile, char *file )
60 // Report information about available demuxers and codecs as YAML Tiny
61 if ( file && strstr( file, "f-list" ) )
63 fprintf( stderr, "---\nformats:\n" );
64 AVInputFormat *format = NULL;
65 while ( ( format = av_iformat_next( format ) ) )
66 fprintf( stderr, " - %s\n", format->name );
67 fprintf( stderr, "...\n" );
70 if ( file && strstr( file, "acodec-list" ) )
72 fprintf( stderr, "---\naudio_codecs:\n" );
73 AVCodec *codec = NULL;
74 while ( ( codec = av_codec_next( codec ) ) )
75 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
76 fprintf( stderr, " - %s\n", codec->name );
77 fprintf( stderr, "...\n" );
80 if ( file && strstr( file, "vcodec-list" ) )
82 fprintf( stderr, "---\nvideo_codecs:\n" );
83 AVCodec *codec = NULL;
84 while ( ( codec = av_codec_next( codec ) ) )
85 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
86 fprintf( stderr, " - %s\n", codec->name );
87 fprintf( stderr, "...\n" );
93 mlt_producer this = NULL;
95 // Check that we have a non-NULL argument
98 // Construct the producer
99 this = calloc( 1, sizeof( struct mlt_producer_s ) );
102 if ( mlt_producer_init( this, NULL ) == 0 )
104 // Get the properties
105 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
107 // Set the resource property (required for all producers)
108 mlt_properties_set( properties, "resource", file );
110 // Register our get_frame implementation
111 this->get_frame = producer_get_frame;
114 if ( producer_open( this, profile, file ) != 0 )
117 mlt_producer_close( this );
122 // Close the file to release resources for large playlists - reopen later as needed
123 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
124 mlt_properties_set_data( properties, "audio_context", NULL, 0, NULL, NULL );
125 mlt_properties_set_data( properties, "video_context", NULL, 0, NULL, NULL );
127 // Default the user-selectable indices from the auto-detected indices
128 mlt_properties_set_int( properties, "audio_index", mlt_properties_get_int( properties, "_audio_index" ) );
129 mlt_properties_set_int( properties, "video_index", mlt_properties_get_int( properties, "_video_index" ) );
137 /** Find the default streams.
140 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
145 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
147 // Allow for multiple audio and video streams in the file and select first of each (if available)
148 for( i = 0; i < context->nb_streams; i++ )
150 // Get the codec context
151 AVStream *stream = context->streams[ i ];
152 if ( ! stream ) continue;
153 AVCodecContext *codec_context = stream->codec;
154 if ( ! codec_context ) continue;
155 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
156 if ( ! codec ) continue;
158 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
160 // Determine the type and obtain the first index of each type
161 switch( codec_context->codec_type )
163 case CODEC_TYPE_VIDEO:
164 if ( *video_index < 0 )
166 mlt_properties_set( meta_media, key, "video" );
167 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
168 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
169 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
170 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
171 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
173 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
174 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
175 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
176 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
178 case CODEC_TYPE_AUDIO:
179 if ( *audio_index < 0 )
181 mlt_properties_set( meta_media, key, "audio" );
182 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
183 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
184 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
186 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
187 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
188 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
189 mlt_properties_set_int( meta_media, key, codec_context->channels );
194 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
195 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
196 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
197 mlt_properties_set( meta_media, key, codec->name );
198 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
199 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
200 mlt_properties_set( meta_media, key, codec->long_name );
202 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
203 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
204 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
205 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
206 snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
207 mlt_properties_set_int( meta_media, key, codec_context->profile );
208 snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
209 mlt_properties_set_int( meta_media, key, codec_context->level );
215 /** Producer file destructor.
218 static void producer_file_close( void *context )
220 if ( context != NULL )
222 // Lock the mutex now
226 av_close_input_file( context );
228 // Unlock the mutex now
233 /** Producer file destructor.
236 static void producer_codec_close( void *codec )
240 // Lock the mutex now
244 avcodec_close( codec );
246 // Unlock the mutex now
251 static inline int dv_is_pal( AVPacket *pkt )
253 return pkt->data[3] & 0x80;
256 static int dv_is_wide( AVPacket *pkt )
258 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
260 for ( ; i < pkt->size; i += 5 /* packet size */ )
262 if ( pkt->data[ i ] == 0x61 )
264 uint8_t x = pkt->data[ i + 2 ] & 0x7;
265 return ( x == 2 ) || ( x == 7 );
271 static double get_aspect_ratio( AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
273 double aspect_ratio = 1.0;
275 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
279 if ( dv_is_pal( pkt ) )
281 aspect_ratio = dv_is_wide( pkt )
282 ? 64.0/45.0 // 16:9 PAL
283 : 16.0/15.0; // 4:3 PAL
287 aspect_ratio = dv_is_wide( pkt )
288 ? 32.0/27.0 // 16:9 NTSC
289 : 8.0/9.0; // 4:3 NTSC
295 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
296 stream->sample_aspect_ratio;
298 codec_context->sample_aspect_ratio;
300 // Override FFmpeg's notion of DV aspect ratios, which are
301 // based upon a width of 704. Since we do not have a normaliser
302 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
303 // we just coerce the values to facilitate a passive behaviour through
304 // the rescale normaliser when using equivalent producers and consumers.
305 // = display_aspect / (width * height)
306 if ( ar.num == 10 && ar.den == 11 )
307 aspect_ratio = 8.0/9.0; // 4:3 NTSC
308 else if ( ar.num == 59 && ar.den == 54 )
309 aspect_ratio = 16.0/15.0; // 4:3 PAL
310 else if ( ar.num == 40 && ar.den == 33 )
311 aspect_ratio = 32.0/27.0; // 16:9 NTSC
312 else if ( ar.num == 118 && ar.den == 81 )
313 aspect_ratio = 64.0/45.0; // 16:9 PAL
318 AVRational codec_sar = codec_context->sample_aspect_ratio;
319 AVRational stream_sar =
320 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
321 stream->sample_aspect_ratio;
325 if ( codec_sar.num > 0 )
326 aspect_ratio = av_q2d( codec_sar );
327 else if ( stream_sar.num > 0 )
328 aspect_ratio = av_q2d( stream_sar );
336 static int producer_open( mlt_producer this, mlt_profile profile, char *file )
338 // Return an error code (0 == no error)
341 // Context for avformat
342 AVFormatContext *context = NULL;
344 // Get the properties
345 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
347 // We will treat everything with the producer fps
348 double fps = mlt_profile_fps( profile );
350 // Lock the mutex now
353 // If "MRL", then create AVInputFormat
354 AVInputFormat *format = NULL;
355 AVFormatParameters *params = NULL;
356 char *standard = NULL;
357 char *mrl = strchr( file, ':' );
359 // AV option (0 = both, 1 = video, 2 = audio)
362 // Setting lowest log level
363 av_log_set_level( -1 );
365 // Only if there is not a protocol specification that avformat can handle
366 if ( mrl && !url_exist( file ) )
368 // 'file' becomes format abbreviation
372 format = av_find_input_format( file );
374 // Eat the format designator
380 params = calloc( sizeof( AVFormatParameters ), 1 );
382 // These are required by video4linux (defaults)
384 params->height = 480;
385 params->time_base= (AVRational){1,25};
386 // params->device = file;
387 params->channels = 2;
388 params->sample_rate = 48000;
391 // XXX: this does not work anymore since avdevice
392 // TODO: make producer_avddevice?
394 mrl = strchr( file, '?' );
398 char *name = strdup( ++mrl );
399 char *value = strchr( name, ':' );
404 char *t = strchr( value, '&' );
407 if ( !strcmp( name, "frame_rate" ) )
408 params->time_base.den = atoi( value );
409 else if ( !strcmp( name, "frame_rate_base" ) )
410 params->time_base.num = atoi( value );
411 else if ( !strcmp( name, "sample_rate" ) )
412 params->sample_rate = atoi( value );
413 else if ( !strcmp( name, "channels" ) )
414 params->channels = atoi( value );
415 else if ( !strcmp( name, "width" ) )
416 params->width = atoi( value );
417 else if ( !strcmp( name, "height" ) )
418 params->height = atoi( value );
419 else if ( !strcmp( name, "standard" ) )
421 standard = strdup( value );
422 params->standard = standard;
424 else if ( !strcmp( name, "av" ) )
428 mrl = strchr( mrl, '&' );
432 // Now attempt to open the file
433 error = av_open_input_file( &context, file, format, 0, params ) < 0;
435 // Cleanup AVFormatParameters
439 // If successful, then try to get additional info
442 // Get the stream info
443 error = av_find_stream_info( context ) < 0;
445 // Continue if no error
448 // We will default to the first audio and video streams found
449 int audio_index = -1;
450 int video_index = -1;
453 // Now set properties where we can (use default unknowns if required)
454 if ( context->duration != AV_NOPTS_VALUE )
456 // This isn't going to be accurate for all formats
457 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + 0.5 );
458 mlt_properties_set_position( properties, "out", frames - 1 );
459 mlt_properties_set_position( properties, "length", frames );
462 // Find default audio and video streams
463 find_default_streams( properties, context, &audio_index, &video_index );
465 if ( context->start_time != AV_NOPTS_VALUE )
466 mlt_properties_set_double( properties, "_start_time", context->start_time );
468 // Check if we're seekable (something funny about mpeg here :-/)
469 if ( strcmp( file, "pipe:" ) && strncmp( file, "http://", 6 ) && strncmp( file, "udp:", 4 ) && strncmp( file, "tcp:", 4 ) && strncmp( file, "rtsp:", 5 ) && strncmp( file, "rtp:", 4 ) )
471 mlt_properties_set_int( properties, "seekable", av_seek_frame( context, -1, mlt_properties_get_double( properties, "_start_time" ), AVSEEK_FLAG_BACKWARD ) >= 0 );
472 mlt_properties_set_data( properties, "dummy_context", context, 0, producer_file_close, NULL );
473 av_open_input_file( &context, file, NULL, 0, NULL );
474 av_find_stream_info( context );
479 // Store selected audio and video indexes on properties
480 mlt_properties_set_int( properties, "_audio_index", audio_index );
481 mlt_properties_set_int( properties, "_video_index", video_index );
482 mlt_properties_set_int( properties, "_last_position", -1 );
484 // Fetch the width, height and aspect ratio
485 if ( video_index != -1 )
487 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
488 mlt_properties_set_int( properties, "width", codec_context->width );
489 mlt_properties_set_int( properties, "height", codec_context->height );
491 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
493 // Fetch the first frame of DV so we can read it directly
498 ret = av_read_frame( context, &pkt );
499 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
501 mlt_properties_set_double( properties, "aspect_ratio",
502 get_aspect_ratio( context->streams[ video_index ], codec_context, &pkt ) );
509 mlt_properties_set_double( properties, "aspect_ratio",
510 get_aspect_ratio( context->streams[ video_index ], codec_context, NULL ) );
515 if (context->title != NULL)
516 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
517 if (context->author != NULL)
518 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
519 if (context->copyright != NULL)
520 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
521 if (context->comment != NULL)
522 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
523 if (context->album != NULL)
524 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
525 if (context->year != 0)
526 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
527 if (context->track != 0)
528 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
530 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
531 if ( av == 0 && audio_index != -1 && video_index != -1 )
533 // We'll use the open one as our video_context
534 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
536 // And open again for our audio context
537 av_open_input_file( &context, file, NULL, 0, NULL );
538 av_find_stream_info( context );
541 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
543 else if ( av != 2 && video_index != -1 )
545 // We only have a video context
546 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
548 else if ( audio_index != -1 )
550 // We only have an audio context
551 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
555 // Something has gone wrong
559 mlt_properties_set_int( properties, "av_bypass", av_bypass );
563 // Unlock the mutex now
569 /** Convert a frame position to a time code.
572 static double producer_time_of_frame( mlt_producer this, mlt_position position )
574 return ( double )position / mlt_producer_get_fps( this );
577 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format format, int width, int height )
580 if ( format == mlt_image_yuv420p )
582 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
583 width, height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
585 output.data[0] = buffer;
586 output.data[1] = buffer + width * height;
587 output.data[2] = buffer + ( 3 * width * height ) / 2;
588 output.linesize[0] = width;
589 output.linesize[1] = width >> 1;
590 output.linesize[2] = width >> 1;
591 sws_scale( context, frame->data, frame->linesize, 0, height,
592 output.data, output.linesize);
593 sws_freeContext( context );
595 else if ( format == mlt_image_rgb24 )
597 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
598 width, height, PIX_FMT_RGB24, SWS_FAST_BILINEAR, NULL, NULL, NULL);
600 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
601 sws_scale( context, frame->data, frame->linesize, 0, height,
602 output.data, output.linesize);
603 sws_freeContext( context );
607 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
608 width, height, PIX_FMT_YUYV422, SWS_FAST_BILINEAR, NULL, NULL, NULL);
610 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
611 sws_scale( context, frame->data, frame->linesize, 0, height,
612 output.data, output.linesize);
613 sws_freeContext( context );
616 if ( format == mlt_image_yuv420p )
619 pict.data[0] = buffer;
620 pict.data[1] = buffer + width * height;
621 pict.data[2] = buffer + ( 3 * width * height ) / 2;
622 pict.linesize[0] = width;
623 pict.linesize[1] = width >> 1;
624 pict.linesize[2] = width >> 1;
625 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
627 else if ( format == mlt_image_rgb24 )
630 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
631 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
636 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
637 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
642 /** Allocate the image buffer and set it on the frame.
645 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
649 if ( codec_context->width == 0 || codec_context->height == 0 )
652 *width = codec_context->width;
653 *height = codec_context->height;
654 mlt_properties_set_int( frame_properties, "width", *width );
655 mlt_properties_set_int( frame_properties, "height", *height );
659 case mlt_image_yuv420p:
660 size = *width * 3 * ( *height + 1 ) / 2;
662 case mlt_image_rgb24:
663 size = *width * ( *height + 1 ) * 3;
666 *format = mlt_image_yuv422;
667 size = *width * ( *height + 1 ) * 2;
671 // Construct the output image
672 *buffer = mlt_pool_alloc( size );
674 mlt_properties_set_data( frame_properties, "image", *buffer, size, (mlt_destructor)mlt_pool_release, NULL );
681 /** Get an image from a frame.
684 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
686 // Get the properties from the frame
687 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
689 // Obtain the frame number of this frame
690 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
693 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
695 // Get the producer properties
696 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
698 // Fetch the video_context
699 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
701 // Get the video_index
702 int index = mlt_properties_get_int( properties, "video_index" );
704 // Obtain the expected frame numer
705 mlt_position expected = mlt_properties_get_position( properties, "_video_expected" );
707 // Get the video stream
708 AVStream *stream = context->streams[ index ];
711 AVCodecContext *codec_context = stream->codec;
716 // Get the conversion frame
717 AVFrame *av_frame = mlt_properties_get_data( properties, "av_frame", NULL );
719 // Special case pause handling flag
722 // Special case ffwd handling
725 // We may want to use the source fps if available
726 double source_fps = mlt_properties_get_double( properties, "source_fps" );
727 double fps = mlt_producer_get_fps( this );
729 // This is the physical frame position in the source
730 int req_position = ( int )( position / fps * source_fps + 0.5 );
732 // Get the seekable status
733 int seekable = mlt_properties_get_int( properties, "seekable" );
735 // Hopefully provide better support for streams...
736 int av_bypass = mlt_properties_get_int( properties, "av_bypass" );
738 // Determines if we have to decode all frames in a sequence
741 // Temporary hack to improve intra frame only
742 must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
743 strcmp( codec_context->codec->name, "dvvideo" ) &&
744 strcmp( codec_context->codec->name, "huffyuv" ) &&
745 strcmp( codec_context->codec->name, "mjpeg" ) &&
746 strcmp( codec_context->codec->name, "rawvideo" );
749 if ( position != expected )
751 if ( av_frame != NULL && position + 1 == expected )
753 // We're paused - use last image
756 else if ( !seekable && position > expected && ( position - expected ) < 250 )
758 // Fast forward - seeking is inefficient for small distances - just ignore following frames
759 ignore = ( int )( ( position - expected ) / fps * source_fps );
761 else if ( seekable && ( position < expected || position - expected >= 12 ) )
763 // Calculate the timestamp for the requested frame
764 int64_t timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
765 if ( ( uint64_t )context->start_time != AV_NOPTS_VALUE )
766 timestamp += context->start_time;
768 timestamp -= AV_TIME_BASE;
772 // Set to the timestamp
773 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
775 // Remove the cached info relating to the previous position
776 mlt_properties_set_int( properties, "_current_position", -1 );
777 mlt_properties_set_int( properties, "_last_position", -1 );
778 mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
783 // Duplicate the last image if necessary (see comment on rawvideo below)
784 int current_position = mlt_properties_get_int( properties, "_current_position" );
785 int got_picture = mlt_properties_get_int( properties, "_got_picture" );
786 if ( av_frame != NULL && got_picture && ( paused || current_position >= req_position ) && av_bypass == 0 )
789 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
790 convert_image( av_frame, *buffer, codec_context->pix_fmt, *format, *width, *height );
792 mlt_frame_get_image( frame, buffer, format, width, height, writable );
797 int int_position = 0;
800 av_init_packet( &pkt );
802 // Construct an AVFrame for YUV422 conversion
803 if ( av_frame == NULL )
804 av_frame = avcodec_alloc_frame( );
806 while( ret >= 0 && !got_picture )
809 ret = av_read_frame( context, &pkt );
811 // We only deal with video from the selected video_index
812 if ( ret >= 0 && pkt.stream_index == index && pkt.size > 0 )
814 // Determine time code of the packet
815 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
816 if ( context->start_time != AV_NOPTS_VALUE )
817 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
818 int last_position = mlt_properties_get_int( properties, "_last_position" );
819 if ( int_position == last_position )
820 int_position = last_position + 1;
821 mlt_properties_set_int( properties, "_last_position", int_position );
824 if ( must_decode || int_position >= req_position )
825 ret = avcodec_decode_video( codec_context, av_frame, &got_picture, pkt.data, pkt.size );
830 if ( int_position < req_position )
835 else if ( int_position >= req_position )
839 else if ( ignore -- )
844 av_free_packet( &pkt );
848 av_free_packet( &pkt );
851 // Now handle the picture if we have one
854 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
856 convert_image( av_frame, *buffer, codec_context->pix_fmt, *format, *width, *height );
857 mlt_properties_set_int( frame_properties, "progressive", !av_frame->interlaced_frame );
858 mlt_properties_set_int( properties, "top_field_first", av_frame->top_field_first );
859 mlt_properties_set_int( properties, "_current_position", int_position );
860 mlt_properties_set_int( properties, "_got_picture", 1 );
861 mlt_properties_set_data( properties, "av_frame", av_frame, 0, av_free, NULL );
870 mlt_frame_get_image( frame, buffer, format, width, height, writable );
873 // Very untidy - for rawvideo, the packet contains the frame, hence the free packet
874 // above will break the pause behaviour - so we wipe the frame now
875 if ( !strcmp( codec_context->codec->name, "rawvideo" ) )
876 mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
878 // Set the field order property for this frame
879 mlt_properties_set_int( frame_properties, "top_field_first", mlt_properties_get_int( properties, "top_field_first" ) );
881 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
882 mlt_properties_set_position( properties, "_video_expected", position + 1 );
887 /** Process properties as AVOptions and apply to AV context obj
890 static void apply_properties( void *obj, mlt_properties properties, int flags )
893 int count = mlt_properties_count( properties );
894 for ( i = 0; i < count; i++ )
896 const char *opt_name = mlt_properties_get_name( properties, i );
897 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
899 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
900 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
901 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
902 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
904 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
909 /** Set up video handling.
912 static void producer_set_up_video( mlt_producer this, mlt_frame frame )
914 // Get the properties
915 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
917 // Fetch the video_context
918 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
920 // Get the video_index
921 int index = mlt_properties_get_int( properties, "video_index" );
923 // Reopen the file if necessary
924 if ( !context && index > -1 )
926 mlt_events_block( properties, this );
927 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(this) ),
928 mlt_properties_get( properties, "resource" ) );
929 context = mlt_properties_get_data( properties, "video_context", NULL );
930 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
931 mlt_events_unblock( properties, this );
933 // Process properties as AVOptions
934 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
937 // Exception handling for video_index
938 if ( context && index >= (int) context->nb_streams )
940 // Get the last video stream
941 for ( index = context->nb_streams - 1; index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO; --index );
942 mlt_properties_set_int( properties, "video_index", index );
944 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
946 // Invalidate the video stream
948 mlt_properties_set_int( properties, "video_index", index );
951 // Get the frame properties
952 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
954 if ( context && index > -1 )
956 // Get the video stream
957 AVStream *stream = context->streams[ index ];
960 AVCodecContext *codec_context = stream->codec;
963 AVCodec *codec = mlt_properties_get_data( properties, "video_codec", NULL );
965 // Update the video properties if the index changed
966 if ( index != mlt_properties_get_int( properties, "_video_index" ) )
968 // Reset the video properties if the index changed
969 mlt_properties_set_int( properties, "_video_index", index );
970 mlt_properties_set_data( properties, "video_codec", NULL, 0, NULL, NULL );
971 mlt_properties_set_int( properties, "width", codec_context->width );
972 mlt_properties_set_int( properties, "height", codec_context->height );
973 // TODO: get the first usable AVPacket and reset the stream position
974 mlt_properties_set_double( properties, "aspect_ratio",
975 get_aspect_ratio( context->streams[ index ], codec_context, NULL ) );
979 // Initialise the codec if necessary
982 // Initialise multi-threading
983 int thread_count = mlt_properties_get_int( properties, "threads" );
984 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
985 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
986 if ( thread_count > 1 )
988 avcodec_thread_init( codec_context, thread_count );
989 codec_context->thread_count = thread_count;
993 codec = avcodec_find_decoder( codec_context->codec_id );
995 // If we don't have a codec and we can't initialise it, we can't do much more...
997 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
999 // Now store the codec with its destructor
1000 mlt_properties_set_data( properties, "video_codec", codec_context, 0, producer_codec_close, NULL );
1004 // Remember that we can't use this later
1005 mlt_properties_set_int( properties, "video_index", -1 );
1010 // Process properties as AVOptions
1011 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1014 // No codec, no show...
1015 if ( codec && index > -1 )
1017 double source_fps = 0;
1018 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1019 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1020 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1022 // Determine the fps
1023 source_fps = ( double )codec_context->time_base.den / ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num );
1025 // We'll use fps if it's available
1026 if ( source_fps > 0 )
1027 mlt_properties_set_double( properties, "source_fps", source_fps );
1029 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( this ) );
1030 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
1032 // Set the width and height
1033 mlt_properties_set_int( frame_properties, "width", codec_context->width );
1034 mlt_properties_set_int( frame_properties, "height", codec_context->height );
1035 mlt_properties_set_int( frame_properties, "real_width", codec_context->width );
1036 mlt_properties_set_int( frame_properties, "real_height", codec_context->height );
1037 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1039 mlt_frame_push_get_image( frame, producer_get_image );
1040 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
1044 mlt_properties_set_int( frame_properties, "test_image", 1 );
1049 mlt_properties_set_int( frame_properties, "test_image", 1 );
1053 /** Get the audio from a frame.
1056 static int producer_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1058 // Get the properties from the frame
1059 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1061 // Obtain the frame number of this frame
1062 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1065 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
1067 // Get the producer properties
1068 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
1070 // Fetch the audio_context
1071 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
1073 // Get the audio_index
1074 int index = mlt_properties_get_int( properties, "audio_index" );
1076 // Get the seekable status
1077 int seekable = mlt_properties_get_int( properties, "seekable" );
1079 // Obtain the expected frame numer
1080 mlt_position expected = mlt_properties_get_position( properties, "_audio_expected" );
1082 // Obtain the resample context if it exists (not always needed)
1083 ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
1085 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
1086 // Get the format converter context if it exists
1087 AVAudioConvert *convert = mlt_properties_get_data( properties, "audio_convert", NULL );
1090 // Obtain the audio buffers
1091 int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
1092 int16_t *decode_buffer = mlt_properties_get_data( properties, "decode_buffer", NULL );
1093 int16_t *convert_buffer = mlt_properties_get_data( properties, "convert_buffer", NULL );
1095 // Get amount of audio used
1096 int audio_used = mlt_properties_get_int( properties, "_audio_used" );
1098 // Calculate the real time code
1099 double real_timecode = producer_time_of_frame( this, position );
1101 // Get the audio stream
1102 AVStream *stream = context->streams[ index ];
1104 // Get codec context
1105 AVCodecContext *codec_context = stream->codec;
1110 // Number of frames to ignore (for ffwd)
1113 // Flag for paused (silence)
1116 // Check for resample and create if necessary
1117 if ( resample == NULL && codec_context->channels <= 2 )
1119 // Create the resampler
1120 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
1122 // And store it on properties
1123 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
1125 else if ( resample == NULL )
1127 *channels = codec_context->channels;
1128 *frequency = codec_context->sample_rate;
1131 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
1132 // Check for audio format converter and create if necessary
1133 // TODO: support higher resolutions than 16-bit.
1134 if ( convert == NULL && codec_context->sample_fmt != SAMPLE_FMT_S16 )
1136 // Create single channel converter for interleaved with no mixing matrix
1137 convert = av_audio_convert_alloc( SAMPLE_FMT_S16, 1, codec_context->sample_fmt, 1, NULL, 0 );
1138 mlt_properties_set_data( properties, "audio_convert", convert, 0, ( mlt_destructor )av_audio_convert_free, NULL );
1142 // Check for audio buffer and create if necessary
1143 if ( audio_buffer == NULL )
1145 // Allocate the audio buffer
1146 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1148 // And store it on properties for reuse
1149 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
1152 // Check for decoder buffer and create if necessary
1153 if ( decode_buffer == NULL )
1155 // Allocate the audio buffer
1156 decode_buffer = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1158 // And store it on properties for reuse
1159 mlt_properties_set_data( properties, "decode_buffer", decode_buffer, 0, ( mlt_destructor )av_free, NULL );
1162 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
1163 // Check for format converter buffer and create if necessary
1164 if ( resample && convert && convert_buffer == NULL )
1166 // Allocate the audio buffer
1167 convert_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1169 // And store it on properties for reuse
1170 mlt_properties_set_data( properties, "convert_buffer", convert_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
1174 // Seek if necessary
1175 if ( position != expected )
1177 if ( position + 1 == expected )
1179 // We're paused - silence required
1182 else if ( !seekable && position > expected && ( position - expected ) < 250 )
1184 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1185 ignore = position - expected;
1187 else if ( position < expected || position - expected >= 12 )
1189 int64_t timestamp = ( int64_t )( real_timecode * AV_TIME_BASE + 0.5 );
1190 if ( context->start_time != AV_NOPTS_VALUE )
1191 timestamp += context->start_time;
1192 if ( timestamp < 0 )
1195 // Set to the real timecode
1196 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1199 // Clear the usage in the audio buffer
1204 // Get the audio if required
1210 av_init_packet( &pkt );
1212 while( ret >= 0 && !got_audio )
1214 // Check if the buffer already contains the samples required
1215 if ( audio_used >= *samples && ignore == 0 )
1222 ret = av_read_frame( context, &pkt );
1225 uint8_t *ptr = pkt.data;
1227 // We only deal with audio from the selected audio_index
1228 while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
1230 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1233 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1234 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1236 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1247 if ( data_size > 0 )
1249 int src_stride[6]= { av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 };
1250 int dst_stride[6]= { av_get_bits_per_sample_format( SAMPLE_FMT_S16 ) / 8 };
1254 int16_t *source = decode_buffer;
1255 int16_t *dest = &audio_buffer[ audio_used * *channels ];
1256 int convert_samples = data_size / src_stride[0];
1258 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
1261 const void *src_buf[6] = { decode_buffer };
1262 void *dst_buf[6] = { convert_buffer };
1263 av_audio_convert( convert, dst_buf, dst_stride, src_buf, src_stride, convert_samples );
1264 source = convert_buffer;
1267 audio_used += audio_resample( resample, dest, source, convert_samples / codec_context->channels );
1271 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
1274 const void *src_buf[6] = { decode_buffer };
1275 void *dst_buf[6] = { &audio_buffer[ audio_used * *channels ] };
1276 av_audio_convert( convert, dst_buf, dst_stride, src_buf, src_stride, data_size / src_stride[0] );
1281 memcpy( &audio_buffer[ audio_used * *channels ], decode_buffer, data_size );
1283 audio_used += data_size / *channels / src_stride[0];
1287 while ( ignore && audio_used > *samples )
1290 audio_used -= *samples;
1291 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
1295 // If we're behind, ignore this packet
1298 double current_pts = av_q2d( stream->time_base ) * pkt.pts;
1299 double source_fps = mlt_properties_get_double( properties, "source_fps" );
1300 int req_position = ( int )( real_timecode * source_fps + 0.5 );
1301 int int_position = ( int )( current_pts * source_fps + 0.5 );
1303 if ( context->start_time != AV_NOPTS_VALUE )
1304 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1305 if ( seekable && !ignore && int_position < req_position )
1310 // We're finished with this packet regardless
1311 av_free_packet( &pkt );
1314 *buffer = mlt_pool_alloc( *samples * *channels * sizeof( int16_t ) );
1315 mlt_properties_set_data( frame_properties, "audio", *buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
1317 // Now handle the audio if we have enough
1318 if ( audio_used >= *samples )
1320 memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
1321 audio_used -= *samples;
1322 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
1326 memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
1329 // Store the number of audio samples still available
1330 mlt_properties_set_int( properties, "_audio_used", audio_used );
1334 // Get silence and don't touch the context
1335 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1338 // Regardless of speed (other than paused), we expect to get the next frame
1340 mlt_properties_set_position( properties, "_audio_expected", position + 1 );
1345 /** Set up audio handling.
1348 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
1350 // Get the properties
1351 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
1353 // Fetch the audio_context
1354 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
1356 // Get the audio_index
1357 int index = mlt_properties_get_int( properties, "audio_index" );
1359 // Reopen the file if necessary
1360 if ( !context && index > -1 )
1362 mlt_events_block( properties, this );
1363 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(this) ),
1364 mlt_properties_get( properties, "resource" ) );
1365 context = mlt_properties_get_data( properties, "audio_context", NULL );
1366 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
1367 mlt_events_unblock( properties, this );
1370 // Exception handling for audio_index
1371 if ( context && index >= (int) context->nb_streams )
1373 for ( index = context->nb_streams - 1; index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO; --index );
1374 mlt_properties_set_int( properties, "audio_index", index );
1376 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1379 mlt_properties_set_int( properties, "audio_index", index );
1382 // Update the audio properties if the index changed
1383 if ( index > -1 && index != mlt_properties_get_int( properties, "_audio_index" ) )
1385 mlt_properties_set_int( properties, "_audio_index", index );
1386 mlt_properties_set_data( properties, "audio_codec", NULL, 0, NULL, NULL );
1389 // Deal with audio context
1390 if ( context != NULL && index > -1 )
1392 // Get the frame properties
1393 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1395 // Get the audio stream
1396 AVStream *stream = context->streams[ index ];
1398 // Get codec context
1399 AVCodecContext *codec_context = stream->codec;
1402 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
1404 // Initialise the codec if necessary
1405 if ( codec == NULL )
1408 codec = avcodec_find_decoder( codec_context->codec_id );
1410 // If we don't have a codec and we can't initialise it, we can't do much more...
1412 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
1414 // Now store the codec with its destructor
1415 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
1420 // Remember that we can't use this later
1421 mlt_properties_set_int( properties, "audio_index", -1 );
1426 // Process properties as AVOptions
1427 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1430 // No codec, no show...
1431 if ( codec && index > -1 )
1433 mlt_frame_push_audio( frame, producer_get_audio );
1434 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
1435 mlt_properties_set_int( frame_properties, "frequency", codec_context->sample_rate );
1436 mlt_properties_set_int( frame_properties, "channels", codec_context->channels );
1441 /** Our get frame implementation.
1444 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
1446 // Create an empty frame
1447 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE( this ) );
1449 // Update timecode on the frame we're creating
1450 mlt_frame_set_position( *frame, mlt_producer_position( this ) );
1452 // Set the position of this producer
1453 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( this ) );
1456 producer_set_up_video( this, *frame );
1459 producer_set_up_audio( this, *frame );
1461 // Set the aspect_ratio
1462 mlt_properties_set_double( MLT_FRAME_PROPERTIES( *frame ), "aspect_ratio", mlt_properties_get_double( MLT_PRODUCER_PROPERTIES( this ), "aspect_ratio" ) );
1464 // Calculate the next timecode
1465 mlt_producer_prepare_next( this );