2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2009 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Author: Dan Dennedy <dan@dennedy.org>
6 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <framework/mlt_producer.h>
25 #include <framework/mlt_frame.h>
26 #include <framework/mlt_profile.h>
27 #include <framework/mlt_log.h>
28 #include <framework/mlt_deque.h>
29 #include <framework/mlt_factory.h>
30 #include <framework/mlt_cache.h>
32 // ffmpeg Header files
38 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
39 # include "audioconvert.h"
45 // System header files
52 #if LIBAVUTIL_VERSION_INT < (50<<16)
53 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
54 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
57 #define POSITION_INITIAL (-2)
58 #define POSITION_INVALID (-1)
60 #define MAX_AUDIO_STREAMS (8)
61 #define MAX_VDPAU_SURFACES (10)
63 void avformat_lock( );
64 void avformat_unlock( );
66 struct producer_avformat_s
69 AVFormatContext *dummy_context;
70 AVFormatContext *audio_format;
71 AVFormatContext *video_format;
72 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
73 AVCodecContext *video_codec;
75 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
76 mlt_position audio_expected;
77 mlt_position video_expected;
87 int16_t *audio_buffer[ MAX_AUDIO_STREAMS ];
88 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
89 int16_t *decode_buffer[ MAX_AUDIO_STREAMS ];
90 int audio_used[ MAX_AUDIO_STREAMS ];
96 unsigned int invalid_pts_counter;
97 double resample_factor;
102 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
113 typedef struct producer_avformat_s *producer_avformat;
115 // Forward references.
116 static int producer_open( producer_avformat this, mlt_profile profile, char *file );
117 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
118 static void producer_format_close( void *context );
119 static void producer_avformat_close( producer_avformat );
120 static void producer_close( mlt_producer parent );
126 /** Constructor for libavformat.
129 mlt_producer producer_avformat_init( mlt_profile profile, char *file )
133 // Report information about available demuxers and codecs as YAML Tiny
134 if ( file && strstr( file, "f-list" ) )
136 fprintf( stderr, "---\nformats:\n" );
137 AVInputFormat *format = NULL;
138 while ( ( format = av_iformat_next( format ) ) )
139 fprintf( stderr, " - %s\n", format->name );
140 fprintf( stderr, "...\n" );
143 if ( file && strstr( file, "acodec-list" ) )
145 fprintf( stderr, "---\naudio_codecs:\n" );
146 AVCodec *codec = NULL;
147 while ( ( codec = av_codec_next( codec ) ) )
148 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
149 fprintf( stderr, " - %s\n", codec->name );
150 fprintf( stderr, "...\n" );
153 if ( file && strstr( file, "vcodec-list" ) )
155 fprintf( stderr, "---\nvideo_codecs:\n" );
156 AVCodec *codec = NULL;
157 while ( ( codec = av_codec_next( codec ) ) )
158 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
159 fprintf( stderr, " - %s\n", codec->name );
160 fprintf( stderr, "...\n" );
164 // Check that we have a non-NULL argument
167 // Construct the producer
168 mlt_producer producer = calloc( 1, sizeof( struct mlt_producer_s ) );
169 producer_avformat this = calloc( 1, sizeof( struct producer_avformat_s ) );
172 if ( mlt_producer_init( producer, this ) == 0 )
174 this->parent = producer;
176 // Get the properties
177 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
179 // Set the resource property (required for all producers)
180 mlt_properties_set( properties, "resource", file );
182 // Register transport implementation with the producer
183 producer->close = (mlt_destructor) producer_close;
185 // Register our get_frame implementation
186 producer->get_frame = producer_get_frame;
189 if ( producer_open( this, profile, file ) != 0 )
192 mlt_producer_close( producer );
197 // Default the user-selectable indices from the auto-detected indices
198 mlt_properties_set_int( properties, "audio_index", this->audio_index );
199 mlt_properties_set_int( properties, "video_index", this->video_index );
202 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
204 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
212 /** Find the default streams.
215 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
220 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
222 // Allow for multiple audio and video streams in the file and select first of each (if available)
223 for( i = 0; i < context->nb_streams; i++ )
225 // Get the codec context
226 AVStream *stream = context->streams[ i ];
227 if ( ! stream ) continue;
228 AVCodecContext *codec_context = stream->codec;
229 if ( ! codec_context ) continue;
230 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
231 if ( ! codec ) continue;
233 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
235 // Determine the type and obtain the first index of each type
236 switch( codec_context->codec_type )
238 case CODEC_TYPE_VIDEO:
239 if ( *video_index < 0 )
241 mlt_properties_set( meta_media, key, "video" );
242 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
243 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
244 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
245 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
246 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
248 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
249 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
250 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
251 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
252 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
253 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
254 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
256 case CODEC_TYPE_AUDIO:
257 if ( *audio_index < 0 )
259 mlt_properties_set( meta_media, key, "audio" );
260 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
261 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
262 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
264 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
265 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
266 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
267 mlt_properties_set_int( meta_media, key, codec_context->channels );
272 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
273 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
274 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
275 mlt_properties_set( meta_media, key, codec->name );
276 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
277 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
278 mlt_properties_set( meta_media, key, codec->long_name );
280 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
281 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
282 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
283 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
284 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
285 // mlt_properties_set_int( meta_media, key, codec_context->profile );
286 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
287 // mlt_properties_set_int( meta_media, key, codec_context->level );
293 /** Producer file destructor.
296 static void producer_format_close( void *context )
300 // Lock the mutex now
304 av_close_input_file( context );
306 // Unlock the mutex now
311 /** Producer file destructor.
314 static void producer_codec_close( void *codec )
318 // Lock the mutex now
322 avcodec_close( codec );
324 // Unlock the mutex now
329 static inline int dv_is_pal( AVPacket *pkt )
331 return pkt->data[3] & 0x80;
334 static int dv_is_wide( AVPacket *pkt )
336 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
338 for ( ; i < pkt->size; i += 5 /* packet size */ )
340 if ( pkt->data[ i ] == 0x61 )
342 uint8_t x = pkt->data[ i + 2 ] & 0x7;
343 return ( x == 2 ) || ( x == 7 );
349 static double get_aspect_ratio( AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
351 double aspect_ratio = 1.0;
353 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
357 if ( dv_is_pal( pkt ) )
359 aspect_ratio = dv_is_wide( pkt )
360 ? 64.0/45.0 // 16:9 PAL
361 : 16.0/15.0; // 4:3 PAL
365 aspect_ratio = dv_is_wide( pkt )
366 ? 32.0/27.0 // 16:9 NTSC
367 : 8.0/9.0; // 4:3 NTSC
373 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
374 stream->sample_aspect_ratio;
376 codec_context->sample_aspect_ratio;
378 // Override FFmpeg's notion of DV aspect ratios, which are
379 // based upon a width of 704. Since we do not have a normaliser
380 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
381 // we just coerce the values to facilitate a passive behaviour through
382 // the rescale normaliser when using equivalent producers and consumers.
383 // = display_aspect / (width * height)
384 if ( ar.num == 10 && ar.den == 11 )
385 aspect_ratio = 8.0/9.0; // 4:3 NTSC
386 else if ( ar.num == 59 && ar.den == 54 )
387 aspect_ratio = 16.0/15.0; // 4:3 PAL
388 else if ( ar.num == 40 && ar.den == 33 )
389 aspect_ratio = 32.0/27.0; // 16:9 NTSC
390 else if ( ar.num == 118 && ar.den == 81 )
391 aspect_ratio = 64.0/45.0; // 16:9 PAL
396 AVRational codec_sar = codec_context->sample_aspect_ratio;
397 AVRational stream_sar =
398 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
399 stream->sample_aspect_ratio;
403 if ( codec_sar.num > 0 )
404 aspect_ratio = av_q2d( codec_sar );
405 else if ( stream_sar.num > 0 )
406 aspect_ratio = av_q2d( stream_sar );
414 static int producer_open( producer_avformat this, mlt_profile profile, char *file )
416 // Return an error code (0 == no error)
419 // Context for avformat
420 AVFormatContext *context = NULL;
422 // Get the properties
423 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this->parent );
425 // We will treat everything with the producer fps
426 double fps = mlt_profile_fps( profile );
428 // Lock the mutex now
431 // If "MRL", then create AVInputFormat
432 AVInputFormat *format = NULL;
433 AVFormatParameters *params = NULL;
434 char *standard = NULL;
435 char *mrl = strchr( file, ':' );
437 // AV option (0 = both, 1 = video, 2 = audio)
440 // Only if there is not a protocol specification that avformat can handle
441 if ( mrl && !url_exist( file ) )
443 // 'file' becomes format abbreviation
447 format = av_find_input_format( file );
449 // Eat the format designator
455 params = calloc( sizeof( AVFormatParameters ), 1 );
457 // These are required by video4linux (defaults)
459 params->height = 480;
460 params->time_base= (AVRational){1,25};
461 // params->device = file;
462 params->channels = 2;
463 params->sample_rate = 48000;
466 // XXX: this does not work anymore since avdevice
467 // TODO: make producer_avddevice?
469 mrl = strchr( file, '?' );
473 char *name = strdup( ++mrl );
474 char *value = strchr( name, ':' );
479 char *t = strchr( value, '&' );
482 if ( !strcmp( name, "frame_rate" ) )
483 params->time_base.den = atoi( value );
484 else if ( !strcmp( name, "frame_rate_base" ) )
485 params->time_base.num = atoi( value );
486 else if ( !strcmp( name, "sample_rate" ) )
487 params->sample_rate = atoi( value );
488 else if ( !strcmp( name, "channels" ) )
489 params->channels = atoi( value );
490 else if ( !strcmp( name, "width" ) )
491 params->width = atoi( value );
492 else if ( !strcmp( name, "height" ) )
493 params->height = atoi( value );
494 else if ( !strcmp( name, "standard" ) )
496 standard = strdup( value );
497 params->standard = standard;
499 else if ( !strcmp( name, "av" ) )
503 mrl = strchr( mrl, '&' );
507 // Now attempt to open the file
508 error = av_open_input_file( &context, file, format, 0, params ) < 0;
510 // Cleanup AVFormatParameters
514 // If successful, then try to get additional info
517 // Get the stream info
518 error = av_find_stream_info( context ) < 0;
520 // Continue if no error
523 // We will default to the first audio and video streams found
524 int audio_index = -1;
525 int video_index = -1;
527 // Now set properties where we can (use default unknowns if required)
528 if ( context->duration != AV_NOPTS_VALUE )
530 // This isn't going to be accurate for all formats
531 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + 0.5 );
532 mlt_properties_set_position( properties, "out", frames - 1 );
533 mlt_properties_set_position( properties, "length", frames );
536 // Find default audio and video streams
537 find_default_streams( properties, context, &audio_index, &video_index );
539 if ( context->start_time != AV_NOPTS_VALUE )
540 this->start_time = context->start_time;
542 // Check if we're seekable (something funny about mpeg here :-/)
543 if ( strncmp( file, "pipe:", 5 ) &&
544 strncmp( file, "http:", 5 ) &&
545 strncmp( file, "udp:", 4 ) &&
546 strncmp( file, "tcp:", 4 ) &&
547 strncmp( file, "rtsp:", 5 ) &&
548 strncmp( file, "rtp:", 4 ) )
550 this->seekable = av_seek_frame( context, -1, this->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
551 mlt_properties_set_int( properties, "seekable", this->seekable );
552 producer_format_close( this->dummy_context );
553 this->dummy_context = context;
554 av_open_input_file( &context, file, NULL, 0, NULL );
555 av_find_stream_info( context );
558 // Store selected audio and video indexes on properties
559 this->audio_index = audio_index;
560 this->video_index = video_index;
561 this->first_pts = -1;
562 this->last_position = POSITION_INITIAL;
564 // Fetch the width, height and aspect ratio
565 if ( video_index != -1 )
567 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
568 mlt_properties_set_int( properties, "width", codec_context->width );
569 mlt_properties_set_int( properties, "height", codec_context->height );
571 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
573 // Fetch the first frame of DV so we can read it directly
578 ret = av_read_frame( context, &pkt );
579 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
581 mlt_properties_set_double( properties, "aspect_ratio",
582 get_aspect_ratio( context->streams[ video_index ], codec_context, &pkt ) );
589 mlt_properties_set_double( properties, "aspect_ratio",
590 get_aspect_ratio( context->streams[ video_index ], codec_context, NULL ) );
595 if ( context->title )
596 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
597 if ( context->author )
598 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
599 if ( context->copyright )
600 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
601 if ( context->comment )
602 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
603 if ( context->album )
604 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
606 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
607 if ( context->track )
608 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
610 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
611 if ( av == 0 && audio_index != -1 && video_index != -1 )
613 // We'll use the open one as our video_format
615 producer_format_close( this->video_format );
617 this->video_format = context;
619 // And open again for our audio context
620 av_open_input_file( &context, file, NULL, 0, NULL );
621 av_find_stream_info( context );
625 producer_format_close( this->audio_format );
627 this->audio_format = context;
629 else if ( av != 2 && video_index != -1 )
631 // We only have a video context
633 producer_format_close( this->video_format );
635 this->video_format = context;
637 else if ( audio_index != -1 )
639 // We only have an audio context
641 producer_format_close( this->audio_format );
643 this->audio_format = context;
647 // Something has gone wrong
653 // Unlock the mutex now
659 /** Convert a frame position to a time code.
662 static double producer_time_of_frame( mlt_producer this, mlt_position position )
664 return ( double )position / mlt_producer_get_fps( this );
667 // Collect information about all audio streams
669 static void get_audio_streams_info( producer_avformat this )
671 // Fetch the audio format context
672 AVFormatContext *context = this->audio_format;
676 i < context->nb_streams;
679 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
681 AVCodecContext *codec_context = context->streams[i]->codec;
682 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
684 // If we don't have a codec and we can't initialise it, we can't do much more...
686 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
688 this->audio_streams++;
689 this->audio_max_stream = i;
690 this->total_channels += codec_context->channels;
691 if ( codec_context->channels > this->max_channel )
692 this->max_channel = codec_context->channels;
693 if ( codec_context->sample_rate > this->max_frequency )
694 this->max_frequency = codec_context->sample_rate;
695 avcodec_close( codec_context );
700 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
701 this->audio_streams, this->audio_max_stream, this->total_channels, this->max_channel );
703 // Other audio-specific initializations
704 this->resample_factor = 1.0;
707 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format *format, int width, int height )
710 if ( pix_fmt == PIX_FMT_RGB32 )
712 *format = mlt_image_rgb24a;
713 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
714 width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
716 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
717 sws_scale( context, frame->data, frame->linesize, 0, height,
718 output.data, output.linesize);
719 sws_freeContext( context );
721 else if ( *format == mlt_image_yuv420p )
723 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
724 width, height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
726 output.data[0] = buffer;
727 output.data[1] = buffer + width * height;
728 output.data[2] = buffer + ( 5 * width * height ) / 4;
729 output.linesize[0] = width;
730 output.linesize[1] = width >> 1;
731 output.linesize[2] = width >> 1;
732 sws_scale( context, frame->data, frame->linesize, 0, height,
733 output.data, output.linesize);
734 sws_freeContext( context );
736 else if ( *format == mlt_image_rgb24 )
738 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
739 width, height, PIX_FMT_RGB24, SWS_FAST_BILINEAR, NULL, NULL, NULL);
741 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
742 sws_scale( context, frame->data, frame->linesize, 0, height,
743 output.data, output.linesize);
744 sws_freeContext( context );
746 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
748 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
749 width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
751 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
752 sws_scale( context, frame->data, frame->linesize, 0, height,
753 output.data, output.linesize);
754 sws_freeContext( context );
758 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
759 width, height, PIX_FMT_YUYV422, SWS_FAST_BILINEAR, NULL, NULL, NULL);
761 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
762 sws_scale( context, frame->data, frame->linesize, 0, height,
763 output.data, output.linesize);
764 sws_freeContext( context );
767 if ( *format == mlt_image_yuv420p )
770 pict.data[0] = buffer;
771 pict.data[1] = buffer + width * height;
772 pict.data[2] = buffer + ( 5 * width * height ) / 4;
773 pict.linesize[0] = width;
774 pict.linesize[1] = width >> 1;
775 pict.linesize[2] = width >> 1;
776 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
778 else if ( *format == mlt_image_rgb24 )
781 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
782 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
784 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
787 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
788 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
793 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
794 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
799 /** Allocate the image buffer and set it on the frame.
802 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
806 if ( codec_context->width == 0 || codec_context->height == 0 )
809 *width = codec_context->width;
810 *height = codec_context->height;
811 mlt_properties_set_int( frame_properties, "width", *width );
812 mlt_properties_set_int( frame_properties, "height", *height );
814 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
815 size = *width * ( *height + 1 ) * 4;
816 else switch ( *format )
818 case mlt_image_yuv420p:
819 size = *width * 3 * ( *height + 1 ) / 2;
821 case mlt_image_rgb24:
822 size = *width * ( *height + 1 ) * 3;
824 case mlt_image_rgb24a:
825 case mlt_image_opengl:
826 size = *width * ( *height + 1 ) * 4;
829 *format = mlt_image_yuv422;
830 size = *width * ( *height + 1 ) * 2;
834 // Construct the output image
835 *buffer = mlt_pool_alloc( size );
837 mlt_properties_set_data( frame_properties, "image", *buffer, size, mlt_pool_release, NULL );
844 /** Get an image from a frame.
847 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
850 producer_avformat this = mlt_frame_pop_service( frame );
851 mlt_producer producer = this->parent;
853 // Get the properties from the frame
854 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
856 // Obtain the frame number of this frame
857 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
859 // Get the producer properties
860 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
864 // Fetch the video format context
865 AVFormatContext *context = this->video_format;
867 // Get the video stream
868 AVStream *stream = context->streams[ this->video_index ];
871 AVCodecContext *codec_context = stream->codec;
876 // Special case pause handling flag
879 // Special case ffwd handling
882 // We may want to use the source fps if available
883 double source_fps = mlt_properties_get_double( properties, "source_fps" );
884 double fps = mlt_producer_get_fps( producer );
886 // This is the physical frame position in the source
887 int req_position = ( int )( position / fps * source_fps + 0.5 );
889 // Determines if we have to decode all frames in a sequence
890 // Temporary hack to improve intra frame only
891 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
892 strcmp( codec_context->codec->name, "dvvideo" ) &&
893 strcmp( codec_context->codec->name, "huffyuv" ) &&
894 strcmp( codec_context->codec->name, "mjpeg" ) &&
895 strcmp( codec_context->codec->name, "rawvideo" );
897 int last_position = this->last_position;
899 // Turn on usage of new seek API and PTS for seeking
900 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
901 if ( mlt_properties_get( properties, "new_seek" ) )
902 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
905 if ( position != this->video_expected || last_position < 0 )
907 if ( this->av_frame && position + 1 == this->video_expected )
909 // We're paused - use last image
912 else if ( !this->seekable && position > this->video_expected && ( position - this->video_expected ) < 250 )
914 // Fast forward - seeking is inefficient for small distances - just ignore following frames
915 ignore = ( int )( ( position - this->video_expected ) / fps * source_fps );
916 codec_context->skip_loop_filter = AVDISCARD_NONREF;
918 else if ( this->seekable && ( position < this->video_expected || position - this->video_expected >= 12 || last_position < 0 ) )
920 if ( use_new_seek && last_position == POSITION_INITIAL )
922 // find first key frame
926 while ( ret >= 0 && toscan-- > 0 )
928 ret = av_read_frame( context, &pkt );
929 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == this->video_index )
931 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "first_pts %lld dts %lld pts_dts_delta %d\n", pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
932 this->first_pts = pkt.pts;
935 av_free_packet( &pkt );
938 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
941 // Calculate the timestamp for the requested frame
945 timestamp = ( req_position - 0.1 / source_fps ) /
946 ( av_q2d( stream->time_base ) * source_fps );
947 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
948 if ( this->first_pts > 0 )
949 timestamp += this->first_pts;
950 else if ( context->start_time != AV_NOPTS_VALUE )
951 timestamp += context->start_time;
955 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
956 if ( context->start_time != AV_NOPTS_VALUE )
957 timestamp += context->start_time;
960 timestamp -= AV_TIME_BASE;
963 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
964 timestamp, position, this->video_expected, last_position );
966 // Seek to the timestamp
969 codec_context->skip_loop_filter = AVDISCARD_NONREF;
970 av_seek_frame( context, this->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
974 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
977 // Remove the cached info relating to the previous position
978 this->current_position = POSITION_INVALID;
979 this->last_position = POSITION_INVALID;
980 av_freep( &this->av_frame );
984 // flush any pictures still in decode buffer
985 avcodec_flush_buffers( codec_context );
990 // Duplicate the last image if necessary (see comment on rawvideo below)
991 if ( this->av_frame && this->got_picture && this->seekable
993 || this->current_position == req_position
994 || ( !use_new_seek && this->current_position > req_position ) ) )
997 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
999 if ( this->vdpau && this->vdpau->buffer )
1002 picture.data[0] = this->vdpau->buffer;
1003 picture.data[2] = this->vdpau->buffer + codec_context->width * codec_context->height;
1004 picture.data[1] = this->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1005 picture.linesize[0] = codec_context->width;
1006 picture.linesize[1] = codec_context->width / 2;
1007 picture.linesize[2] = codec_context->width / 2;
1008 convert_image( (AVFrame*) &picture, *buffer, PIX_FMT_YUV420P, format, *width, *height );
1012 convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1014 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1019 int int_position = 0;
1020 int decode_errors = 0;
1021 int got_picture = 0;
1023 av_init_packet( &pkt );
1025 // Construct an AVFrame for YUV422 conversion
1026 if ( !this->av_frame )
1027 this->av_frame = avcodec_alloc_frame( );
1029 while( ret >= 0 && !got_picture )
1032 ret = av_read_frame( context, &pkt );
1034 // We only deal with video from the selected video_index
1035 if ( ret >= 0 && pkt.stream_index == this->video_index && pkt.size > 0 )
1037 // Determine time code of the packet
1040 int64_t pts = pkt.pts;
1041 if ( this->first_pts > 0 )
1042 pts -= this->first_pts;
1043 else if ( context->start_time != AV_NOPTS_VALUE )
1044 pts -= context->start_time;
1045 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1046 if ( pkt.pts == AV_NOPTS_VALUE )
1048 this->invalid_pts_counter++;
1049 if ( this->invalid_pts_counter > 20 )
1051 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1052 mlt_properties_set_int( properties, "new_seek", 0 );
1053 int_position = req_position;
1059 this->invalid_pts_counter = 0;
1061 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1062 pkt.pts, req_position, this->current_position, int_position );
1066 if ( pkt.dts != AV_NOPTS_VALUE )
1068 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1069 if ( context->start_time != AV_NOPTS_VALUE )
1070 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1071 last_position = this->last_position;
1072 if ( int_position == last_position )
1073 int_position = last_position + 1;
1077 int_position = req_position;
1079 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1080 pkt.dts, req_position, this->current_position, int_position );
1081 // Make a dumb assumption on streams that contain wild timestamps
1082 if ( abs( req_position - int_position ) > 999 )
1084 int_position = req_position;
1085 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1088 this->last_position = int_position;
1091 if ( must_decode || int_position >= req_position )
1094 if ( g_vdpau && this->vdpau )
1096 if ( g_vdpau->producer != this )
1098 vdpau_decoder_close();
1099 vdpau_decoder_init( this );
1102 this->vdpau->is_decoded = 0;
1105 codec_context->reordered_opaque = pkt.pts;
1106 if ( int_position >= req_position )
1107 codec_context->skip_loop_filter = AVDISCARD_NONE;
1108 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1109 ret = avcodec_decode_video2( codec_context, this->av_frame, &got_picture, &pkt );
1111 ret = avcodec_decode_video( codec_context, this->av_frame, &got_picture, pkt.data, pkt.size );
1113 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1116 if ( ++decode_errors <= 10 )
1129 // Determine time code of the packet
1130 int64_t pts = this->av_frame->reordered_opaque;
1131 if ( this->first_pts > 0 )
1132 pts -= this->first_pts;
1133 else if ( context->start_time != AV_NOPTS_VALUE )
1134 pts -= context->start_time;
1135 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1136 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, this->av_frame->key_frame );
1139 if ( int_position < req_position )
1144 else if ( int_position >= req_position )
1147 codec_context->skip_loop_filter = AVDISCARD_NONE;
1149 else if ( ignore -- )
1154 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1155 av_free_packet( &pkt );
1157 else if ( ret >= 0 )
1159 av_free_packet( &pkt );
1162 // Now handle the picture if we have one
1165 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
1170 if ( this->vdpau->is_decoded )
1172 struct vdpau_render_state *render = (struct vdpau_render_state*) this->av_frame->data[0];
1174 uint32_t pitches[3];
1175 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1178 if ( !this->vdpau->buffer )
1179 this->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1180 picture.data[0] = planes[0] = this->vdpau->buffer;
1181 picture.data[2] = planes[1] = this->vdpau->buffer + codec_context->width * codec_context->height;
1182 picture.data[1] = planes[2] = this->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1183 picture.linesize[0] = pitches[0] = codec_context->width;
1184 picture.linesize[1] = pitches[1] = codec_context->width / 2;
1185 picture.linesize[2] = pitches[2] = codec_context->width / 2;
1187 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1188 if ( status == VDP_STATUS_OK )
1190 convert_image( (AVFrame*) &picture, *buffer, PIX_FMT_YUV420P, format, *width, *height );
1194 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1195 this->vdpau->is_decoded = 0;
1200 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1206 convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1207 if ( !mlt_properties_get( properties, "force_progressive" ) )
1208 mlt_properties_set_int( frame_properties, "progressive", !this->av_frame->interlaced_frame );
1209 this->top_field_first |= this->av_frame->top_field_first;
1210 this->current_position = int_position;
1211 this->got_picture = 1;
1220 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1223 // Very untidy - for rawvideo, the packet contains the frame, hence the free packet
1224 // above will break the pause behaviour - so we wipe the frame now
1225 if ( !strcmp( codec_context->codec->name, "rawvideo" ) )
1226 av_freep( &this->av_frame );
1230 // Set the field order property for this frame
1231 mlt_properties_set_int( frame_properties, "top_field_first", this->top_field_first );
1233 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1234 this->video_expected = position + 1;
1239 /** Process properties as AVOptions and apply to AV context obj
1242 static void apply_properties( void *obj, mlt_properties properties, int flags )
1245 int count = mlt_properties_count( properties );
1246 for ( i = 0; i < count; i++ )
1248 const char *opt_name = mlt_properties_get_name( properties, i );
1249 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1251 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1252 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1253 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1254 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1256 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1261 /** Initialize the video codec context.
1264 static int video_codec_init( producer_avformat this, int index, mlt_properties properties )
1266 // Initialise the codec if necessary
1267 if ( !this->video_codec )
1269 // Get the video stream
1270 AVStream *stream = this->video_format->streams[ index ];
1272 // Get codec context
1273 AVCodecContext *codec_context = stream->codec;
1276 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1278 if ( codec_context->codec_id == CODEC_ID_H264 )
1280 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1282 if ( vdpau_init( this ) )
1284 this->video_codec = codec_context;
1285 if ( !vdpau_decoder_init( this ) )
1286 vdpau_decoder_close();
1290 codec = avcodec_find_decoder( codec_context->codec_id );
1294 // Initialise multi-threading
1295 int thread_count = mlt_properties_get_int( properties, "threads" );
1296 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1297 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1298 if ( thread_count > 1 )
1300 avcodec_thread_init( codec_context, thread_count );
1301 codec_context->thread_count = thread_count;
1304 // If we don't have a codec and we can't initialise it, we can't do much more...
1306 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1308 // Now store the codec with its destructor
1309 this->video_codec = codec_context;
1313 // Remember that we can't use this later
1314 this->video_index = -1;
1318 // Process properties as AVOptions
1319 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1321 // Reset some image properties
1322 mlt_properties_set_int( properties, "width", this->video_codec->width );
1323 mlt_properties_set_int( properties, "height", this->video_codec->height );
1324 mlt_properties_set_double( properties, "aspect_ratio", get_aspect_ratio( stream, this->video_codec, NULL ) );
1326 // Determine the fps first from the codec
1327 double source_fps = (double) this->video_codec->time_base.den /
1328 ( this->video_codec->time_base.num == 0 ? 1 : this->video_codec->time_base.num );
1330 if ( mlt_properties_get( properties, "force_fps" ) )
1332 source_fps = mlt_properties_get_double( properties, "force_fps" );
1333 stream->time_base = av_d2q( source_fps, 255 );
1337 // If the muxer reports a frame rate different than the codec
1338 double muxer_fps = av_q2d( stream->r_frame_rate );
1339 // Choose the lesser - the wrong tends to be off by some multiple of 10
1340 source_fps = FFMIN( source_fps, muxer_fps );
1343 // We'll use fps if it's available
1344 if ( source_fps > 0 )
1345 mlt_properties_set_double( properties, "source_fps", source_fps );
1347 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( this->parent ) );
1349 return this->video_codec && this->video_index > -1;
1352 /** Set up video handling.
1355 static void producer_set_up_video( producer_avformat this, mlt_frame frame )
1358 mlt_producer producer = this->parent;
1360 // Get the properties
1361 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1363 // Fetch the video format context
1364 AVFormatContext *context = this->video_format;
1366 // Get the video_index
1367 int index = mlt_properties_get_int( properties, "video_index" );
1369 // Reopen the file if necessary
1370 if ( !context && index > -1 )
1372 mlt_events_block( properties, producer );
1373 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1374 mlt_properties_get( properties, "resource" ) );
1375 context = this->video_format;
1376 producer_format_close( this->dummy_context );
1377 this->dummy_context = NULL;
1378 mlt_events_unblock( properties, producer );
1379 if ( this->audio_format )
1380 get_audio_streams_info( this );
1382 // Process properties as AVOptions
1383 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1386 // Exception handling for video_index
1387 if ( context && index >= (int) context->nb_streams )
1389 // Get the last video stream
1390 for ( index = context->nb_streams - 1;
1391 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1393 mlt_properties_set_int( properties, "video_index", index );
1395 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1397 // Invalidate the video stream
1399 mlt_properties_set_int( properties, "video_index", index );
1402 // Update the video properties if the index changed
1403 if ( index != this->video_index )
1405 // Reset the video properties if the index changed
1406 this->video_index = index;
1407 producer_codec_close( this->video_codec );
1408 this->video_codec = NULL;
1411 // Get the frame properties
1412 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1415 if ( context && index > -1 && video_codec_init( this, index, properties ) )
1417 // Set the frame properties
1418 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1419 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1420 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1422 // Set the width and height
1423 mlt_properties_set_int( frame_properties, "width", this->video_codec->width );
1424 mlt_properties_set_int( frame_properties, "height", this->video_codec->height );
1425 mlt_properties_set_int( frame_properties, "real_width", this->video_codec->width );
1426 mlt_properties_set_int( frame_properties, "real_height", this->video_codec->height );
1427 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1428 if ( mlt_properties_get( properties, "force_progressive" ) )
1429 mlt_properties_set_int( frame_properties, "progressive", mlt_properties_get_int( properties, "force_progressive" ) );
1431 // Add our image operation
1432 mlt_frame_push_service( frame, this );
1433 mlt_frame_push_get_image( frame, producer_get_image );
1437 // If something failed, use test card image
1438 mlt_properties_set_int( frame_properties, "test_image", 1 );
1442 static int seek_audio( producer_avformat this, mlt_position position, double timecode, int *ignore )
1446 // Fetch the audio_format
1447 AVFormatContext *context = this->audio_format;
1449 // Seek if necessary
1450 if ( position != this->audio_expected )
1452 if ( position + 1 == this->audio_expected )
1454 // We're paused - silence required
1457 else if ( !this->seekable && position > this->audio_expected && ( position - this->audio_expected ) < 250 )
1459 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1460 *ignore = position - this->audio_expected;
1462 else if ( position < this->audio_expected || position - this->audio_expected >= 12 )
1464 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1465 if ( context->start_time != AV_NOPTS_VALUE )
1466 timestamp += context->start_time;
1467 if ( timestamp < 0 )
1470 // Set to the real timecode
1471 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1474 // Clear the usage in the audio buffer
1475 int i = MAX_AUDIO_STREAMS + 1;
1477 this->audio_used[i - 1] = 0;
1483 static int decode_audio( producer_avformat this, int *ignore, AVPacket *pkt, int channels, int samples, double timecode, double source_fps )
1485 // Fetch the audio_format
1486 AVFormatContext *context = this->audio_format;
1488 // Get the current stream index
1489 int index = pkt->stream_index;
1491 // Get codec context
1492 AVCodecContext *codec_context = this->audio_codec[ index ];
1494 // Obtain the resample context if it exists (not always needed)
1495 ReSampleContext *resample = this->audio_resample[ index ];
1497 // Obtain the audio buffers
1498 int16_t *audio_buffer = this->audio_buffer[ index ];
1499 int16_t *decode_buffer = this->decode_buffer[ index ];
1501 int audio_used = this->audio_used[ index ];
1502 uint8_t *ptr = pkt->data;
1503 int len = pkt->size;
1506 while ( ptr && ret >= 0 && len > 0 )
1508 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1511 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1512 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, pkt );
1513 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1514 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1516 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1527 // If decoded successfully
1528 if ( data_size > 0 )
1530 // Figure out how many samples will be needed after resampling
1531 int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1532 int samples_needed = this->resample_factor * convert_samples + 1;
1534 // Resize audio buffer to prevent overflow
1535 if ( audio_used * channels + samples_needed > this->audio_buffer_size[ index ] )
1537 this->audio_buffer_size[ index ] *= 2;
1538 audio_buffer = this->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, this->audio_buffer_size[ index ] * sizeof(int16_t) );
1542 // Copy to audio buffer while resampling
1543 int16_t *source = decode_buffer;
1544 int16_t *dest = &audio_buffer[ audio_used * channels ];
1545 audio_used += audio_resample( resample, dest, source, convert_samples );
1549 // Straight copy to audio buffer
1550 memcpy( &audio_buffer[ audio_used * codec_context->channels ], decode_buffer, data_size );
1551 audio_used += convert_samples;
1555 while ( *ignore && audio_used > samples )
1558 audio_used -= samples;
1559 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) ],
1560 audio_used * sizeof( int16_t ) );
1565 // If we're behind, ignore this packet
1566 if ( pkt->pts >= 0 )
1568 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt->pts;
1569 int req_position = ( int )( timecode * source_fps + 0.5 );
1570 int int_position = ( int )( current_pts * source_fps + 0.5 );
1572 if ( context->start_time != AV_NOPTS_VALUE )
1573 int_position -= ( int )( source_fps * context->start_time / AV_TIME_BASE + 0.5 );
1574 if ( this->seekable && *ignore == 0 && int_position < req_position )
1578 this->audio_used[ index ] = audio_used;
1583 /** Get the audio from a frame.
1586 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1589 producer_avformat this = mlt_frame_pop_audio( frame );
1591 // Obtain the frame number of this frame
1592 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1594 // Calculate the real time code
1595 double real_timecode = producer_time_of_frame( this->parent, position );
1597 // Get the source fps
1598 double source_fps = mlt_properties_get_double( MLT_PRODUCER_PROPERTIES( this->parent ), "source_fps" );
1600 // Number of frames to ignore (for ffwd)
1603 // Flag for paused (silence)
1604 int paused = seek_audio( this, position, real_timecode, &ignore );
1606 // Fetch the audio_format
1607 AVFormatContext *context = this->audio_format;
1609 // Determine the tracks to use
1610 int index = this->audio_index;
1611 int index_max = this->audio_index + 1;
1612 if ( this->audio_index == INT_MAX )
1615 index_max = context->nb_streams;
1616 *channels = this->total_channels;
1617 *frequency = this->max_frequency;
1620 // Initialize the resamplers and buffers
1621 for ( ; index < index_max; index++ )
1623 // Get codec context
1624 AVCodecContext *codec_context = this->audio_codec[ index ];
1626 if ( codec_context && !this->audio_buffer[ index ] )
1628 // Check for resample and create if necessary
1629 if ( codec_context->channels <= 2 )
1631 // Determine by how much resampling will increase number of samples
1632 double resample_factor = this->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
1633 resample_factor *= (double) *frequency / codec_context->sample_rate;
1634 if ( resample_factor > this->resample_factor )
1635 this->resample_factor = resample_factor;
1637 // Create the resampler
1638 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1639 this->audio_resample[ index ] = av_audio_resample_init(
1640 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1641 codec_context->channels, *frequency, codec_context->sample_rate,
1642 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1644 this->audio_resample[ index ] = audio_resample_init(
1645 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1646 codec_context->channels, *frequency, codec_context->sample_rate );
1651 codec_context->request_channels = this->audio_index == INT_MAX ? codec_context->channels : *channels;
1654 // Check for audio buffer and create if necessary
1655 this->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1656 this->audio_buffer[ index ] = mlt_pool_alloc( this->audio_buffer_size[ index ] * sizeof( int16_t ) );
1658 // Check for decoder buffer and create if necessary
1659 this->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1663 // Get the audio if required
1670 av_init_packet( &pkt );
1672 while ( ret >= 0 && !got_audio )
1674 // Check if the buffer already contains the samples required
1675 if ( this->audio_index != INT_MAX && this->audio_used[ this->audio_index ] >= *samples && ignore == 0 )
1682 ret = av_read_frame( context, &pkt );
1684 // We only deal with audio from the selected audio index
1685 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == this->audio_index ||
1686 ( this->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
1687 ret = decode_audio( this, &ignore, &pkt, *channels, *samples, real_timecode, source_fps );
1688 av_free_packet( &pkt );
1690 if ( this->audio_index == INT_MAX && ret >= 0 )
1692 // Determine if there is enough audio for all streams
1694 for ( index = 0; index < context->nb_streams; index++ )
1696 if ( this->audio_codec[ index ] && this->audio_used[ index ] < *samples )
1702 // Allocate and set the frame's audio buffer
1703 int size = *samples * *channels * sizeof(int16_t);
1704 *buffer = mlt_pool_alloc( size );
1705 *format = mlt_audio_s16;
1706 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
1708 // Interleave tracks if audio_index=all
1709 if ( this->audio_index == INT_MAX )
1711 int16_t *dest = *buffer;
1713 for ( i = 0; i < *samples; i++ )
1715 for ( index = 0; index < index_max; index++ )
1716 if ( this->audio_codec[ index ] )
1718 int current_channels = this->audio_codec[ index ]->channels;
1719 int16_t *src = this->audio_buffer[ index ] + i * current_channels;
1720 memcpy( dest, src, current_channels * sizeof(int16_t) );
1721 dest += current_channels;
1724 for ( index = 0; index < index_max; index++ )
1725 if ( this->audio_codec[ index ] )
1727 int current_channels = this->audio_codec[ index ]->channels;
1728 int16_t *src = this->audio_buffer[ index ] + *samples * current_channels;
1729 this->audio_used[index] -= *samples;
1730 memmove( this->audio_buffer[ index ], src, this->audio_used[ index ] * current_channels * sizeof(int16_t) );
1733 // Copy a single track to the output buffer
1736 index = this->audio_index;
1738 // Now handle the audio if we have enough
1739 if ( this->audio_used[ index ] >= *samples )
1741 int16_t *src = this->audio_buffer[ index ];
1742 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
1743 this->audio_used[ index ] -= *samples;
1744 memmove( src, &src[ *samples * *channels ], this->audio_used[ index ] * *channels * sizeof(int16_t) );
1748 // Otherwise fill with silence
1749 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
1751 if ( !this->audio_resample[ index ] )
1753 // TODO: uncomment and remove following line when full multi-channel support is ready
1754 // *channels = codec_context->channels;
1755 *frequency = this->audio_codec[ index ]->sample_rate;
1761 // Get silence and don't touch the context
1762 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1765 // Regardless of speed (other than paused), we expect to get the next frame
1767 this->audio_expected = position + 1;
1772 /** Initialize the audio codec context.
1775 static int audio_codec_init( producer_avformat this, int index, mlt_properties properties )
1777 // Initialise the codec if necessary
1778 if ( !this->audio_codec[ index ] )
1780 // Get codec context
1781 AVCodecContext *codec_context = this->audio_format->streams[index]->codec;
1784 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1786 // If we don't have a codec and we can't initialise it, we can't do much more...
1788 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1790 // Now store the codec with its destructor
1792 producer_codec_close( this->audio_codec[index] );
1793 this->audio_codec[ index ] = codec_context;
1797 // Remember that we can't use this later
1798 this->audio_index = -1;
1802 // Process properties as AVOptions
1803 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1805 return this->audio_codec[ index ] && this->audio_index > -1;
1808 /** Set up audio handling.
1811 static void producer_set_up_audio( producer_avformat this, mlt_frame frame )
1814 mlt_producer producer = this->parent;
1816 // Get the properties
1817 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1819 // Fetch the audio format context
1820 AVFormatContext *context = this->audio_format;
1822 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1824 // Get the audio_index
1825 int index = mlt_properties_get_int( properties, "audio_index" );
1827 // Handle all audio tracks
1828 if ( mlt_properties_get( properties, "audio_index" ) &&
1829 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
1832 // Reopen the file if necessary
1833 if ( !context && index > -1 )
1835 mlt_events_block( properties, producer );
1836 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1837 mlt_properties_get( properties, "resource" ) );
1838 context = this->audio_format;
1839 producer_format_close( this->dummy_context );
1840 this->dummy_context = NULL;
1841 mlt_events_unblock( properties, producer );
1842 get_audio_streams_info( this );
1845 // Exception handling for audio_index
1846 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
1848 for ( index = context->nb_streams - 1;
1849 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
1851 mlt_properties_set_int( properties, "audio_index", index );
1853 if ( context && index > -1 && index < INT_MAX &&
1854 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1857 mlt_properties_set_int( properties, "audio_index", index );
1860 // Update the audio properties if the index changed
1861 if ( index > -1 && index != this->audio_index )
1863 producer_codec_close( this->audio_codec[ this->audio_index ] );
1864 this->audio_codec[ this->audio_index ] = NULL;
1866 this->audio_index = index;
1869 if ( context && index == INT_MAX )
1871 mlt_properties_set_int( frame_properties, "frequency", this->max_frequency );
1872 mlt_properties_set_int( frame_properties, "channels", this->total_channels );
1873 for ( index = 0; index < context->nb_streams; index++ )
1875 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
1876 audio_codec_init( this, index, properties );
1879 else if ( context && index > -1 && audio_codec_init( this, index, properties ) )
1881 // Set the frame properties
1882 if ( index < INT_MAX )
1884 mlt_properties_set_int( frame_properties, "frequency", this->audio_codec[ index ]->sample_rate );
1885 mlt_properties_set_int( frame_properties, "channels", this->audio_codec[ index ]->channels );
1888 if ( context && index > -1 )
1890 // Add our audio operation
1891 mlt_frame_push_audio( frame, this );
1892 mlt_frame_push_audio( frame, producer_get_audio );
1896 /** Our get frame implementation.
1899 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
1901 // Access the private data
1902 mlt_cache_item cache_item = mlt_service_cache_get( MLT_PRODUCER_SERVICE(producer), "producer_avformat" );
1903 producer_avformat this = mlt_cache_item_data( cache_item, NULL );
1905 // Create an empty frame
1906 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE( producer ) );
1909 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
1911 mlt_cache_item_close( cache_item );
1913 // Update timecode on the frame we're creating
1914 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
1916 // Set the position of this producer
1917 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
1922 this = calloc( 1, sizeof( struct producer_avformat_s ) );
1923 producer->child = this;
1924 this->parent = producer;
1925 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
1929 producer_set_up_video( this, *frame );
1932 producer_set_up_audio( this, *frame );
1934 // Calculate the next timecode
1935 mlt_producer_prepare_next( producer );
1940 static void producer_avformat_close( producer_avformat this )
1942 mlt_log_debug( MLT_PRODUCER_SERVICE(this->parent), "producer_avformat_close\n" );
1944 av_free( this->av_frame );
1946 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1948 if ( this->audio_resample[i] )
1949 audio_resample_close( this->audio_resample[i] );
1950 mlt_pool_release( this->audio_buffer[i] );
1951 av_free( this->decode_buffer[i] );
1952 producer_codec_close( this->audio_codec[i] );
1954 producer_codec_close( this->video_codec );
1955 producer_format_close( this->dummy_context );
1956 producer_format_close( this->audio_format );
1957 producer_format_close( this->video_format );
1959 vdpau_producer_close( this );
1964 static void producer_close( mlt_producer parent )
1967 parent->close = NULL;
1968 mlt_producer_close( parent );