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 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
80 int16_t *decode_buffer[ MAX_AUDIO_STREAMS ];
81 int audio_used[ MAX_AUDIO_STREAMS ];
87 unsigned int invalid_pts_counter;
89 typedef struct producer_avformat_s *producer_avformat;
91 // Forward references.
92 static int producer_open( producer_avformat this, mlt_profile profile, char *file );
93 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
94 static void producer_format_close( void *context );
95 static void producer_close( mlt_producer parent );
97 /** Constructor for libavformat.
100 mlt_producer producer_avformat_init( mlt_profile profile, char *file )
104 // Report information about available demuxers and codecs as YAML Tiny
105 if ( file && strstr( file, "f-list" ) )
107 fprintf( stderr, "---\nformats:\n" );
108 AVInputFormat *format = NULL;
109 while ( ( format = av_iformat_next( format ) ) )
110 fprintf( stderr, " - %s\n", format->name );
111 fprintf( stderr, "...\n" );
114 if ( file && strstr( file, "acodec-list" ) )
116 fprintf( stderr, "---\naudio_codecs:\n" );
117 AVCodec *codec = NULL;
118 while ( ( codec = av_codec_next( codec ) ) )
119 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
120 fprintf( stderr, " - %s\n", codec->name );
121 fprintf( stderr, "...\n" );
124 if ( file && strstr( file, "vcodec-list" ) )
126 fprintf( stderr, "---\nvideo_codecs:\n" );
127 AVCodec *codec = NULL;
128 while ( ( codec = av_codec_next( codec ) ) )
129 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
130 fprintf( stderr, " - %s\n", codec->name );
131 fprintf( stderr, "...\n" );
135 // Check that we have a non-NULL argument
138 // Construct the producer
139 producer_avformat this = calloc( 1, sizeof( struct producer_avformat_s ) );
142 if ( mlt_producer_init( &this->parent, this ) == 0 )
144 mlt_producer producer = &this->parent;
146 // Get the properties
147 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
149 // Set the resource property (required for all producers)
150 mlt_properties_set( properties, "resource", file );
152 // Register transport implementation with the producer
153 producer->close = (mlt_destructor) producer_close;
155 // Register our get_frame implementation
156 producer->get_frame = producer_get_frame;
159 if ( producer_open( this, profile, file ) != 0 )
162 mlt_producer_close( producer );
167 // Close the file to release resources for large playlists - reopen later as needed
168 producer_format_close( this->dummy_context );
169 this->dummy_context = NULL;
170 producer_format_close( this->audio_format );
171 this->audio_format = NULL;
172 producer_format_close( this->video_format );
173 this->video_format = NULL;
175 // Default the user-selectable indices from the auto-detected indices
176 mlt_properties_set_int( properties, "audio_index", this->audio_index );
177 mlt_properties_set_int( properties, "video_index", this->video_index );
185 /** Find the default streams.
188 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
193 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
195 // Allow for multiple audio and video streams in the file and select first of each (if available)
196 for( i = 0; i < context->nb_streams; i++ )
198 // Get the codec context
199 AVStream *stream = context->streams[ i ];
200 if ( ! stream ) continue;
201 AVCodecContext *codec_context = stream->codec;
202 if ( ! codec_context ) continue;
203 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
204 if ( ! codec ) continue;
206 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
208 // Determine the type and obtain the first index of each type
209 switch( codec_context->codec_type )
211 case CODEC_TYPE_VIDEO:
212 if ( *video_index < 0 )
214 mlt_properties_set( meta_media, key, "video" );
215 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
216 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
217 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
218 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
219 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
221 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
222 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
223 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
224 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
225 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
226 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
227 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
229 case CODEC_TYPE_AUDIO:
230 if ( *audio_index < 0 )
232 mlt_properties_set( meta_media, key, "audio" );
233 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
234 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
235 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
237 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
238 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
239 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
240 mlt_properties_set_int( meta_media, key, codec_context->channels );
245 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
246 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
247 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
248 mlt_properties_set( meta_media, key, codec->name );
249 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
250 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
251 mlt_properties_set( meta_media, key, codec->long_name );
253 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
254 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
255 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
256 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
257 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
258 // mlt_properties_set_int( meta_media, key, codec_context->profile );
259 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
260 // mlt_properties_set_int( meta_media, key, codec_context->level );
266 /** Producer file destructor.
269 static void producer_format_close( void *context )
273 // Lock the mutex now
277 av_close_input_file( context );
279 // Unlock the mutex now
284 /** Producer file destructor.
287 static void producer_codec_close( void *codec )
291 // Lock the mutex now
295 avcodec_close( codec );
297 // Unlock the mutex now
302 static inline int dv_is_pal( AVPacket *pkt )
304 return pkt->data[3] & 0x80;
307 static int dv_is_wide( AVPacket *pkt )
309 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
311 for ( ; i < pkt->size; i += 5 /* packet size */ )
313 if ( pkt->data[ i ] == 0x61 )
315 uint8_t x = pkt->data[ i + 2 ] & 0x7;
316 return ( x == 2 ) || ( x == 7 );
322 static double get_aspect_ratio( AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
324 double aspect_ratio = 1.0;
326 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
330 if ( dv_is_pal( pkt ) )
332 aspect_ratio = dv_is_wide( pkt )
333 ? 64.0/45.0 // 16:9 PAL
334 : 16.0/15.0; // 4:3 PAL
338 aspect_ratio = dv_is_wide( pkt )
339 ? 32.0/27.0 // 16:9 NTSC
340 : 8.0/9.0; // 4:3 NTSC
346 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
347 stream->sample_aspect_ratio;
349 codec_context->sample_aspect_ratio;
351 // Override FFmpeg's notion of DV aspect ratios, which are
352 // based upon a width of 704. Since we do not have a normaliser
353 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
354 // we just coerce the values to facilitate a passive behaviour through
355 // the rescale normaliser when using equivalent producers and consumers.
356 // = display_aspect / (width * height)
357 if ( ar.num == 10 && ar.den == 11 )
358 aspect_ratio = 8.0/9.0; // 4:3 NTSC
359 else if ( ar.num == 59 && ar.den == 54 )
360 aspect_ratio = 16.0/15.0; // 4:3 PAL
361 else if ( ar.num == 40 && ar.den == 33 )
362 aspect_ratio = 32.0/27.0; // 16:9 NTSC
363 else if ( ar.num == 118 && ar.den == 81 )
364 aspect_ratio = 64.0/45.0; // 16:9 PAL
369 AVRational codec_sar = codec_context->sample_aspect_ratio;
370 AVRational stream_sar =
371 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
372 stream->sample_aspect_ratio;
376 if ( codec_sar.num > 0 )
377 aspect_ratio = av_q2d( codec_sar );
378 else if ( stream_sar.num > 0 )
379 aspect_ratio = av_q2d( stream_sar );
387 static int producer_open( producer_avformat this, mlt_profile profile, char *file )
389 // Return an error code (0 == no error)
392 // Context for avformat
393 AVFormatContext *context = NULL;
395 // Get the properties
396 mlt_properties properties = MLT_PRODUCER_PROPERTIES( &this->parent );
398 // We will treat everything with the producer fps
399 double fps = mlt_profile_fps( profile );
401 // Lock the mutex now
404 // If "MRL", then create AVInputFormat
405 AVInputFormat *format = NULL;
406 AVFormatParameters *params = NULL;
407 char *standard = NULL;
408 char *mrl = strchr( file, ':' );
410 // AV option (0 = both, 1 = video, 2 = audio)
413 // Only if there is not a protocol specification that avformat can handle
414 if ( mrl && !url_exist( file ) )
416 // 'file' becomes format abbreviation
420 format = av_find_input_format( file );
422 // Eat the format designator
428 params = calloc( sizeof( AVFormatParameters ), 1 );
430 // These are required by video4linux (defaults)
432 params->height = 480;
433 params->time_base= (AVRational){1,25};
434 // params->device = file;
435 params->channels = 2;
436 params->sample_rate = 48000;
439 // XXX: this does not work anymore since avdevice
440 // TODO: make producer_avddevice?
442 mrl = strchr( file, '?' );
446 char *name = strdup( ++mrl );
447 char *value = strchr( name, ':' );
452 char *t = strchr( value, '&' );
455 if ( !strcmp( name, "frame_rate" ) )
456 params->time_base.den = atoi( value );
457 else if ( !strcmp( name, "frame_rate_base" ) )
458 params->time_base.num = atoi( value );
459 else if ( !strcmp( name, "sample_rate" ) )
460 params->sample_rate = atoi( value );
461 else if ( !strcmp( name, "channels" ) )
462 params->channels = atoi( value );
463 else if ( !strcmp( name, "width" ) )
464 params->width = atoi( value );
465 else if ( !strcmp( name, "height" ) )
466 params->height = atoi( value );
467 else if ( !strcmp( name, "standard" ) )
469 standard = strdup( value );
470 params->standard = standard;
472 else if ( !strcmp( name, "av" ) )
476 mrl = strchr( mrl, '&' );
480 // Now attempt to open the file
481 error = av_open_input_file( &context, file, format, 0, params ) < 0;
483 // Cleanup AVFormatParameters
487 // If successful, then try to get additional info
490 // Get the stream info
491 error = av_find_stream_info( context ) < 0;
493 // Continue if no error
496 // We will default to the first audio and video streams found
497 int audio_index = -1;
498 int video_index = -1;
500 // Now set properties where we can (use default unknowns if required)
501 if ( context->duration != AV_NOPTS_VALUE )
503 // This isn't going to be accurate for all formats
504 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + 0.5 );
505 mlt_properties_set_position( properties, "out", frames - 1 );
506 mlt_properties_set_position( properties, "length", frames );
509 // Find default audio and video streams
510 find_default_streams( properties, context, &audio_index, &video_index );
512 if ( context->start_time != AV_NOPTS_VALUE )
513 this->start_time = context->start_time;
515 // Check if we're seekable (something funny about mpeg here :-/)
516 if ( strncmp( file, "pipe:", 5 ) &&
517 strncmp( file, "http:", 5 ) &&
518 strncmp( file, "udp:", 4 ) &&
519 strncmp( file, "tcp:", 4 ) &&
520 strncmp( file, "rtsp:", 5 ) &&
521 strncmp( file, "rtp:", 4 ) )
523 this->seekable = av_seek_frame( context, -1, this->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
524 mlt_properties_set_int( properties, "seekable", this->seekable );
525 producer_format_close( this->dummy_context );
526 this->dummy_context = context;
527 av_open_input_file( &context, file, NULL, 0, NULL );
528 av_find_stream_info( context );
531 // Store selected audio and video indexes on properties
532 this->audio_index = audio_index;
533 this->video_index = video_index;
534 this->first_pts = -1;
535 this->last_position = POSITION_INITIAL;
537 // Fetch the width, height and aspect ratio
538 if ( video_index != -1 )
540 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
541 mlt_properties_set_int( properties, "width", codec_context->width );
542 mlt_properties_set_int( properties, "height", codec_context->height );
544 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
546 // Fetch the first frame of DV so we can read it directly
551 ret = av_read_frame( context, &pkt );
552 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
554 mlt_properties_set_double( properties, "aspect_ratio",
555 get_aspect_ratio( context->streams[ video_index ], codec_context, &pkt ) );
562 mlt_properties_set_double( properties, "aspect_ratio",
563 get_aspect_ratio( context->streams[ video_index ], codec_context, NULL ) );
568 if ( context->title )
569 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
570 if ( context->author )
571 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
572 if ( context->copyright )
573 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
574 if ( context->comment )
575 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
576 if ( context->album )
577 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
579 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
580 if ( context->track )
581 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
583 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
584 if ( av == 0 && audio_index != -1 && video_index != -1 )
586 // We'll use the open one as our video_format
588 producer_format_close( this->video_format );
590 this->video_format = context;
592 // And open again for our audio context
593 av_open_input_file( &context, file, NULL, 0, NULL );
594 av_find_stream_info( context );
598 producer_format_close( this->audio_format );
600 this->audio_format = context;
602 else if ( av != 2 && video_index != -1 )
604 // We only have a video context
606 producer_format_close( this->video_format );
608 this->video_format = context;
610 else if ( audio_index != -1 )
612 // We only have an audio context
614 producer_format_close( this->audio_format );
616 this->audio_format = context;
620 // Something has gone wrong
626 // Unlock the mutex now
632 /** Convert a frame position to a time code.
635 static double producer_time_of_frame( mlt_producer this, mlt_position position )
637 return ( double )position / mlt_producer_get_fps( this );
640 // Collect information about all audio streams
642 static void get_audio_streams_info( producer_avformat this )
644 // Fetch the audio format context
645 AVFormatContext *context = this->audio_format;
649 i < context->nb_streams;
652 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
654 AVCodecContext *codec_context = context->streams[i]->codec;
655 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
657 // If we don't have a codec and we can't initialise it, we can't do much more...
659 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
661 this->audio_streams++;
662 this->audio_max_stream = i;
663 this->total_channels += codec_context->channels;
664 if ( codec_context->channels > this->max_channel )
665 this->max_channel = codec_context->channels;
666 if ( codec_context->sample_rate > this->max_frequency )
667 this->max_frequency = codec_context->sample_rate;
668 avcodec_close( codec_context );
673 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
674 this->audio_streams, this->audio_max_stream, this->total_channels, this->max_channel );
677 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format *format, int width, int height )
680 if ( pix_fmt == PIX_FMT_RGB32 )
682 *format = mlt_image_rgb24a;
683 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
684 width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
686 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
687 sws_scale( context, frame->data, frame->linesize, 0, height,
688 output.data, output.linesize);
689 sws_freeContext( context );
691 else if ( *format == mlt_image_yuv420p )
693 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
694 width, height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
696 output.data[0] = buffer;
697 output.data[1] = buffer + width * height;
698 output.data[2] = buffer + ( 3 * width * height ) / 2;
699 output.linesize[0] = width;
700 output.linesize[1] = width >> 1;
701 output.linesize[2] = width >> 1;
702 sws_scale( context, frame->data, frame->linesize, 0, height,
703 output.data, output.linesize);
704 sws_freeContext( context );
706 else if ( *format == mlt_image_rgb24 )
708 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
709 width, height, PIX_FMT_RGB24, SWS_FAST_BILINEAR, NULL, NULL, NULL);
711 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
712 sws_scale( context, frame->data, frame->linesize, 0, height,
713 output.data, output.linesize);
714 sws_freeContext( context );
716 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
718 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
719 width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
721 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
722 sws_scale( context, frame->data, frame->linesize, 0, height,
723 output.data, output.linesize);
724 sws_freeContext( context );
728 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
729 width, height, PIX_FMT_YUYV422, SWS_FAST_BILINEAR, NULL, NULL, NULL);
731 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
732 sws_scale( context, frame->data, frame->linesize, 0, height,
733 output.data, output.linesize);
734 sws_freeContext( context );
737 if ( *format == mlt_image_yuv420p )
740 pict.data[0] = buffer;
741 pict.data[1] = buffer + width * height;
742 pict.data[2] = buffer + ( 3 * width * height ) / 2;
743 pict.linesize[0] = width;
744 pict.linesize[1] = width >> 1;
745 pict.linesize[2] = width >> 1;
746 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
748 else if ( *format == mlt_image_rgb24 )
751 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
752 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
754 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
757 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
758 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
763 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
764 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
769 /** Allocate the image buffer and set it on the frame.
772 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
776 if ( codec_context->width == 0 || codec_context->height == 0 )
779 *width = codec_context->width;
780 *height = codec_context->height;
781 mlt_properties_set_int( frame_properties, "width", *width );
782 mlt_properties_set_int( frame_properties, "height", *height );
784 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
785 size = *width * ( *height + 1 ) * 4;
786 else switch ( *format )
788 case mlt_image_yuv420p:
789 size = *width * 3 * ( *height + 1 ) / 2;
791 case mlt_image_rgb24:
792 size = *width * ( *height + 1 ) * 3;
794 case mlt_image_rgb24a:
795 case mlt_image_opengl:
796 size = *width * ( *height + 1 ) * 4;
799 *format = mlt_image_yuv422;
800 size = *width * ( *height + 1 ) * 2;
804 // Construct the output image
805 *buffer = mlt_pool_alloc( size );
807 mlt_properties_set_data( frame_properties, "image", *buffer, size, mlt_pool_release, NULL );
814 /** Get an image from a frame.
817 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
820 producer_avformat this = mlt_frame_pop_service( frame );
821 mlt_producer producer = &this->parent;
823 // Get the properties from the frame
824 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
826 // Obtain the frame number of this frame
827 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
829 // Get the producer properties
830 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
834 // Fetch the video format context
835 AVFormatContext *context = this->video_format;
837 // Get the video stream
838 AVStream *stream = context->streams[ this->video_index ];
841 AVCodecContext *codec_context = stream->codec;
846 // Special case pause handling flag
849 // Special case ffwd handling
852 // We may want to use the source fps if available
853 double source_fps = mlt_properties_get_double( properties, "source_fps" );
854 double fps = mlt_producer_get_fps( producer );
856 // This is the physical frame position in the source
857 int req_position = ( int )( position / fps * source_fps + 0.5 );
859 // Determines if we have to decode all frames in a sequence
860 // Temporary hack to improve intra frame only
861 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
862 strcmp( codec_context->codec->name, "dvvideo" ) &&
863 strcmp( codec_context->codec->name, "huffyuv" ) &&
864 strcmp( codec_context->codec->name, "mjpeg" ) &&
865 strcmp( codec_context->codec->name, "rawvideo" );
867 int last_position = this->last_position;
869 // Turn on usage of new seek API and PTS for seeking
870 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
871 if ( mlt_properties_get( properties, "new_seek" ) )
872 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
875 if ( position != this->video_expected || last_position < 0 )
877 if ( this->av_frame && position + 1 == this->video_expected )
879 // We're paused - use last image
882 else if ( !this->seekable && position > this->video_expected && ( position - this->video_expected ) < 250 )
884 // Fast forward - seeking is inefficient for small distances - just ignore following frames
885 ignore = ( int )( ( position - this->video_expected ) / fps * source_fps );
886 codec_context->skip_loop_filter = AVDISCARD_NONREF;
888 else if ( this->seekable && ( position < this->video_expected || position - this->video_expected >= 12 || last_position < 0 ) )
890 if ( use_new_seek && last_position == POSITION_INITIAL )
892 // find first key frame
896 while ( ret >= 0 && toscan-- > 0 )
898 ret = av_read_frame( context, &pkt );
899 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == this->video_index )
901 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) );
902 this->first_pts = pkt.pts;
905 av_free_packet( &pkt );
908 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
911 // Calculate the timestamp for the requested frame
915 timestamp = ( req_position - 0.1 / source_fps ) /
916 ( av_q2d( stream->time_base ) * source_fps );
917 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
918 if ( this->first_pts > 0 )
919 timestamp += this->first_pts;
920 else if ( context->start_time != AV_NOPTS_VALUE )
921 timestamp += context->start_time;
925 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
926 if ( context->start_time != AV_NOPTS_VALUE )
927 timestamp += context->start_time;
930 timestamp -= AV_TIME_BASE;
933 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
934 timestamp, position, this->video_expected, last_position );
936 // Seek to the timestamp
939 codec_context->skip_loop_filter = AVDISCARD_NONREF;
940 av_seek_frame( context, this->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
944 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
947 // Remove the cached info relating to the previous position
948 this->current_position = POSITION_INVALID;
949 this->last_position = POSITION_INVALID;
950 av_freep( &this->av_frame );
954 // flush any pictures still in decode buffer
955 avcodec_flush_buffers( codec_context );
960 // Duplicate the last image if necessary (see comment on rawvideo below)
961 if ( this->av_frame && this->got_picture && this->seekable
963 || this->current_position == req_position
964 || ( !use_new_seek && this->current_position > req_position ) ) )
967 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
968 convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
970 mlt_frame_get_image( frame, buffer, format, width, height, writable );
975 int int_position = 0;
976 int decode_errors = 0;
979 av_init_packet( &pkt );
981 // Construct an AVFrame for YUV422 conversion
982 if ( !this->av_frame )
983 this->av_frame = avcodec_alloc_frame( );
985 while( ret >= 0 && !got_picture )
988 ret = av_read_frame( context, &pkt );
990 // We only deal with video from the selected video_index
991 if ( ret >= 0 && pkt.stream_index == this->video_index && pkt.size > 0 )
993 // Determine time code of the packet
996 int64_t pts = pkt.pts;
997 if ( this->first_pts > 0 )
998 pts -= this->first_pts;
999 else if ( context->start_time != AV_NOPTS_VALUE )
1000 pts -= context->start_time;
1001 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1002 if ( pkt.pts == AV_NOPTS_VALUE )
1004 this->invalid_pts_counter++;
1005 if ( this->invalid_pts_counter > 20 )
1007 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1008 mlt_properties_set_int( properties, "new_seek", 0 );
1009 int_position = req_position;
1015 this->invalid_pts_counter = 0;
1017 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %llu req_pos %d cur_pos %d pkt_pos %d",
1018 pkt.pts, req_position, this->current_position, int_position );
1022 if ( pkt.dts != AV_NOPTS_VALUE )
1024 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1025 if ( context->start_time != AV_NOPTS_VALUE )
1026 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1027 last_position = this->last_position;
1028 if ( int_position == last_position )
1029 int_position = last_position + 1;
1033 int_position = req_position;
1035 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d",
1036 pkt.dts, req_position, this->current_position, int_position );
1037 // Make a dumb assumption on streams that contain wild timestamps
1038 if ( abs( req_position - int_position ) > 999 )
1040 int_position = req_position;
1041 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1044 this->last_position = int_position;
1047 if ( must_decode || int_position >= req_position )
1049 codec_context->reordered_opaque = pkt.pts;
1050 if ( int_position >= req_position )
1051 codec_context->skip_loop_filter = AVDISCARD_NONE;
1052 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1053 ret = avcodec_decode_video2( codec_context, this->av_frame, &got_picture, &pkt );
1055 ret = avcodec_decode_video( codec_context, this->av_frame, &got_picture, pkt.data, pkt.size );
1057 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1060 if ( ++decode_errors <= 10 )
1073 // Determine time code of the packet
1074 int64_t pts = this->av_frame->reordered_opaque;
1075 if ( this->first_pts > 0 )
1076 pts -= this->first_pts;
1077 else if ( context->start_time != AV_NOPTS_VALUE )
1078 pts -= context->start_time;
1079 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1080 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, this->av_frame->key_frame );
1083 if ( int_position < req_position )
1088 else if ( int_position >= req_position )
1091 codec_context->skip_loop_filter = AVDISCARD_NONE;
1093 else if ( ignore -- )
1098 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1099 av_free_packet( &pkt );
1101 else if ( ret >= 0 )
1103 av_free_packet( &pkt );
1106 // Now handle the picture if we have one
1109 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
1111 convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1112 if ( !mlt_properties_get( properties, "force_progressive" ) )
1113 mlt_properties_set_int( frame_properties, "progressive", !this->av_frame->interlaced_frame );
1114 this->top_field_first |= this->av_frame->top_field_first;
1115 this->current_position = int_position;
1116 this->got_picture = 1;
1125 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1128 // Very untidy - for rawvideo, the packet contains the frame, hence the free packet
1129 // above will break the pause behaviour - so we wipe the frame now
1130 if ( !strcmp( codec_context->codec->name, "rawvideo" ) )
1131 av_freep( &this->av_frame );
1135 // Set the field order property for this frame
1136 mlt_properties_set_int( frame_properties, "top_field_first", this->top_field_first );
1138 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1139 this->video_expected = position + 1;
1144 /** Process properties as AVOptions and apply to AV context obj
1147 static void apply_properties( void *obj, mlt_properties properties, int flags )
1150 int count = mlt_properties_count( properties );
1151 for ( i = 0; i < count; i++ )
1153 const char *opt_name = mlt_properties_get_name( properties, i );
1154 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1156 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1157 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1158 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1159 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1161 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1166 /** Initialize the video codec context.
1169 static int video_codec_init( producer_avformat this, int index, mlt_properties properties )
1171 // Initialise the codec if necessary
1172 if ( !this->video_codec )
1174 // Get the video stream
1175 AVStream *stream = this->video_format->streams[ index ];
1177 // Get codec context
1178 AVCodecContext *codec_context = stream->codec;
1181 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1183 // Initialise multi-threading
1184 int thread_count = mlt_properties_get_int( properties, "threads" );
1185 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1186 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1187 if ( thread_count > 1 )
1189 avcodec_thread_init( codec_context, thread_count );
1190 codec_context->thread_count = thread_count;
1193 // If we don't have a codec and we can't initialise it, we can't do much more...
1195 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1197 // Now store the codec with its destructor
1198 producer_codec_close( this->video_codec );
1199 this->video_codec = codec_context;
1203 // Remember that we can't use this later
1204 this->video_index = -1;
1208 // Process properties as AVOptions
1209 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1211 // Reset some image properties
1212 mlt_properties_set_int( properties, "width", this->video_codec->width );
1213 mlt_properties_set_int( properties, "height", this->video_codec->height );
1214 mlt_properties_set_double( properties, "aspect_ratio", get_aspect_ratio( stream, this->video_codec, NULL ) );
1216 // Determine the fps first from the codec
1217 double source_fps = (double) this->video_codec->time_base.den /
1218 ( this->video_codec->time_base.num == 0 ? 1 : this->video_codec->time_base.num );
1220 // If the muxer reports a frame rate different than the codec
1221 double muxer_fps = av_q2d( stream->r_frame_rate );
1222 if ( source_fps != muxer_fps )
1223 // Choose the lesser - the wrong tends to be off by some multiple of 10
1224 source_fps = muxer_fps < source_fps ? muxer_fps : source_fps;
1226 // We'll use fps if it's available
1227 if ( source_fps > 0 )
1228 mlt_properties_set_double( properties, "source_fps", source_fps );
1230 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( &this->parent ) );
1232 return this->video_codec && this->video_index > -1;
1235 /** Set up video handling.
1238 static void producer_set_up_video( producer_avformat this, mlt_frame frame )
1241 mlt_producer producer = &this->parent;
1243 // Get the properties
1244 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1246 // Fetch the video format context
1247 AVFormatContext *context = this->video_format;
1249 // Get the video_index
1250 int index = mlt_properties_get_int( properties, "video_index" );
1252 // Reopen the file if necessary
1253 if ( !context && index > -1 )
1255 mlt_events_block( properties, producer );
1256 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1257 mlt_properties_get( properties, "resource" ) );
1258 context = this->video_format;
1259 producer_format_close( this->dummy_context );
1260 this->dummy_context = NULL;
1261 mlt_events_unblock( properties, producer );
1262 if ( this->audio_format )
1263 get_audio_streams_info( this );
1265 // Process properties as AVOptions
1266 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1269 // Exception handling for video_index
1270 if ( context && index >= (int) context->nb_streams )
1272 // Get the last video stream
1273 for ( index = context->nb_streams - 1;
1274 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1276 mlt_properties_set_int( properties, "video_index", index );
1278 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1280 // Invalidate the video stream
1282 mlt_properties_set_int( properties, "video_index", index );
1285 // Update the video properties if the index changed
1286 if ( index != this->video_index )
1288 // Reset the video properties if the index changed
1289 this->video_index = index;
1290 producer_codec_close( this->video_codec );
1291 this->video_codec = NULL;
1294 // Get the frame properties
1295 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1298 if ( context && index > -1 && video_codec_init( this, index, properties ) )
1300 // Set the frame properties
1301 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1302 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1303 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1305 // Set the width and height
1306 mlt_properties_set_int( frame_properties, "width", this->video_codec->width );
1307 mlt_properties_set_int( frame_properties, "height", this->video_codec->height );
1308 mlt_properties_set_int( frame_properties, "real_width", this->video_codec->width );
1309 mlt_properties_set_int( frame_properties, "real_height", this->video_codec->height );
1310 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1311 if ( mlt_properties_get( properties, "force_progressive" ) )
1312 mlt_properties_set_int( frame_properties, "progressive", mlt_properties_get_int( properties, "force_progressive" ) );
1314 // Add our image operation
1315 mlt_frame_push_service( frame, this );
1316 mlt_frame_push_get_image( frame, producer_get_image );
1320 // If something failed, use test card image
1321 mlt_properties_set_int( frame_properties, "test_image", 1 );
1325 static int seek_audio( producer_avformat this, mlt_position position, double timecode, int *ignore )
1329 // Fetch the audio_format
1330 AVFormatContext *context = this->audio_format;
1332 // Seek if necessary
1333 if ( position != this->audio_expected )
1335 if ( position + 1 == this->audio_expected )
1337 // We're paused - silence required
1340 else if ( !this->seekable && position > this->audio_expected && ( position - this->audio_expected ) < 250 )
1342 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1343 *ignore = position - this->audio_expected;
1345 else if ( position < this->audio_expected || position - this->audio_expected >= 12 )
1347 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1348 if ( context->start_time != AV_NOPTS_VALUE )
1349 timestamp += context->start_time;
1350 if ( timestamp < 0 )
1353 // Set to the real timecode
1354 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1357 // Clear the usage in the audio buffer
1358 int i = MAX_AUDIO_STREAMS + 1;
1360 this->audio_used[i - 1] = 0;
1366 static int decode_audio( producer_avformat this, int *ignore, AVPacket *pkt, int samples, double timecode, double source_fps )
1368 // Fetch the audio_format
1369 AVFormatContext *context = this->audio_format;
1371 // Get the current stream index
1372 int index = pkt->stream_index;
1374 // Get codec context
1375 AVCodecContext *codec_context = this->audio_codec[ index ];
1377 // Obtain the resample context if it exists (not always needed)
1378 ReSampleContext *resample = this->audio_resample[ index ];
1380 // Obtain the audio buffers
1381 int16_t *audio_buffer = this->audio_buffer[ index ];
1382 int16_t *decode_buffer = this->decode_buffer[ index ];
1384 int audio_used = this->audio_used[ index ];
1385 int channels = codec_context->channels;
1386 uint8_t *ptr = pkt->data;
1387 int len = pkt->size;
1390 while ( ptr && ret >= 0 && len > 0 )
1392 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1395 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1396 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, pkt );
1397 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1398 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1400 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1411 // If decoded successfully
1412 if ( data_size > 0 )
1414 // Resize audio buffer to prevent overflow
1415 if ( audio_used * channels + data_size > this->audio_buffer_size[ index ] )
1417 mlt_pool_release( this->audio_buffer[ index ] );
1418 this->audio_buffer_size[ index ] = audio_used * channels * sizeof(int16_t) + data_size * 2;
1419 audio_buffer = this->audio_buffer[ index ] = mlt_pool_alloc( this->audio_buffer_size[ index ] );
1423 // Copy to audio buffer while resampling
1424 int16_t *source = decode_buffer;
1425 int16_t *dest = &audio_buffer[ audio_used * channels ];
1426 int convert_samples = data_size / channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1427 audio_used += audio_resample( resample, dest, source, convert_samples );
1431 // Straight copy to audio buffer
1432 memcpy( &audio_buffer[ audio_used * channels ], decode_buffer, data_size );
1433 audio_used += data_size / channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1437 while ( *ignore && audio_used > samples )
1440 audio_used -= samples;
1441 memmove( audio_buffer, &audio_buffer[ samples * channels ], audio_used * sizeof( int16_t ) );
1446 // If we're behind, ignore this packet
1447 if ( pkt->pts >= 0 )
1449 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt->pts;
1450 int req_position = ( int )( timecode * source_fps + 0.5 );
1451 int int_position = ( int )( current_pts * source_fps + 0.5 );
1453 if ( context->start_time != AV_NOPTS_VALUE )
1454 int_position -= ( int )( source_fps * context->start_time / AV_TIME_BASE + 0.5 );
1455 if ( this->seekable && *ignore == 0 && int_position < req_position )
1459 this->audio_used[ index ] = audio_used;
1464 /** Get the audio from a frame.
1467 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1470 producer_avformat this = mlt_frame_pop_audio( frame );
1472 // Obtain the frame number of this frame
1473 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1475 // Calculate the real time code
1476 double real_timecode = producer_time_of_frame( &this->parent, position );
1478 // Get the source fps
1479 double source_fps = mlt_properties_get_double( MLT_PRODUCER_PROPERTIES( &this->parent ), "source_fps" );
1481 // Number of frames to ignore (for ffwd)
1484 // Flag for paused (silence)
1485 int paused = seek_audio( this, position, real_timecode, &ignore );
1487 // Fetch the audio_format
1488 AVFormatContext *context = this->audio_format;
1490 // Determine the tracks to use
1491 int index = this->audio_index;
1492 int index_max = this->audio_index + 1;
1493 if ( this->audio_index == INT_MAX )
1496 index_max = context->nb_streams;
1497 *channels = this->total_channels;
1498 *frequency = this->max_frequency;
1501 // Initialize the resamplers and buffers
1502 for ( ; index < index_max; index++ )
1504 // Get codec context
1505 AVCodecContext *codec_context = this->audio_codec[ index ];
1507 if ( codec_context && !this->audio_buffer[ index ] )
1509 // Check for resample and create if necessary
1510 if ( codec_context->channels <= 2 )
1512 // Create the resampler
1513 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1514 this->audio_resample[ index ] = av_audio_resample_init(
1515 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1516 codec_context->channels, *frequency, codec_context->sample_rate,
1517 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1519 this->audio_resample[ index ] = audio_resample_init(
1520 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1521 codec_context->channels, *frequency, codec_context->sample_rate );
1526 codec_context->request_channels = this->audio_index == INT_MAX ? codec_context->channels : *channels;
1529 // Check for audio buffer and create if necessary
1530 this->audio_buffer[ index ] = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1531 this->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1533 // Check for decoder buffer and create if necessary
1534 this->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1538 // Get the audio if required
1545 av_init_packet( &pkt );
1547 while ( ret >= 0 && !got_audio )
1549 // Check if the buffer already contains the samples required
1550 if ( this->audio_index != INT_MAX && this->audio_used[ this->audio_index ] >= *samples && ignore == 0 )
1557 ret = av_read_frame( context, &pkt );
1559 // We only deal with audio from the selected audio index
1560 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == this->audio_index ||
1561 ( this->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
1562 ret = decode_audio( this, &ignore, &pkt, *samples, real_timecode, source_fps );
1563 av_free_packet( &pkt );
1565 if ( this->audio_index == INT_MAX && ret >= 0 )
1567 // Determine if there is enough audio for all streams
1569 for ( index = 0; index < context->nb_streams; index++ )
1571 if ( this->audio_codec[ index ] && this->audio_used[ index ] < *samples )
1577 // Allocate and set the frame's audio buffer
1578 int size = *samples * *channels * sizeof(int16_t);
1579 *buffer = mlt_pool_alloc( size );
1580 *format = mlt_audio_s16;
1581 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
1583 // Interleave tracks if audio_index=all
1584 if ( this->audio_index == INT_MAX )
1586 int16_t *dest = *buffer;
1588 for ( i = 0; i < *samples; i++ )
1590 for ( index = 0; index < index_max; index++ )
1591 if ( this->audio_codec[ index ] )
1593 int current_channels = this->audio_codec[ index ]->channels;
1594 int16_t *src = this->audio_buffer[ index ] + i * current_channels;
1595 memcpy( dest, src, current_channels * sizeof(int16_t) );
1596 dest += current_channels;
1599 for ( index = 0; index < index_max; index++ )
1600 if ( this->audio_codec[ index ] )
1602 int current_channels = this->audio_codec[ index ]->channels;
1603 int16_t *src = this->audio_buffer[ index ] + *samples * current_channels;
1604 this->audio_used[index] -= *samples;
1605 memmove( this->audio_buffer[ index ], src, this->audio_used[ index ] * current_channels * sizeof(int16_t) );
1608 // Copy a single track to the output buffer
1611 index = this->audio_index;
1613 // Now handle the audio if we have enough
1614 if ( this->audio_used[ index ] >= *samples )
1616 int16_t *src = this->audio_buffer[ index ];
1617 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
1618 this->audio_used[ index ] -= *samples;
1619 memmove( src, &src[ *samples * *channels ], this->audio_used[ index ] * *channels * sizeof(int16_t) );
1623 // Otherwise fill with silence
1624 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
1626 if ( !this->audio_resample[ index ] )
1628 // TODO: uncomment and remove following line when full multi-channel support is ready
1629 // *channels = codec_context->channels;
1630 *frequency = this->audio_codec[ index ]->sample_rate;
1636 // Get silence and don't touch the context
1637 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1640 // Regardless of speed (other than paused), we expect to get the next frame
1642 this->audio_expected = position + 1;
1647 /** Initialize the audio codec context.
1650 static int audio_codec_init( producer_avformat this, int index, mlt_properties properties )
1652 // Initialise the codec if necessary
1653 if ( !this->audio_codec[ index ] )
1655 // Get codec context
1656 AVCodecContext *codec_context = this->audio_format->streams[index]->codec;
1659 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1661 // If we don't have a codec and we can't initialise it, we can't do much more...
1663 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1665 // Now store the codec with its destructor
1667 producer_codec_close( this->audio_codec[index] );
1668 this->audio_codec[ index ] = codec_context;
1672 // Remember that we can't use this later
1673 this->audio_index = -1;
1677 // Process properties as AVOptions
1678 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1680 return this->audio_codec[ index ] && this->audio_index > -1;
1683 /** Set up audio handling.
1686 static void producer_set_up_audio( producer_avformat this, mlt_frame frame )
1689 mlt_producer producer = &this->parent;
1691 // Get the properties
1692 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1694 // Fetch the audio format context
1695 AVFormatContext *context = this->audio_format;
1697 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1699 // Get the audio_index
1700 int index = mlt_properties_get_int( properties, "audio_index" );
1702 // Handle all audio tracks
1703 if ( mlt_properties_get( properties, "audio_index" ) &&
1704 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
1707 // Reopen the file if necessary
1708 if ( !context && index > -1 )
1710 mlt_events_block( properties, producer );
1711 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1712 mlt_properties_get( properties, "resource" ) );
1713 context = this->audio_format;
1714 producer_format_close( this->dummy_context );
1715 this->dummy_context = NULL;
1716 mlt_events_unblock( properties, producer );
1717 get_audio_streams_info( this );
1720 // Exception handling for audio_index
1721 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
1723 for ( index = context->nb_streams - 1;
1724 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
1726 mlt_properties_set_int( properties, "audio_index", index );
1728 if ( context && index > -1 && index < INT_MAX &&
1729 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1732 mlt_properties_set_int( properties, "audio_index", index );
1735 // Update the audio properties if the index changed
1736 if ( index > -1 && index != this->audio_index )
1738 producer_codec_close( this->audio_codec[ this->audio_index ] );
1739 this->audio_codec[ this->audio_index ] = NULL;
1741 this->audio_index = index;
1744 if ( context && index == INT_MAX )
1746 mlt_properties_set_int( frame_properties, "frequency", this->max_frequency );
1747 mlt_properties_set_int( frame_properties, "channels", this->total_channels );
1748 for ( index = 0; index < context->nb_streams; index++ )
1750 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
1751 audio_codec_init( this, index, properties );
1754 else if ( context && index > -1 && audio_codec_init( this, index, properties ) )
1756 // Set the frame properties
1757 if ( index < INT_MAX )
1759 mlt_properties_set_int( frame_properties, "frequency", this->audio_codec[ index ]->sample_rate );
1760 mlt_properties_set_int( frame_properties, "channels", this->audio_codec[ index ]->channels );
1763 if ( context && index > -1 )
1765 // Add our audio operation
1766 mlt_frame_push_audio( frame, this );
1767 mlt_frame_push_audio( frame, producer_get_audio );
1771 /** Our get frame implementation.
1774 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
1776 // Access the private data
1777 producer_avformat this = producer->child;
1779 // Create an empty frame
1780 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE( producer ) );
1782 // Update timecode on the frame we're creating
1783 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
1785 // Set the position of this producer
1786 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
1789 producer_set_up_video( this, *frame );
1792 producer_set_up_audio( this, *frame );
1794 // Calculate the next timecode
1795 mlt_producer_prepare_next( producer );
1800 static void producer_close( mlt_producer parent )
1803 producer_avformat this = parent->child;
1806 av_free( this->av_frame );
1808 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1810 if ( this->audio_resample[i] )
1811 audio_resample_close( this->audio_resample[i] );
1812 mlt_pool_release( this->audio_buffer[i] );
1813 av_free( this->decode_buffer[i] );
1814 producer_codec_close( this->audio_codec[i] );
1816 producer_codec_close( this->video_codec );
1817 producer_format_close( this->dummy_context );
1818 producer_format_close( this->audio_format );
1819 producer_format_close( this->video_format );
1822 parent->close = NULL;
1823 mlt_producer_close( parent );