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>
26 #include <framework/mlt_log.h>
28 // ffmpeg Header files
34 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
35 # include "audioconvert.h"
38 // System header files
44 #if LIBAVUTIL_VERSION_INT < (50<<16)
45 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
46 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
49 #define POSITION_INITIAL (-2)
50 #define POSITION_INVALID (-1)
52 #define MAX_AUDIO_STREAMS (8)
54 void avformat_lock( );
55 void avformat_unlock( );
57 struct producer_avformat_s
59 struct mlt_producer_s parent;
60 AVFormatContext *dummy_context;
61 AVFormatContext *audio_format;
62 AVFormatContext *video_format;
63 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
64 AVCodecContext *video_codec;
66 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
67 mlt_position audio_expected;
68 mlt_position video_expected;
78 int16_t *audio_buffer[ MAX_AUDIO_STREAMS ];
79 int16_t *decode_buffer[ MAX_AUDIO_STREAMS ];
80 int audio_used[ MAX_AUDIO_STREAMS ];
87 typedef struct producer_avformat_s *producer_avformat;
89 // Forward references.
90 static int producer_open( producer_avformat this, mlt_profile profile, char *file );
91 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
92 static void producer_format_close( void *context );
93 static void producer_close( mlt_producer parent );
95 /** Constructor for libavformat.
98 mlt_producer producer_avformat_init( mlt_profile profile, char *file )
102 // Report information about available demuxers and codecs as YAML Tiny
103 if ( file && strstr( file, "f-list" ) )
105 fprintf( stderr, "---\nformats:\n" );
106 AVInputFormat *format = NULL;
107 while ( ( format = av_iformat_next( format ) ) )
108 fprintf( stderr, " - %s\n", format->name );
109 fprintf( stderr, "...\n" );
112 if ( file && strstr( file, "acodec-list" ) )
114 fprintf( stderr, "---\naudio_codecs:\n" );
115 AVCodec *codec = NULL;
116 while ( ( codec = av_codec_next( codec ) ) )
117 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
118 fprintf( stderr, " - %s\n", codec->name );
119 fprintf( stderr, "...\n" );
122 if ( file && strstr( file, "vcodec-list" ) )
124 fprintf( stderr, "---\nvideo_codecs:\n" );
125 AVCodec *codec = NULL;
126 while ( ( codec = av_codec_next( codec ) ) )
127 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
128 fprintf( stderr, " - %s\n", codec->name );
129 fprintf( stderr, "...\n" );
133 // Check that we have a non-NULL argument
136 // Construct the producer
137 producer_avformat this = calloc( 1, sizeof( struct producer_avformat_s ) );
140 if ( mlt_producer_init( &this->parent, this ) == 0 )
142 mlt_producer producer = &this->parent;
144 // Get the properties
145 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
147 // Set the resource property (required for all producers)
148 mlt_properties_set( properties, "resource", file );
150 // Register transport implementation with the producer
151 producer->close = (mlt_destructor) producer_close;
153 // Register our get_frame implementation
154 producer->get_frame = producer_get_frame;
157 if ( producer_open( this, profile, file ) != 0 )
160 mlt_producer_close( producer );
165 // Close the file to release resources for large playlists - reopen later as needed
166 producer_format_close( this->dummy_context );
167 this->dummy_context = NULL;
168 producer_format_close( this->audio_format );
169 this->audio_format = NULL;
170 producer_format_close( this->video_format );
171 this->video_format = NULL;
173 // Default the user-selectable indices from the auto-detected indices
174 mlt_properties_set_int( properties, "audio_index", this->audio_index );
175 mlt_properties_set_int( properties, "video_index", this->video_index );
183 /** Find the default streams.
186 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
191 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
193 // Allow for multiple audio and video streams in the file and select first of each (if available)
194 for( i = 0; i < context->nb_streams; i++ )
196 // Get the codec context
197 AVStream *stream = context->streams[ i ];
198 if ( ! stream ) continue;
199 AVCodecContext *codec_context = stream->codec;
200 if ( ! codec_context ) continue;
201 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
202 if ( ! codec ) continue;
204 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
206 // Determine the type and obtain the first index of each type
207 switch( codec_context->codec_type )
209 case CODEC_TYPE_VIDEO:
210 if ( *video_index < 0 )
212 mlt_properties_set( meta_media, key, "video" );
213 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
214 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
215 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
216 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
217 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
219 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
220 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
221 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
222 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
224 case CODEC_TYPE_AUDIO:
225 if ( *audio_index < 0 )
227 mlt_properties_set( meta_media, key, "audio" );
228 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
229 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
230 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
232 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
233 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
234 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
235 mlt_properties_set_int( meta_media, key, codec_context->channels );
240 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
241 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
242 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
243 mlt_properties_set( meta_media, key, codec->name );
244 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
245 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
246 mlt_properties_set( meta_media, key, codec->long_name );
248 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
249 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
250 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
251 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
252 snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
253 mlt_properties_set_int( meta_media, key, codec_context->profile );
254 snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
255 mlt_properties_set_int( meta_media, key, codec_context->level );
261 /** Producer file destructor.
264 static void producer_format_close( void *context )
268 // Lock the mutex now
272 av_close_input_file( context );
274 // Unlock the mutex now
279 /** Producer file destructor.
282 static void producer_codec_close( void *codec )
286 // Lock the mutex now
290 avcodec_close( codec );
292 // Unlock the mutex now
297 static inline int dv_is_pal( AVPacket *pkt )
299 return pkt->data[3] & 0x80;
302 static int dv_is_wide( AVPacket *pkt )
304 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
306 for ( ; i < pkt->size; i += 5 /* packet size */ )
308 if ( pkt->data[ i ] == 0x61 )
310 uint8_t x = pkt->data[ i + 2 ] & 0x7;
311 return ( x == 2 ) || ( x == 7 );
317 static double get_aspect_ratio( AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
319 double aspect_ratio = 1.0;
321 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
325 if ( dv_is_pal( pkt ) )
327 aspect_ratio = dv_is_wide( pkt )
328 ? 64.0/45.0 // 16:9 PAL
329 : 16.0/15.0; // 4:3 PAL
333 aspect_ratio = dv_is_wide( pkt )
334 ? 32.0/27.0 // 16:9 NTSC
335 : 8.0/9.0; // 4:3 NTSC
341 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
342 stream->sample_aspect_ratio;
344 codec_context->sample_aspect_ratio;
346 // Override FFmpeg's notion of DV aspect ratios, which are
347 // based upon a width of 704. Since we do not have a normaliser
348 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
349 // we just coerce the values to facilitate a passive behaviour through
350 // the rescale normaliser when using equivalent producers and consumers.
351 // = display_aspect / (width * height)
352 if ( ar.num == 10 && ar.den == 11 )
353 aspect_ratio = 8.0/9.0; // 4:3 NTSC
354 else if ( ar.num == 59 && ar.den == 54 )
355 aspect_ratio = 16.0/15.0; // 4:3 PAL
356 else if ( ar.num == 40 && ar.den == 33 )
357 aspect_ratio = 32.0/27.0; // 16:9 NTSC
358 else if ( ar.num == 118 && ar.den == 81 )
359 aspect_ratio = 64.0/45.0; // 16:9 PAL
364 AVRational codec_sar = codec_context->sample_aspect_ratio;
365 AVRational stream_sar =
366 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
367 stream->sample_aspect_ratio;
371 if ( codec_sar.num > 0 )
372 aspect_ratio = av_q2d( codec_sar );
373 else if ( stream_sar.num > 0 )
374 aspect_ratio = av_q2d( stream_sar );
382 static int producer_open( producer_avformat this, mlt_profile profile, char *file )
384 // Return an error code (0 == no error)
387 // Context for avformat
388 AVFormatContext *context = NULL;
390 // Get the properties
391 mlt_properties properties = MLT_PRODUCER_PROPERTIES( &this->parent );
393 // We will treat everything with the producer fps
394 double fps = mlt_profile_fps( profile );
396 // Lock the mutex now
399 // If "MRL", then create AVInputFormat
400 AVInputFormat *format = NULL;
401 AVFormatParameters *params = NULL;
402 char *standard = NULL;
403 char *mrl = strchr( file, ':' );
405 // AV option (0 = both, 1 = video, 2 = audio)
408 // Only if there is not a protocol specification that avformat can handle
409 if ( mrl && !url_exist( file ) )
411 // 'file' becomes format abbreviation
415 format = av_find_input_format( file );
417 // Eat the format designator
423 params = calloc( sizeof( AVFormatParameters ), 1 );
425 // These are required by video4linux (defaults)
427 params->height = 480;
428 params->time_base= (AVRational){1,25};
429 // params->device = file;
430 params->channels = 2;
431 params->sample_rate = 48000;
434 // XXX: this does not work anymore since avdevice
435 // TODO: make producer_avddevice?
437 mrl = strchr( file, '?' );
441 char *name = strdup( ++mrl );
442 char *value = strchr( name, ':' );
447 char *t = strchr( value, '&' );
450 if ( !strcmp( name, "frame_rate" ) )
451 params->time_base.den = atoi( value );
452 else if ( !strcmp( name, "frame_rate_base" ) )
453 params->time_base.num = atoi( value );
454 else if ( !strcmp( name, "sample_rate" ) )
455 params->sample_rate = atoi( value );
456 else if ( !strcmp( name, "channels" ) )
457 params->channels = atoi( value );
458 else if ( !strcmp( name, "width" ) )
459 params->width = atoi( value );
460 else if ( !strcmp( name, "height" ) )
461 params->height = atoi( value );
462 else if ( !strcmp( name, "standard" ) )
464 standard = strdup( value );
465 params->standard = standard;
467 else if ( !strcmp( name, "av" ) )
471 mrl = strchr( mrl, '&' );
475 // Now attempt to open the file
476 error = av_open_input_file( &context, file, format, 0, params ) < 0;
478 // Cleanup AVFormatParameters
482 // If successful, then try to get additional info
485 // Get the stream info
486 error = av_find_stream_info( context ) < 0;
488 // Continue if no error
491 // We will default to the first audio and video streams found
492 int audio_index = -1;
493 int video_index = -1;
495 // Now set properties where we can (use default unknowns if required)
496 if ( context->duration != AV_NOPTS_VALUE )
498 // This isn't going to be accurate for all formats
499 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + 0.5 );
500 mlt_properties_set_position( properties, "out", frames - 1 );
501 mlt_properties_set_position( properties, "length", frames );
504 // Find default audio and video streams
505 find_default_streams( properties, context, &audio_index, &video_index );
507 if ( context->start_time != AV_NOPTS_VALUE )
508 this->start_time = context->start_time;
510 // Check if we're seekable (something funny about mpeg here :-/)
511 if ( strncmp( file, "pipe:", 5 ) &&
512 strncmp( file, "http:", 5 ) &&
513 strncmp( file, "udp:", 4 ) &&
514 strncmp( file, "tcp:", 4 ) &&
515 strncmp( file, "rtsp:", 5 ) &&
516 strncmp( file, "rtp:", 4 ) )
518 this->seekable = av_seek_frame( context, -1, this->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
519 mlt_properties_set_int( properties, "seekable", this->seekable );
520 producer_format_close( this->dummy_context );
521 this->dummy_context = context;
522 av_open_input_file( &context, file, NULL, 0, NULL );
523 av_find_stream_info( context );
526 // Store selected audio and video indexes on properties
527 this->audio_index = audio_index;
528 this->video_index = video_index;
529 this->first_pts = -1;
530 this->last_position = POSITION_INITIAL;
532 // Fetch the width, height and aspect ratio
533 if ( video_index != -1 )
535 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
536 mlt_properties_set_int( properties, "width", codec_context->width );
537 mlt_properties_set_int( properties, "height", codec_context->height );
539 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
541 // Fetch the first frame of DV so we can read it directly
546 ret = av_read_frame( context, &pkt );
547 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
549 mlt_properties_set_double( properties, "aspect_ratio",
550 get_aspect_ratio( context->streams[ video_index ], codec_context, &pkt ) );
557 mlt_properties_set_double( properties, "aspect_ratio",
558 get_aspect_ratio( context->streams[ video_index ], codec_context, NULL ) );
563 if ( context->title )
564 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
565 if ( context->author )
566 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
567 if ( context->copyright )
568 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
569 if ( context->comment )
570 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
571 if ( context->album )
572 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
574 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
575 if ( context->track )
576 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
578 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
579 if ( av == 0 && audio_index != -1 && video_index != -1 )
581 // We'll use the open one as our video_format
583 producer_format_close( this->video_format );
585 this->video_format = context;
587 // And open again for our audio context
588 av_open_input_file( &context, file, NULL, 0, NULL );
589 av_find_stream_info( context );
593 producer_format_close( this->audio_format );
595 this->audio_format = context;
597 else if ( av != 2 && video_index != -1 )
599 // We only have a video context
601 producer_format_close( this->video_format );
603 this->video_format = context;
605 else if ( audio_index != -1 )
607 // We only have an audio context
609 producer_format_close( this->audio_format );
611 this->audio_format = context;
615 // Something has gone wrong
621 // Unlock the mutex now
627 /** Convert a frame position to a time code.
630 static double producer_time_of_frame( mlt_producer this, mlt_position position )
632 return ( double )position / mlt_producer_get_fps( this );
635 // Collect information about all audio streams
637 static void get_audio_streams_info( producer_avformat this )
639 // Fetch the audio format context
640 AVFormatContext *context = this->audio_format;
644 i < context->nb_streams;
647 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
649 AVCodecContext *codec_context = context->streams[i]->codec;
650 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
652 // If we don't have a codec and we can't initialise it, we can't do much more...
654 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
656 this->audio_streams++;
657 this->audio_max_stream = i;
658 this->total_channels += codec_context->channels;
659 if ( codec_context->channels > this->max_channel )
660 this->max_channel = codec_context->channels;
661 if ( codec_context->sample_rate > this->max_frequency )
662 this->max_frequency = codec_context->sample_rate;
663 avcodec_close( codec_context );
668 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
669 this->audio_streams, this->audio_max_stream, this->total_channels, this->max_channel );
672 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format *format, int width, int height )
675 if ( pix_fmt == PIX_FMT_RGB32 )
677 *format = mlt_image_rgb24a;
678 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
679 width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
681 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
682 sws_scale( context, frame->data, frame->linesize, 0, height,
683 output.data, output.linesize);
684 sws_freeContext( context );
686 else if ( *format == mlt_image_yuv420p )
688 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
689 width, height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
691 output.data[0] = buffer;
692 output.data[1] = buffer + width * height;
693 output.data[2] = buffer + ( 3 * width * height ) / 2;
694 output.linesize[0] = width;
695 output.linesize[1] = width >> 1;
696 output.linesize[2] = width >> 1;
697 sws_scale( context, frame->data, frame->linesize, 0, height,
698 output.data, output.linesize);
699 sws_freeContext( context );
701 else if ( *format == mlt_image_rgb24 )
703 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
704 width, height, PIX_FMT_RGB24, SWS_FAST_BILINEAR, NULL, NULL, NULL);
706 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
707 sws_scale( context, frame->data, frame->linesize, 0, height,
708 output.data, output.linesize);
709 sws_freeContext( context );
711 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
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 );
723 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
724 width, height, PIX_FMT_YUYV422, SWS_FAST_BILINEAR, NULL, NULL, NULL);
726 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
727 sws_scale( context, frame->data, frame->linesize, 0, height,
728 output.data, output.linesize);
729 sws_freeContext( context );
732 if ( *format == mlt_image_yuv420p )
735 pict.data[0] = buffer;
736 pict.data[1] = buffer + width * height;
737 pict.data[2] = buffer + ( 3 * width * height ) / 2;
738 pict.linesize[0] = width;
739 pict.linesize[1] = width >> 1;
740 pict.linesize[2] = width >> 1;
741 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
743 else if ( *format == mlt_image_rgb24 )
746 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
747 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
749 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
752 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
753 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
758 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
759 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
764 /** Allocate the image buffer and set it on the frame.
767 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
771 if ( codec_context->width == 0 || codec_context->height == 0 )
774 *width = codec_context->width;
775 *height = codec_context->height;
776 mlt_properties_set_int( frame_properties, "width", *width );
777 mlt_properties_set_int( frame_properties, "height", *height );
779 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
780 size = *width * ( *height + 1 ) * 4;
781 else switch ( *format )
783 case mlt_image_yuv420p:
784 size = *width * 3 * ( *height + 1 ) / 2;
786 case mlt_image_rgb24:
787 size = *width * ( *height + 1 ) * 3;
789 case mlt_image_rgb24a:
790 case mlt_image_opengl:
791 size = *width * ( *height + 1 ) * 4;
794 *format = mlt_image_yuv422;
795 size = *width * ( *height + 1 ) * 2;
799 // Construct the output image
800 *buffer = mlt_pool_alloc( size );
802 mlt_properties_set_data( frame_properties, "image", *buffer, size, mlt_pool_release, NULL );
809 /** Get an image from a frame.
812 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
815 producer_avformat this = mlt_frame_pop_service( frame );
816 mlt_producer producer = &this->parent;
818 // Get the properties from the frame
819 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
821 // Obtain the frame number of this frame
822 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
824 // Get the producer properties
825 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
829 // Fetch the video format context
830 AVFormatContext *context = this->video_format;
832 // Get the video stream
833 AVStream *stream = context->streams[ this->video_index ];
836 AVCodecContext *codec_context = stream->codec;
841 // Special case pause handling flag
844 // Special case ffwd handling
847 // We may want to use the source fps if available
848 double source_fps = mlt_properties_get_double( properties, "source_fps" );
849 double fps = mlt_producer_get_fps( producer );
851 // This is the physical frame position in the source
852 int req_position = ( int )( position / fps * source_fps + 0.5 );
854 // Determines if we have to decode all frames in a sequence
855 // Temporary hack to improve intra frame only
856 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
857 strcmp( codec_context->codec->name, "dvvideo" ) &&
858 strcmp( codec_context->codec->name, "huffyuv" ) &&
859 strcmp( codec_context->codec->name, "mjpeg" ) &&
860 strcmp( codec_context->codec->name, "rawvideo" );
862 int last_position = this->last_position;
864 // Turn on usage of new seek API and PTS for seeking
865 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
866 if ( mlt_properties_get( properties, "new_seek" ) )
867 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
870 if ( position != this->video_expected || last_position < 0 )
872 if ( this->av_frame && position + 1 == this->video_expected )
874 // We're paused - use last image
877 else if ( !this->seekable && position > this->video_expected && ( position - this->video_expected ) < 250 )
879 // Fast forward - seeking is inefficient for small distances - just ignore following frames
880 ignore = ( int )( ( position - this->video_expected ) / fps * source_fps );
881 codec_context->skip_loop_filter = AVDISCARD_NONREF;
883 else if ( this->seekable && ( position < this->video_expected || position - this->video_expected >= 12 || last_position < 0 ) )
885 if ( use_new_seek && last_position == POSITION_INITIAL )
887 // find first key frame
891 while ( ret >= 0 && toscan-- > 0 )
893 ret = av_read_frame( context, &pkt );
894 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == this->video_index )
896 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) );
897 this->first_pts = pkt.pts;
900 av_free_packet( &pkt );
903 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
906 // Calculate the timestamp for the requested frame
910 timestamp = ( req_position - 0.1 / source_fps ) /
911 ( av_q2d( stream->time_base ) * source_fps );
912 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
913 if ( this->first_pts > 0 )
914 timestamp += this->first_pts;
915 else if ( context->start_time != AV_NOPTS_VALUE )
916 timestamp += context->start_time;
920 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
921 if ( context->start_time != AV_NOPTS_VALUE )
922 timestamp += context->start_time;
925 timestamp -= AV_TIME_BASE;
928 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
929 timestamp, position, this->video_expected, last_position );
931 // Seek to the timestamp
934 codec_context->skip_loop_filter = AVDISCARD_NONREF;
935 av_seek_frame( context, this->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
939 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
942 // Remove the cached info relating to the previous position
943 this->current_position = POSITION_INVALID;
944 this->last_position = POSITION_INVALID;
945 av_freep( &this->av_frame );
949 // flush any pictures still in decode buffer
950 avcodec_flush_buffers( codec_context );
955 // Duplicate the last image if necessary (see comment on rawvideo below)
956 if ( this->av_frame && this->got_picture && this->seekable
958 || this->current_position == req_position
959 || ( !use_new_seek && this->current_position > req_position ) ) )
962 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
963 convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
965 mlt_frame_get_image( frame, buffer, format, width, height, writable );
970 int int_position = 0;
971 int decode_errors = 0;
974 av_init_packet( &pkt );
976 // Construct an AVFrame for YUV422 conversion
977 if ( !this->av_frame )
978 this->av_frame = avcodec_alloc_frame( );
980 while( ret >= 0 && !got_picture )
983 ret = av_read_frame( context, &pkt );
985 // We only deal with video from the selected video_index
986 if ( ret >= 0 && pkt.stream_index == this->video_index && pkt.size > 0 )
988 // Determine time code of the packet
991 int64_t pts = pkt.pts;
992 if ( this->first_pts > 0 )
993 pts -= this->first_pts;
994 else if ( context->start_time != AV_NOPTS_VALUE )
995 pts -= context->start_time;
996 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1000 if ( pkt.dts != AV_NOPTS_VALUE )
1002 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1003 if ( context->start_time != AV_NOPTS_VALUE )
1004 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1005 last_position = this->last_position;
1006 if ( int_position == last_position )
1007 int_position = last_position + 1;
1011 int_position = req_position;
1013 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d",
1014 pkt.dts, req_position, this->current_position, int_position );
1015 // Make a dumb assumption on streams that contain wild timestamps
1016 if ( abs( req_position - int_position ) > 999 )
1018 int_position = req_position;
1019 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1022 this->last_position = int_position;
1025 if ( must_decode || int_position >= req_position )
1027 codec_context->reordered_opaque = pkt.pts;
1028 if ( int_position >= req_position )
1029 codec_context->skip_loop_filter = AVDISCARD_NONE;
1030 ret = avcodec_decode_video( codec_context, this->av_frame, &got_picture, pkt.data, pkt.size );
1031 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1034 if ( ++decode_errors <= 10 )
1047 // Determine time code of the packet
1048 int64_t pts = this->av_frame->reordered_opaque;
1049 if ( this->first_pts > 0 )
1050 pts -= this->first_pts;
1051 else if ( context->start_time != AV_NOPTS_VALUE )
1052 pts -= context->start_time;
1053 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1054 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, this->av_frame->key_frame );
1057 if ( int_position < req_position )
1062 else if ( int_position >= req_position )
1065 codec_context->skip_loop_filter = AVDISCARD_NONE;
1067 else if ( ignore -- )
1072 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1073 av_free_packet( &pkt );
1075 else if ( ret >= 0 )
1077 av_free_packet( &pkt );
1080 // Now handle the picture if we have one
1083 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
1085 convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1086 if ( !mlt_properties_get( properties, "force_progressive" ) )
1087 mlt_properties_set_int( frame_properties, "progressive", !this->av_frame->interlaced_frame );
1088 this->top_field_first |= this->av_frame->top_field_first;
1089 this->current_position = int_position;
1090 this->got_picture = 1;
1099 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1102 // Very untidy - for rawvideo, the packet contains the frame, hence the free packet
1103 // above will break the pause behaviour - so we wipe the frame now
1104 if ( !strcmp( codec_context->codec->name, "rawvideo" ) )
1105 av_freep( &this->av_frame );
1109 // Set the field order property for this frame
1110 mlt_properties_set_int( frame_properties, "top_field_first", this->top_field_first );
1112 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1113 this->video_expected = position + 1;
1118 /** Process properties as AVOptions and apply to AV context obj
1121 static void apply_properties( void *obj, mlt_properties properties, int flags )
1124 int count = mlt_properties_count( properties );
1125 for ( i = 0; i < count; i++ )
1127 const char *opt_name = mlt_properties_get_name( properties, i );
1128 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1130 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1131 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1132 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1133 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1135 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1140 /** Initialize the video codec context.
1143 static int video_codec_init( producer_avformat this, int index, mlt_properties properties )
1145 // Initialise the codec if necessary
1146 if ( !this->video_codec )
1148 // Get the video stream
1149 AVStream *stream = this->video_format->streams[ index ];
1151 // Get codec context
1152 AVCodecContext *codec_context = stream->codec;
1155 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1157 // Initialise multi-threading
1158 int thread_count = mlt_properties_get_int( properties, "threads" );
1159 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1160 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1161 if ( thread_count > 1 )
1163 avcodec_thread_init( codec_context, thread_count );
1164 codec_context->thread_count = thread_count;
1167 // If we don't have a codec and we can't initialise it, we can't do much more...
1169 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1171 // Now store the codec with its destructor
1172 producer_codec_close( this->video_codec );
1173 this->video_codec = codec_context;
1177 // Remember that we can't use this later
1178 this->video_index = -1;
1182 // Process properties as AVOptions
1183 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1185 // Reset some image properties
1186 mlt_properties_set_int( properties, "width", this->video_codec->width );
1187 mlt_properties_set_int( properties, "height", this->video_codec->height );
1188 mlt_properties_set_double( properties, "aspect_ratio", get_aspect_ratio( stream, this->video_codec, NULL ) );
1190 // Determine the fps first from the codec
1191 double source_fps = (double) this->video_codec->time_base.den /
1192 ( this->video_codec->time_base.num == 0 ? 1 : this->video_codec->time_base.num );
1194 // If the muxer reports a frame rate different than the codec
1195 double muxer_fps = av_q2d( stream->r_frame_rate );
1196 if ( source_fps != muxer_fps )
1197 // Choose the lesser - the wrong tends to be off by some multiple of 10
1198 source_fps = muxer_fps < source_fps ? muxer_fps : source_fps;
1200 // We'll use fps if it's available
1201 if ( source_fps > 0 )
1202 mlt_properties_set_double( properties, "source_fps", source_fps );
1204 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( &this->parent ) );
1206 return this->video_codec && this->video_index > -1;
1209 /** Set up video handling.
1212 static void producer_set_up_video( producer_avformat this, mlt_frame frame )
1215 mlt_producer producer = &this->parent;
1217 // Get the properties
1218 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1220 // Fetch the video format context
1221 AVFormatContext *context = this->video_format;
1223 // Get the video_index
1224 int index = mlt_properties_get_int( properties, "video_index" );
1226 // Reopen the file if necessary
1227 if ( !context && index > -1 )
1229 mlt_events_block( properties, producer );
1230 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1231 mlt_properties_get( properties, "resource" ) );
1232 context = this->video_format;
1233 producer_format_close( this->dummy_context );
1234 this->dummy_context = NULL;
1235 mlt_events_unblock( properties, producer );
1236 get_audio_streams_info( this );
1238 // Process properties as AVOptions
1239 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1242 // Exception handling for video_index
1243 if ( context && index >= (int) context->nb_streams )
1245 // Get the last video stream
1246 for ( index = context->nb_streams - 1;
1247 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1249 mlt_properties_set_int( properties, "video_index", index );
1251 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1253 // Invalidate the video stream
1255 mlt_properties_set_int( properties, "video_index", index );
1258 // Update the video properties if the index changed
1259 if ( index != this->video_index )
1261 // Reset the video properties if the index changed
1262 this->video_index = index;
1263 producer_codec_close( this->video_codec );
1264 this->video_codec = NULL;
1267 // Get the frame properties
1268 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1271 if ( context && index > -1 && video_codec_init( this, index, properties ) )
1273 // Set the frame properties
1274 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1275 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1276 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1278 // Set the width and height
1279 mlt_properties_set_int( frame_properties, "width", this->video_codec->width );
1280 mlt_properties_set_int( frame_properties, "height", this->video_codec->height );
1281 mlt_properties_set_int( frame_properties, "real_width", this->video_codec->width );
1282 mlt_properties_set_int( frame_properties, "real_height", this->video_codec->height );
1283 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1284 if ( mlt_properties_get( properties, "force_progressive" ) )
1285 mlt_properties_set_int( frame_properties, "progressive", mlt_properties_get_int( properties, "force_progressive" ) );
1287 // Add our image operation
1288 mlt_frame_push_service( frame, this );
1289 mlt_frame_push_get_image( frame, producer_get_image );
1293 // If something failed, use test card image
1294 mlt_properties_set_int( frame_properties, "test_image", 1 );
1298 static int seek_audio( producer_avformat this, mlt_position position, double timecode, int *ignore )
1302 // Fetch the audio_format
1303 AVFormatContext *context = this->audio_format;
1305 // Seek if necessary
1306 if ( position != this->audio_expected )
1308 if ( position + 1 == this->audio_expected )
1310 // We're paused - silence required
1313 else if ( !this->seekable && position > this->audio_expected && ( position - this->audio_expected ) < 250 )
1315 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1316 *ignore = position - this->audio_expected;
1318 else if ( position < this->audio_expected || position - this->audio_expected >= 12 )
1320 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1321 if ( context->start_time != AV_NOPTS_VALUE )
1322 timestamp += context->start_time;
1323 if ( timestamp < 0 )
1326 // Set to the real timecode
1327 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1330 // Clear the usage in the audio buffer
1331 int i = MAX_AUDIO_STREAMS + 1;
1333 this->audio_used[i - 1] = 0;
1339 static int decode_audio( producer_avformat this, int *ignore, AVPacket *pkt, int samples, double timecode, double source_fps )
1341 // Fetch the audio_format
1342 AVFormatContext *context = this->audio_format;
1344 // Get the current stream index
1345 int index = pkt->stream_index;
1347 // Get codec context
1348 AVCodecContext *codec_context = this->audio_codec[ index ];
1350 // Obtain the resample context if it exists (not always needed)
1351 ReSampleContext *resample = this->audio_resample[ index ];
1353 // Obtain the audio buffers
1354 int16_t *audio_buffer = this->audio_buffer[ index ];
1355 int16_t *decode_buffer = this->decode_buffer[ index ];
1357 int audio_used = this->audio_used[ index ];
1358 int channels = codec_context->channels;
1359 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1360 uint8_t *ptr = pkt->data;
1361 int len = pkt->size;
1364 while ( ptr && ret >= 0 && len > 0 )
1367 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1368 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1370 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1381 // If decoded successfully and will not overflow
1382 if ( data_size > 0 && ( audio_used * channels + data_size / sizeof(int16_t) < AVCODEC_MAX_AUDIO_FRAME_SIZE ) )
1386 int16_t *source = decode_buffer;
1387 int16_t *dest = &audio_buffer[ audio_used * channels ];
1388 int convert_samples = data_size / channels / av_get_bits_per_sample_format( codec_context->sample_fmt ) * 8;
1389 audio_used += audio_resample( resample, dest, source, convert_samples );
1393 memcpy( &audio_buffer[ audio_used * channels ], decode_buffer, data_size );
1394 audio_used += data_size / channels / av_get_bits_per_sample_format( codec_context->sample_fmt ) * 8;
1398 while ( *ignore && audio_used > samples )
1401 audio_used -= samples;
1402 memmove( audio_buffer, &audio_buffer[ samples * channels ], audio_used * sizeof( int16_t ) );
1407 mlt_log_error( MLT_PRODUCER_SERVICE( &this->parent ), "audio_buffer overflow: audio_used %d data_size %d\n", audio_used, data_size );
1411 // If we're behind, ignore this packet
1412 if ( pkt->pts >= 0 )
1414 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt->pts;
1415 int req_position = ( int )( timecode * source_fps + 0.5 );
1416 int int_position = ( int )( current_pts * source_fps + 0.5 );
1418 if ( context->start_time != AV_NOPTS_VALUE )
1419 int_position -= ( int )( source_fps * context->start_time / AV_TIME_BASE + 0.5 );
1420 if ( this->seekable && *ignore == 0 && int_position < req_position )
1424 this->audio_used[ index ] = audio_used;
1429 /** Get the audio from a frame.
1432 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1435 producer_avformat this = mlt_frame_pop_audio( frame );
1437 // Obtain the frame number of this frame
1438 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1440 // Calculate the real time code
1441 double real_timecode = producer_time_of_frame( &this->parent, position );
1443 // Get the source fps
1444 double source_fps = mlt_properties_get_double( MLT_PRODUCER_PROPERTIES( &this->parent ), "source_fps" );
1446 // Number of frames to ignore (for ffwd)
1449 // Flag for paused (silence)
1450 int paused = seek_audio( this, position, real_timecode, &ignore );
1452 // Fetch the audio_format
1453 AVFormatContext *context = this->audio_format;
1455 // Determine the tracks to use
1456 int index = this->audio_index;
1457 int index_max = this->audio_index + 1;
1458 if ( this->audio_index == INT_MAX )
1461 index_max = context->nb_streams;
1462 *channels = this->total_channels;
1463 *frequency = this->max_frequency;
1466 // Initialize the resamplers and buffers
1467 for ( ; index < index_max; index++ )
1469 // Get codec context
1470 AVCodecContext *codec_context = this->audio_codec[ index ];
1472 if ( codec_context && !this->audio_buffer[ index ] )
1474 // Check for resample and create if necessary
1475 if ( codec_context->channels <= 2 )
1477 // Create the resampler
1478 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1479 this->audio_resample[ index ] = av_audio_resample_init(
1480 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1481 codec_context->channels, *frequency, codec_context->sample_rate,
1482 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1484 this->audio_resample[ index ] = audio_resample_init(
1485 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1486 codec_context->channels, *frequency, codec_context->sample_rate );
1491 codec_context->request_channels = this->audio_index == INT_MAX ? codec_context->channels : *channels;
1494 // Check for audio buffer and create if necessary
1495 this->audio_buffer[ index ] = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1497 // Check for decoder buffer and create if necessary
1498 this->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1502 // Get the audio if required
1509 av_init_packet( &pkt );
1511 while ( ret >= 0 && !got_audio )
1513 // Check if the buffer already contains the samples required
1514 if ( this->audio_index != INT_MAX && this->audio_used[ this->audio_index ] >= *samples && ignore == 0 )
1521 ret = av_read_frame( context, &pkt );
1523 // We only deal with audio from the selected audio index
1524 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == this->audio_index ||
1525 ( this->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
1526 ret = decode_audio( this, &ignore, &pkt, *samples, real_timecode, source_fps );
1527 av_free_packet( &pkt );
1529 if ( this->audio_index == INT_MAX && ret >= 0 )
1531 // Determine if there is enough audio for all streams
1533 for ( index = 0; index < context->nb_streams; index++ )
1535 if ( this->audio_codec[ index ] && this->audio_used[ index ] < *samples )
1541 // Allocate and set the frame's audio buffer
1542 int size = *samples * *channels * sizeof(int16_t);
1543 *buffer = mlt_pool_alloc( size );
1544 *format = mlt_audio_s16;
1545 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
1547 // Interleave tracks if audio_index=all
1548 if ( this->audio_index == INT_MAX )
1550 int16_t *dest = *buffer;
1552 for ( i = 0; i < *samples; i++ )
1554 for ( index = 0; index < index_max; index++ )
1555 if ( this->audio_codec[ index ] )
1557 int current_channels = this->audio_codec[ index ]->channels;
1558 int16_t *src = this->audio_buffer[ index ] + i * current_channels;
1559 memcpy( dest, src, current_channels * sizeof(int16_t) );
1560 dest += current_channels;
1563 for ( index = 0; index < index_max; index++ )
1564 if ( this->audio_codec[ index ] )
1566 int current_channels = this->audio_codec[ index ]->channels;
1567 int16_t *src = this->audio_buffer[ index ] + *samples * current_channels;
1568 this->audio_used[index] -= *samples;
1569 memmove( this->audio_buffer[ index ], src, this->audio_used[ index ] * current_channels * sizeof(int16_t) );
1572 // Copy a single track to the output buffer
1575 index = this->audio_index;
1576 int current_channels = this->audio_codec[ index ]->channels;
1578 // Now handle the audio if we have enough
1579 if ( this->audio_used[ index ] >= *samples )
1581 int16_t *src = this->audio_buffer[ index ];
1582 memcpy( *buffer, src, *samples * current_channels * sizeof(int16_t) );
1583 this->audio_used[ index ] -= *samples;
1584 memmove( src, &src[ *samples * current_channels ], this->audio_used[ index ] * current_channels * sizeof(int16_t) );
1588 // Otherwise fill with silence
1589 memset( *buffer, 0, *samples * current_channels * sizeof(int16_t) );
1591 if ( !this->audio_resample[ index ] )
1593 // TODO: uncomment and remove following line when full multi-channel support is ready
1594 // *channels = codec_context->channels;
1595 *frequency = this->audio_codec[ index ]->sample_rate;
1601 // Get silence and don't touch the context
1602 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1605 // Regardless of speed (other than paused), we expect to get the next frame
1607 this->audio_expected = position + 1;
1612 /** Initialize the audio codec context.
1615 static int audio_codec_init( producer_avformat this, int index, mlt_properties properties )
1617 // Initialise the codec if necessary
1618 if ( !this->audio_codec[ index ] )
1620 // Get codec context
1621 AVCodecContext *codec_context = this->audio_format->streams[index]->codec;
1624 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1626 // If we don't have a codec and we can't initialise it, we can't do much more...
1628 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1630 // Now store the codec with its destructor
1632 producer_codec_close( this->audio_codec[index] );
1633 this->audio_codec[ index ] = codec_context;
1637 // Remember that we can't use this later
1638 this->audio_index = -1;
1642 // Process properties as AVOptions
1643 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1645 return this->audio_codec[ index ] && this->audio_index > -1;
1648 /** Set up audio handling.
1651 static void producer_set_up_audio( producer_avformat this, mlt_frame frame )
1654 mlt_producer producer = &this->parent;
1656 // Get the properties
1657 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1659 // Fetch the audio format context
1660 AVFormatContext *context = this->audio_format;
1662 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1664 // Get the audio_index
1665 int index = mlt_properties_get_int( properties, "audio_index" );
1667 // Handle all audio tracks
1668 if ( mlt_properties_get( properties, "audio_index" ) &&
1669 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
1672 // Reopen the file if necessary
1673 if ( !context && index > -1 )
1675 mlt_events_block( properties, producer );
1676 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1677 mlt_properties_get( properties, "resource" ) );
1678 context = this->audio_format;
1679 producer_format_close( this->dummy_context );
1680 this->dummy_context = NULL;
1681 mlt_events_unblock( properties, producer );
1682 get_audio_streams_info( this );
1685 // Exception handling for audio_index
1686 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
1688 for ( index = context->nb_streams - 1;
1689 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
1691 mlt_properties_set_int( properties, "audio_index", index );
1693 if ( context && index > -1 && index < INT_MAX &&
1694 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1697 mlt_properties_set_int( properties, "audio_index", index );
1700 // Update the audio properties if the index changed
1701 if ( index > -1 && index != this->audio_index )
1703 producer_codec_close( this->audio_codec[ this->audio_index ] );
1704 this->audio_codec[ this->audio_index ] = NULL;
1706 this->audio_index = index;
1709 if ( context && index == INT_MAX )
1711 mlt_properties_set_int( frame_properties, "frequency", this->max_frequency );
1712 mlt_properties_set_int( frame_properties, "channels", this->total_channels );
1713 for ( index = 0; index < context->nb_streams; index++ )
1715 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
1716 audio_codec_init( this, index, properties );
1719 else if ( context && index > -1 && audio_codec_init( this, index, properties ) )
1721 // Set the frame properties
1722 if ( index < INT_MAX )
1724 mlt_properties_set_int( frame_properties, "frequency", this->audio_codec[ index ]->sample_rate );
1725 mlt_properties_set_int( frame_properties, "channels", this->audio_codec[ index ]->channels );
1728 if ( context && index > -1 )
1730 // Add our audio operation
1731 mlt_frame_push_audio( frame, this );
1732 mlt_frame_push_audio( frame, producer_get_audio );
1736 /** Our get frame implementation.
1739 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
1741 // Access the private data
1742 producer_avformat this = producer->child;
1744 // Create an empty frame
1745 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE( producer ) );
1747 // Update timecode on the frame we're creating
1748 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
1750 // Set the position of this producer
1751 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
1754 producer_set_up_video( this, *frame );
1757 producer_set_up_audio( this, *frame );
1759 // Calculate the next timecode
1760 mlt_producer_prepare_next( producer );
1765 static void producer_close( mlt_producer parent )
1768 producer_avformat this = parent->child;
1771 av_free( this->av_frame );
1773 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1775 if ( this->audio_resample[i] )
1776 audio_resample_close( this->audio_resample[i] );
1777 mlt_pool_release( this->audio_buffer[i] );
1778 av_free( this->decode_buffer[i] );
1779 producer_codec_close( this->audio_codec[i] );
1781 producer_codec_close( this->video_codec );
1782 producer_format_close( this->dummy_context );
1783 producer_format_close( this->audio_format );
1784 producer_format_close( this->video_format );
1787 parent->close = NULL;
1788 mlt_producer_close( parent );