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.frame_rate", i );
220 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
221 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
222 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
223 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
224 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
225 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
227 case CODEC_TYPE_AUDIO:
228 if ( *audio_index < 0 )
230 mlt_properties_set( meta_media, key, "audio" );
231 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
232 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
233 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
235 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
236 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
237 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
238 mlt_properties_set_int( meta_media, key, codec_context->channels );
243 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
244 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
245 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
246 mlt_properties_set( meta_media, key, codec->name );
247 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
248 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
249 mlt_properties_set( meta_media, key, codec->long_name );
251 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
252 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
253 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
254 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
255 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
256 // mlt_properties_set_int( meta_media, key, codec_context->profile );
257 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
258 // mlt_properties_set_int( meta_media, key, codec_context->level );
264 /** Producer file destructor.
267 static void producer_format_close( void *context )
271 // Lock the mutex now
275 av_close_input_file( context );
277 // Unlock the mutex now
282 /** Producer file destructor.
285 static void producer_codec_close( void *codec )
289 // Lock the mutex now
293 avcodec_close( codec );
295 // Unlock the mutex now
300 static inline int dv_is_pal( AVPacket *pkt )
302 return pkt->data[3] & 0x80;
305 static int dv_is_wide( AVPacket *pkt )
307 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
309 for ( ; i < pkt->size; i += 5 /* packet size */ )
311 if ( pkt->data[ i ] == 0x61 )
313 uint8_t x = pkt->data[ i + 2 ] & 0x7;
314 return ( x == 2 ) || ( x == 7 );
320 static double get_aspect_ratio( AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
322 double aspect_ratio = 1.0;
324 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
328 if ( dv_is_pal( pkt ) )
330 aspect_ratio = dv_is_wide( pkt )
331 ? 64.0/45.0 // 16:9 PAL
332 : 16.0/15.0; // 4:3 PAL
336 aspect_ratio = dv_is_wide( pkt )
337 ? 32.0/27.0 // 16:9 NTSC
338 : 8.0/9.0; // 4:3 NTSC
344 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
345 stream->sample_aspect_ratio;
347 codec_context->sample_aspect_ratio;
349 // Override FFmpeg's notion of DV aspect ratios, which are
350 // based upon a width of 704. Since we do not have a normaliser
351 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
352 // we just coerce the values to facilitate a passive behaviour through
353 // the rescale normaliser when using equivalent producers and consumers.
354 // = display_aspect / (width * height)
355 if ( ar.num == 10 && ar.den == 11 )
356 aspect_ratio = 8.0/9.0; // 4:3 NTSC
357 else if ( ar.num == 59 && ar.den == 54 )
358 aspect_ratio = 16.0/15.0; // 4:3 PAL
359 else if ( ar.num == 40 && ar.den == 33 )
360 aspect_ratio = 32.0/27.0; // 16:9 NTSC
361 else if ( ar.num == 118 && ar.den == 81 )
362 aspect_ratio = 64.0/45.0; // 16:9 PAL
367 AVRational codec_sar = codec_context->sample_aspect_ratio;
368 AVRational stream_sar =
369 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
370 stream->sample_aspect_ratio;
374 if ( codec_sar.num > 0 )
375 aspect_ratio = av_q2d( codec_sar );
376 else if ( stream_sar.num > 0 )
377 aspect_ratio = av_q2d( stream_sar );
385 static int producer_open( producer_avformat this, mlt_profile profile, char *file )
387 // Return an error code (0 == no error)
390 // Context for avformat
391 AVFormatContext *context = NULL;
393 // Get the properties
394 mlt_properties properties = MLT_PRODUCER_PROPERTIES( &this->parent );
396 // We will treat everything with the producer fps
397 double fps = mlt_profile_fps( profile );
399 // Lock the mutex now
402 // If "MRL", then create AVInputFormat
403 AVInputFormat *format = NULL;
404 AVFormatParameters *params = NULL;
405 char *standard = NULL;
406 char *mrl = strchr( file, ':' );
408 // AV option (0 = both, 1 = video, 2 = audio)
411 // Only if there is not a protocol specification that avformat can handle
412 if ( mrl && !url_exist( file ) )
414 // 'file' becomes format abbreviation
418 format = av_find_input_format( file );
420 // Eat the format designator
426 params = calloc( sizeof( AVFormatParameters ), 1 );
428 // These are required by video4linux (defaults)
430 params->height = 480;
431 params->time_base= (AVRational){1,25};
432 // params->device = file;
433 params->channels = 2;
434 params->sample_rate = 48000;
437 // XXX: this does not work anymore since avdevice
438 // TODO: make producer_avddevice?
440 mrl = strchr( file, '?' );
444 char *name = strdup( ++mrl );
445 char *value = strchr( name, ':' );
450 char *t = strchr( value, '&' );
453 if ( !strcmp( name, "frame_rate" ) )
454 params->time_base.den = atoi( value );
455 else if ( !strcmp( name, "frame_rate_base" ) )
456 params->time_base.num = atoi( value );
457 else if ( !strcmp( name, "sample_rate" ) )
458 params->sample_rate = atoi( value );
459 else if ( !strcmp( name, "channels" ) )
460 params->channels = atoi( value );
461 else if ( !strcmp( name, "width" ) )
462 params->width = atoi( value );
463 else if ( !strcmp( name, "height" ) )
464 params->height = atoi( value );
465 else if ( !strcmp( name, "standard" ) )
467 standard = strdup( value );
468 params->standard = standard;
470 else if ( !strcmp( name, "av" ) )
474 mrl = strchr( mrl, '&' );
478 // Now attempt to open the file
479 error = av_open_input_file( &context, file, format, 0, params ) < 0;
481 // Cleanup AVFormatParameters
485 // If successful, then try to get additional info
488 // Get the stream info
489 error = av_find_stream_info( context ) < 0;
491 // Continue if no error
494 // We will default to the first audio and video streams found
495 int audio_index = -1;
496 int video_index = -1;
498 // Now set properties where we can (use default unknowns if required)
499 if ( context->duration != AV_NOPTS_VALUE )
501 // This isn't going to be accurate for all formats
502 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + 0.5 );
503 mlt_properties_set_position( properties, "out", frames - 1 );
504 mlt_properties_set_position( properties, "length", frames );
507 // Find default audio and video streams
508 find_default_streams( properties, context, &audio_index, &video_index );
510 if ( context->start_time != AV_NOPTS_VALUE )
511 this->start_time = context->start_time;
513 // Check if we're seekable (something funny about mpeg here :-/)
514 if ( strncmp( file, "pipe:", 5 ) &&
515 strncmp( file, "http:", 5 ) &&
516 strncmp( file, "udp:", 4 ) &&
517 strncmp( file, "tcp:", 4 ) &&
518 strncmp( file, "rtsp:", 5 ) &&
519 strncmp( file, "rtp:", 4 ) )
521 this->seekable = av_seek_frame( context, -1, this->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
522 mlt_properties_set_int( properties, "seekable", this->seekable );
523 producer_format_close( this->dummy_context );
524 this->dummy_context = context;
525 av_open_input_file( &context, file, NULL, 0, NULL );
526 av_find_stream_info( context );
529 // Store selected audio and video indexes on properties
530 this->audio_index = audio_index;
531 this->video_index = video_index;
532 this->first_pts = -1;
533 this->last_position = POSITION_INITIAL;
535 // Fetch the width, height and aspect ratio
536 if ( video_index != -1 )
538 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
539 mlt_properties_set_int( properties, "width", codec_context->width );
540 mlt_properties_set_int( properties, "height", codec_context->height );
542 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
544 // Fetch the first frame of DV so we can read it directly
549 ret = av_read_frame( context, &pkt );
550 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
552 mlt_properties_set_double( properties, "aspect_ratio",
553 get_aspect_ratio( context->streams[ video_index ], codec_context, &pkt ) );
560 mlt_properties_set_double( properties, "aspect_ratio",
561 get_aspect_ratio( context->streams[ video_index ], codec_context, NULL ) );
566 if ( context->title )
567 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
568 if ( context->author )
569 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
570 if ( context->copyright )
571 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
572 if ( context->comment )
573 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
574 if ( context->album )
575 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
577 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
578 if ( context->track )
579 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
581 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
582 if ( av == 0 && audio_index != -1 && video_index != -1 )
584 // We'll use the open one as our video_format
586 producer_format_close( this->video_format );
588 this->video_format = context;
590 // And open again for our audio context
591 av_open_input_file( &context, file, NULL, 0, NULL );
592 av_find_stream_info( context );
596 producer_format_close( this->audio_format );
598 this->audio_format = context;
600 else if ( av != 2 && video_index != -1 )
602 // We only have a video context
604 producer_format_close( this->video_format );
606 this->video_format = context;
608 else if ( audio_index != -1 )
610 // We only have an audio context
612 producer_format_close( this->audio_format );
614 this->audio_format = context;
618 // Something has gone wrong
624 // Unlock the mutex now
630 /** Convert a frame position to a time code.
633 static double producer_time_of_frame( mlt_producer this, mlt_position position )
635 return ( double )position / mlt_producer_get_fps( this );
638 // Collect information about all audio streams
640 static void get_audio_streams_info( producer_avformat this )
642 // Fetch the audio format context
643 AVFormatContext *context = this->audio_format;
647 i < context->nb_streams;
650 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
652 AVCodecContext *codec_context = context->streams[i]->codec;
653 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
655 // If we don't have a codec and we can't initialise it, we can't do much more...
657 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
659 this->audio_streams++;
660 this->audio_max_stream = i;
661 this->total_channels += codec_context->channels;
662 if ( codec_context->channels > this->max_channel )
663 this->max_channel = codec_context->channels;
664 if ( codec_context->sample_rate > this->max_frequency )
665 this->max_frequency = codec_context->sample_rate;
666 avcodec_close( codec_context );
671 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
672 this->audio_streams, this->audio_max_stream, this->total_channels, this->max_channel );
675 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format *format, int width, int height )
678 if ( pix_fmt == PIX_FMT_RGB32 )
680 *format = mlt_image_rgb24a;
681 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
682 width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
684 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
685 sws_scale( context, frame->data, frame->linesize, 0, height,
686 output.data, output.linesize);
687 sws_freeContext( context );
689 else if ( *format == mlt_image_yuv420p )
691 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
692 width, height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
694 output.data[0] = buffer;
695 output.data[1] = buffer + width * height;
696 output.data[2] = buffer + ( 3 * width * height ) / 2;
697 output.linesize[0] = width;
698 output.linesize[1] = width >> 1;
699 output.linesize[2] = width >> 1;
700 sws_scale( context, frame->data, frame->linesize, 0, height,
701 output.data, output.linesize);
702 sws_freeContext( context );
704 else if ( *format == mlt_image_rgb24 )
706 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
707 width, height, PIX_FMT_RGB24, SWS_FAST_BILINEAR, NULL, NULL, NULL);
709 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
710 sws_scale( context, frame->data, frame->linesize, 0, height,
711 output.data, output.linesize);
712 sws_freeContext( context );
714 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
716 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
717 width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
719 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
720 sws_scale( context, frame->data, frame->linesize, 0, height,
721 output.data, output.linesize);
722 sws_freeContext( context );
726 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
727 width, height, PIX_FMT_YUYV422, SWS_FAST_BILINEAR, NULL, NULL, NULL);
729 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
730 sws_scale( context, frame->data, frame->linesize, 0, height,
731 output.data, output.linesize);
732 sws_freeContext( context );
735 if ( *format == mlt_image_yuv420p )
738 pict.data[0] = buffer;
739 pict.data[1] = buffer + width * height;
740 pict.data[2] = buffer + ( 3 * width * height ) / 2;
741 pict.linesize[0] = width;
742 pict.linesize[1] = width >> 1;
743 pict.linesize[2] = width >> 1;
744 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
746 else if ( *format == mlt_image_rgb24 )
749 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
750 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
752 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
755 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
756 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
761 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
762 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
767 /** Allocate the image buffer and set it on the frame.
770 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
774 if ( codec_context->width == 0 || codec_context->height == 0 )
777 *width = codec_context->width;
778 *height = codec_context->height;
779 mlt_properties_set_int( frame_properties, "width", *width );
780 mlt_properties_set_int( frame_properties, "height", *height );
782 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
783 size = *width * ( *height + 1 ) * 4;
784 else switch ( *format )
786 case mlt_image_yuv420p:
787 size = *width * 3 * ( *height + 1 ) / 2;
789 case mlt_image_rgb24:
790 size = *width * ( *height + 1 ) * 3;
792 case mlt_image_rgb24a:
793 case mlt_image_opengl:
794 size = *width * ( *height + 1 ) * 4;
797 *format = mlt_image_yuv422;
798 size = *width * ( *height + 1 ) * 2;
802 // Construct the output image
803 *buffer = mlt_pool_alloc( size );
805 mlt_properties_set_data( frame_properties, "image", *buffer, size, mlt_pool_release, NULL );
812 /** Get an image from a frame.
815 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
818 producer_avformat this = mlt_frame_pop_service( frame );
819 mlt_producer producer = &this->parent;
821 // Get the properties from the frame
822 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
824 // Obtain the frame number of this frame
825 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
827 // Get the producer properties
828 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
832 // Fetch the video format context
833 AVFormatContext *context = this->video_format;
835 // Get the video stream
836 AVStream *stream = context->streams[ this->video_index ];
839 AVCodecContext *codec_context = stream->codec;
844 // Special case pause handling flag
847 // Special case ffwd handling
850 // We may want to use the source fps if available
851 double source_fps = mlt_properties_get_double( properties, "source_fps" );
852 double fps = mlt_producer_get_fps( producer );
854 // This is the physical frame position in the source
855 int req_position = ( int )( position / fps * source_fps + 0.5 );
857 // Determines if we have to decode all frames in a sequence
858 // Temporary hack to improve intra frame only
859 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
860 strcmp( codec_context->codec->name, "dvvideo" ) &&
861 strcmp( codec_context->codec->name, "huffyuv" ) &&
862 strcmp( codec_context->codec->name, "mjpeg" ) &&
863 strcmp( codec_context->codec->name, "rawvideo" );
865 int last_position = this->last_position;
867 // Turn on usage of new seek API and PTS for seeking
868 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
869 if ( mlt_properties_get( properties, "new_seek" ) )
870 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
873 if ( position != this->video_expected || last_position < 0 )
875 if ( this->av_frame && position + 1 == this->video_expected )
877 // We're paused - use last image
880 else if ( !this->seekable && position > this->video_expected && ( position - this->video_expected ) < 250 )
882 // Fast forward - seeking is inefficient for small distances - just ignore following frames
883 ignore = ( int )( ( position - this->video_expected ) / fps * source_fps );
884 codec_context->skip_loop_filter = AVDISCARD_NONREF;
886 else if ( this->seekable && ( position < this->video_expected || position - this->video_expected >= 12 || last_position < 0 ) )
888 if ( use_new_seek && last_position == POSITION_INITIAL )
890 // find first key frame
894 while ( ret >= 0 && toscan-- > 0 )
896 ret = av_read_frame( context, &pkt );
897 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == this->video_index )
899 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) );
900 this->first_pts = pkt.pts;
903 av_free_packet( &pkt );
906 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
909 // Calculate the timestamp for the requested frame
913 timestamp = ( req_position - 0.1 / source_fps ) /
914 ( av_q2d( stream->time_base ) * source_fps );
915 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
916 if ( this->first_pts > 0 )
917 timestamp += this->first_pts;
918 else if ( context->start_time != AV_NOPTS_VALUE )
919 timestamp += context->start_time;
923 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
924 if ( context->start_time != AV_NOPTS_VALUE )
925 timestamp += context->start_time;
928 timestamp -= AV_TIME_BASE;
931 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
932 timestamp, position, this->video_expected, last_position );
934 // Seek to the timestamp
937 codec_context->skip_loop_filter = AVDISCARD_NONREF;
938 av_seek_frame( context, this->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
942 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
945 // Remove the cached info relating to the previous position
946 this->current_position = POSITION_INVALID;
947 this->last_position = POSITION_INVALID;
948 av_freep( &this->av_frame );
952 // flush any pictures still in decode buffer
953 avcodec_flush_buffers( codec_context );
958 // Duplicate the last image if necessary (see comment on rawvideo below)
959 if ( this->av_frame && this->got_picture && this->seekable
961 || this->current_position == req_position
962 || ( !use_new_seek && this->current_position > req_position ) ) )
965 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
966 convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
968 mlt_frame_get_image( frame, buffer, format, width, height, writable );
973 int int_position = 0;
974 int decode_errors = 0;
977 av_init_packet( &pkt );
979 // Construct an AVFrame for YUV422 conversion
980 if ( !this->av_frame )
981 this->av_frame = avcodec_alloc_frame( );
983 while( ret >= 0 && !got_picture )
986 ret = av_read_frame( context, &pkt );
988 // We only deal with video from the selected video_index
989 if ( ret >= 0 && pkt.stream_index == this->video_index && pkt.size > 0 )
991 // Determine time code of the packet
994 int64_t pts = pkt.pts;
995 if ( this->first_pts > 0 )
996 pts -= this->first_pts;
997 else if ( context->start_time != AV_NOPTS_VALUE )
998 pts -= context->start_time;
999 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1003 if ( pkt.dts != AV_NOPTS_VALUE )
1005 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1006 if ( context->start_time != AV_NOPTS_VALUE )
1007 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1008 last_position = this->last_position;
1009 if ( int_position == last_position )
1010 int_position = last_position + 1;
1014 int_position = req_position;
1016 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d",
1017 pkt.dts, req_position, this->current_position, int_position );
1018 // Make a dumb assumption on streams that contain wild timestamps
1019 if ( abs( req_position - int_position ) > 999 )
1021 int_position = req_position;
1022 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1025 this->last_position = int_position;
1028 if ( must_decode || int_position >= req_position )
1030 codec_context->reordered_opaque = pkt.pts;
1031 if ( int_position >= req_position )
1032 codec_context->skip_loop_filter = AVDISCARD_NONE;
1033 ret = avcodec_decode_video( codec_context, this->av_frame, &got_picture, pkt.data, pkt.size );
1034 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1037 if ( ++decode_errors <= 10 )
1050 // Determine time code of the packet
1051 int64_t pts = this->av_frame->reordered_opaque;
1052 if ( this->first_pts > 0 )
1053 pts -= this->first_pts;
1054 else if ( context->start_time != AV_NOPTS_VALUE )
1055 pts -= context->start_time;
1056 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1057 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, this->av_frame->key_frame );
1060 if ( int_position < req_position )
1065 else if ( int_position >= req_position )
1068 codec_context->skip_loop_filter = AVDISCARD_NONE;
1070 else if ( ignore -- )
1075 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1076 av_free_packet( &pkt );
1078 else if ( ret >= 0 )
1080 av_free_packet( &pkt );
1083 // Now handle the picture if we have one
1086 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
1088 convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1089 if ( !mlt_properties_get( properties, "force_progressive" ) )
1090 mlt_properties_set_int( frame_properties, "progressive", !this->av_frame->interlaced_frame );
1091 this->top_field_first |= this->av_frame->top_field_first;
1092 this->current_position = int_position;
1093 this->got_picture = 1;
1102 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1105 // Very untidy - for rawvideo, the packet contains the frame, hence the free packet
1106 // above will break the pause behaviour - so we wipe the frame now
1107 if ( !strcmp( codec_context->codec->name, "rawvideo" ) )
1108 av_freep( &this->av_frame );
1112 // Set the field order property for this frame
1113 mlt_properties_set_int( frame_properties, "top_field_first", this->top_field_first );
1115 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1116 this->video_expected = position + 1;
1121 /** Process properties as AVOptions and apply to AV context obj
1124 static void apply_properties( void *obj, mlt_properties properties, int flags )
1127 int count = mlt_properties_count( properties );
1128 for ( i = 0; i < count; i++ )
1130 const char *opt_name = mlt_properties_get_name( properties, i );
1131 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1133 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1134 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1135 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1136 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1138 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1143 /** Initialize the video codec context.
1146 static int video_codec_init( producer_avformat this, int index, mlt_properties properties )
1148 // Initialise the codec if necessary
1149 if ( !this->video_codec )
1151 // Get the video stream
1152 AVStream *stream = this->video_format->streams[ index ];
1154 // Get codec context
1155 AVCodecContext *codec_context = stream->codec;
1158 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1160 // Initialise multi-threading
1161 int thread_count = mlt_properties_get_int( properties, "threads" );
1162 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1163 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1164 if ( thread_count > 1 )
1166 avcodec_thread_init( codec_context, thread_count );
1167 codec_context->thread_count = thread_count;
1170 // If we don't have a codec and we can't initialise it, we can't do much more...
1172 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1174 // Now store the codec with its destructor
1175 producer_codec_close( this->video_codec );
1176 this->video_codec = codec_context;
1180 // Remember that we can't use this later
1181 this->video_index = -1;
1185 // Process properties as AVOptions
1186 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1188 // Reset some image properties
1189 mlt_properties_set_int( properties, "width", this->video_codec->width );
1190 mlt_properties_set_int( properties, "height", this->video_codec->height );
1191 mlt_properties_set_double( properties, "aspect_ratio", get_aspect_ratio( stream, this->video_codec, NULL ) );
1193 // Determine the fps first from the codec
1194 double source_fps = (double) this->video_codec->time_base.den /
1195 ( this->video_codec->time_base.num == 0 ? 1 : this->video_codec->time_base.num );
1197 // If the muxer reports a frame rate different than the codec
1198 double muxer_fps = av_q2d( stream->r_frame_rate );
1199 if ( source_fps != muxer_fps )
1200 // Choose the lesser - the wrong tends to be off by some multiple of 10
1201 source_fps = muxer_fps < source_fps ? muxer_fps : source_fps;
1203 // We'll use fps if it's available
1204 if ( source_fps > 0 )
1205 mlt_properties_set_double( properties, "source_fps", source_fps );
1207 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( &this->parent ) );
1209 return this->video_codec && this->video_index > -1;
1212 /** Set up video handling.
1215 static void producer_set_up_video( producer_avformat this, mlt_frame frame )
1218 mlt_producer producer = &this->parent;
1220 // Get the properties
1221 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1223 // Fetch the video format context
1224 AVFormatContext *context = this->video_format;
1226 // Get the video_index
1227 int index = mlt_properties_get_int( properties, "video_index" );
1229 // Reopen the file if necessary
1230 if ( !context && index > -1 )
1232 mlt_events_block( properties, producer );
1233 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1234 mlt_properties_get( properties, "resource" ) );
1235 context = this->video_format;
1236 producer_format_close( this->dummy_context );
1237 this->dummy_context = NULL;
1238 mlt_events_unblock( properties, producer );
1239 get_audio_streams_info( this );
1241 // Process properties as AVOptions
1242 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1245 // Exception handling for video_index
1246 if ( context && index >= (int) context->nb_streams )
1248 // Get the last video stream
1249 for ( index = context->nb_streams - 1;
1250 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1252 mlt_properties_set_int( properties, "video_index", index );
1254 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1256 // Invalidate the video stream
1258 mlt_properties_set_int( properties, "video_index", index );
1261 // Update the video properties if the index changed
1262 if ( index != this->video_index )
1264 // Reset the video properties if the index changed
1265 this->video_index = index;
1266 producer_codec_close( this->video_codec );
1267 this->video_codec = NULL;
1270 // Get the frame properties
1271 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1274 if ( context && index > -1 && video_codec_init( this, index, properties ) )
1276 // Set the frame properties
1277 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1278 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1279 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1281 // Set the width and height
1282 mlt_properties_set_int( frame_properties, "width", this->video_codec->width );
1283 mlt_properties_set_int( frame_properties, "height", this->video_codec->height );
1284 mlt_properties_set_int( frame_properties, "real_width", this->video_codec->width );
1285 mlt_properties_set_int( frame_properties, "real_height", this->video_codec->height );
1286 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1287 if ( mlt_properties_get( properties, "force_progressive" ) )
1288 mlt_properties_set_int( frame_properties, "progressive", mlt_properties_get_int( properties, "force_progressive" ) );
1290 // Add our image operation
1291 mlt_frame_push_service( frame, this );
1292 mlt_frame_push_get_image( frame, producer_get_image );
1296 // If something failed, use test card image
1297 mlt_properties_set_int( frame_properties, "test_image", 1 );
1301 static int seek_audio( producer_avformat this, mlt_position position, double timecode, int *ignore )
1305 // Fetch the audio_format
1306 AVFormatContext *context = this->audio_format;
1308 // Seek if necessary
1309 if ( position != this->audio_expected )
1311 if ( position + 1 == this->audio_expected )
1313 // We're paused - silence required
1316 else if ( !this->seekable && position > this->audio_expected && ( position - this->audio_expected ) < 250 )
1318 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1319 *ignore = position - this->audio_expected;
1321 else if ( position < this->audio_expected || position - this->audio_expected >= 12 )
1323 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1324 if ( context->start_time != AV_NOPTS_VALUE )
1325 timestamp += context->start_time;
1326 if ( timestamp < 0 )
1329 // Set to the real timecode
1330 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1333 // Clear the usage in the audio buffer
1334 int i = MAX_AUDIO_STREAMS + 1;
1336 this->audio_used[i - 1] = 0;
1342 static int decode_audio( producer_avformat this, int *ignore, AVPacket *pkt, int samples, double timecode, double source_fps )
1344 // Fetch the audio_format
1345 AVFormatContext *context = this->audio_format;
1347 // Get the current stream index
1348 int index = pkt->stream_index;
1350 // Get codec context
1351 AVCodecContext *codec_context = this->audio_codec[ index ];
1353 // Obtain the resample context if it exists (not always needed)
1354 ReSampleContext *resample = this->audio_resample[ index ];
1356 // Obtain the audio buffers
1357 int16_t *audio_buffer = this->audio_buffer[ index ];
1358 int16_t *decode_buffer = this->decode_buffer[ index ];
1360 int audio_used = this->audio_used[ index ];
1361 int channels = codec_context->channels;
1362 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1363 uint8_t *ptr = pkt->data;
1364 int len = pkt->size;
1367 while ( ptr && ret >= 0 && len > 0 )
1370 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1371 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1373 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1384 // If decoded successfully and will not overflow
1385 if ( data_size > 0 && ( audio_used * channels + data_size / sizeof(int16_t) < AVCODEC_MAX_AUDIO_FRAME_SIZE ) )
1389 int16_t *source = decode_buffer;
1390 int16_t *dest = &audio_buffer[ audio_used * channels ];
1391 int convert_samples = data_size / channels / av_get_bits_per_sample_format( codec_context->sample_fmt ) * 8;
1392 audio_used += audio_resample( resample, dest, source, convert_samples );
1396 memcpy( &audio_buffer[ audio_used * channels ], decode_buffer, data_size );
1397 audio_used += data_size / channels / av_get_bits_per_sample_format( codec_context->sample_fmt ) * 8;
1401 while ( *ignore && audio_used > samples )
1404 audio_used -= samples;
1405 memmove( audio_buffer, &audio_buffer[ samples * channels ], audio_used * sizeof( int16_t ) );
1410 mlt_log_error( MLT_PRODUCER_SERVICE( &this->parent ), "audio_buffer overflow: audio_used %d data_size %d\n", audio_used, data_size );
1414 // If we're behind, ignore this packet
1415 if ( pkt->pts >= 0 )
1417 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt->pts;
1418 int req_position = ( int )( timecode * source_fps + 0.5 );
1419 int int_position = ( int )( current_pts * source_fps + 0.5 );
1421 if ( context->start_time != AV_NOPTS_VALUE )
1422 int_position -= ( int )( source_fps * context->start_time / AV_TIME_BASE + 0.5 );
1423 if ( this->seekable && *ignore == 0 && int_position < req_position )
1427 this->audio_used[ index ] = audio_used;
1432 /** Get the audio from a frame.
1435 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1438 producer_avformat this = mlt_frame_pop_audio( frame );
1440 // Obtain the frame number of this frame
1441 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1443 // Calculate the real time code
1444 double real_timecode = producer_time_of_frame( &this->parent, position );
1446 // Get the source fps
1447 double source_fps = mlt_properties_get_double( MLT_PRODUCER_PROPERTIES( &this->parent ), "source_fps" );
1449 // Number of frames to ignore (for ffwd)
1452 // Flag for paused (silence)
1453 int paused = seek_audio( this, position, real_timecode, &ignore );
1455 // Fetch the audio_format
1456 AVFormatContext *context = this->audio_format;
1458 // Determine the tracks to use
1459 int index = this->audio_index;
1460 int index_max = this->audio_index + 1;
1461 if ( this->audio_index == INT_MAX )
1464 index_max = context->nb_streams;
1465 *channels = this->total_channels;
1466 *frequency = this->max_frequency;
1469 // Initialize the resamplers and buffers
1470 for ( ; index < index_max; index++ )
1472 // Get codec context
1473 AVCodecContext *codec_context = this->audio_codec[ index ];
1475 if ( codec_context && !this->audio_buffer[ index ] )
1477 // Check for resample and create if necessary
1478 if ( codec_context->channels <= 2 )
1480 // Create the resampler
1481 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1482 this->audio_resample[ index ] = av_audio_resample_init(
1483 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1484 codec_context->channels, *frequency, codec_context->sample_rate,
1485 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1487 this->audio_resample[ index ] = audio_resample_init(
1488 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1489 codec_context->channels, *frequency, codec_context->sample_rate );
1494 codec_context->request_channels = this->audio_index == INT_MAX ? codec_context->channels : *channels;
1497 // Check for audio buffer and create if necessary
1498 this->audio_buffer[ index ] = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1500 // Check for decoder buffer and create if necessary
1501 this->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1505 // Get the audio if required
1512 av_init_packet( &pkt );
1514 while ( ret >= 0 && !got_audio )
1516 // Check if the buffer already contains the samples required
1517 if ( this->audio_index != INT_MAX && this->audio_used[ this->audio_index ] >= *samples && ignore == 0 )
1524 ret = av_read_frame( context, &pkt );
1526 // We only deal with audio from the selected audio index
1527 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == this->audio_index ||
1528 ( this->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
1529 ret = decode_audio( this, &ignore, &pkt, *samples, real_timecode, source_fps );
1530 av_free_packet( &pkt );
1532 if ( this->audio_index == INT_MAX && ret >= 0 )
1534 // Determine if there is enough audio for all streams
1536 for ( index = 0; index < context->nb_streams; index++ )
1538 if ( this->audio_codec[ index ] && this->audio_used[ index ] < *samples )
1544 // Allocate and set the frame's audio buffer
1545 int size = *samples * *channels * sizeof(int16_t);
1546 *buffer = mlt_pool_alloc( size );
1547 *format = mlt_audio_s16;
1548 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
1550 // Interleave tracks if audio_index=all
1551 if ( this->audio_index == INT_MAX )
1553 int16_t *dest = *buffer;
1555 for ( i = 0; i < *samples; i++ )
1557 for ( index = 0; index < index_max; index++ )
1558 if ( this->audio_codec[ index ] )
1560 int current_channels = this->audio_codec[ index ]->channels;
1561 int16_t *src = this->audio_buffer[ index ] + i * current_channels;
1562 memcpy( dest, src, current_channels * sizeof(int16_t) );
1563 dest += current_channels;
1566 for ( index = 0; index < index_max; index++ )
1567 if ( this->audio_codec[ index ] )
1569 int current_channels = this->audio_codec[ index ]->channels;
1570 int16_t *src = this->audio_buffer[ index ] + *samples * current_channels;
1571 this->audio_used[index] -= *samples;
1572 memmove( this->audio_buffer[ index ], src, this->audio_used[ index ] * current_channels * sizeof(int16_t) );
1575 // Copy a single track to the output buffer
1578 index = this->audio_index;
1580 // Now handle the audio if we have enough
1581 if ( this->audio_used[ index ] >= *samples )
1583 int16_t *src = this->audio_buffer[ index ];
1584 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
1585 this->audio_used[ index ] -= *samples;
1586 memmove( src, &src[ *samples * *channels ], this->audio_used[ index ] * *channels * sizeof(int16_t) );
1590 // Otherwise fill with silence
1591 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
1593 if ( !this->audio_resample[ index ] )
1595 // TODO: uncomment and remove following line when full multi-channel support is ready
1596 // *channels = codec_context->channels;
1597 *frequency = this->audio_codec[ index ]->sample_rate;
1603 // Get silence and don't touch the context
1604 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1607 // Regardless of speed (other than paused), we expect to get the next frame
1609 this->audio_expected = position + 1;
1614 /** Initialize the audio codec context.
1617 static int audio_codec_init( producer_avformat this, int index, mlt_properties properties )
1619 // Initialise the codec if necessary
1620 if ( !this->audio_codec[ index ] )
1622 // Get codec context
1623 AVCodecContext *codec_context = this->audio_format->streams[index]->codec;
1626 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1628 // If we don't have a codec and we can't initialise it, we can't do much more...
1630 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1632 // Now store the codec with its destructor
1634 producer_codec_close( this->audio_codec[index] );
1635 this->audio_codec[ index ] = codec_context;
1639 // Remember that we can't use this later
1640 this->audio_index = -1;
1644 // Process properties as AVOptions
1645 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1647 return this->audio_codec[ index ] && this->audio_index > -1;
1650 /** Set up audio handling.
1653 static void producer_set_up_audio( producer_avformat this, mlt_frame frame )
1656 mlt_producer producer = &this->parent;
1658 // Get the properties
1659 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1661 // Fetch the audio format context
1662 AVFormatContext *context = this->audio_format;
1664 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1666 // Get the audio_index
1667 int index = mlt_properties_get_int( properties, "audio_index" );
1669 // Handle all audio tracks
1670 if ( mlt_properties_get( properties, "audio_index" ) &&
1671 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
1674 // Reopen the file if necessary
1675 if ( !context && index > -1 )
1677 mlt_events_block( properties, producer );
1678 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1679 mlt_properties_get( properties, "resource" ) );
1680 context = this->audio_format;
1681 producer_format_close( this->dummy_context );
1682 this->dummy_context = NULL;
1683 mlt_events_unblock( properties, producer );
1684 get_audio_streams_info( this );
1687 // Exception handling for audio_index
1688 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
1690 for ( index = context->nb_streams - 1;
1691 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
1693 mlt_properties_set_int( properties, "audio_index", index );
1695 if ( context && index > -1 && index < INT_MAX &&
1696 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1699 mlt_properties_set_int( properties, "audio_index", index );
1702 // Update the audio properties if the index changed
1703 if ( index > -1 && index != this->audio_index )
1705 producer_codec_close( this->audio_codec[ this->audio_index ] );
1706 this->audio_codec[ this->audio_index ] = NULL;
1708 this->audio_index = index;
1711 if ( context && index == INT_MAX )
1713 mlt_properties_set_int( frame_properties, "frequency", this->max_frequency );
1714 mlt_properties_set_int( frame_properties, "channels", this->total_channels );
1715 for ( index = 0; index < context->nb_streams; index++ )
1717 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
1718 audio_codec_init( this, index, properties );
1721 else if ( context && index > -1 && audio_codec_init( this, index, properties ) )
1723 // Set the frame properties
1724 if ( index < INT_MAX )
1726 mlt_properties_set_int( frame_properties, "frequency", this->audio_codec[ index ]->sample_rate );
1727 mlt_properties_set_int( frame_properties, "channels", this->audio_codec[ index ]->channels );
1730 if ( context && index > -1 )
1732 // Add our audio operation
1733 mlt_frame_push_audio( frame, this );
1734 mlt_frame_push_audio( frame, producer_get_audio );
1738 /** Our get frame implementation.
1741 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
1743 // Access the private data
1744 producer_avformat this = producer->child;
1746 // Create an empty frame
1747 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE( producer ) );
1749 // Update timecode on the frame we're creating
1750 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
1752 // Set the position of this producer
1753 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
1756 producer_set_up_video( this, *frame );
1759 producer_set_up_audio( this, *frame );
1761 // Calculate the next timecode
1762 mlt_producer_prepare_next( producer );
1767 static void producer_close( mlt_producer parent )
1770 producer_avformat this = parent->child;
1773 av_free( this->av_frame );
1775 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1777 if ( this->audio_resample[i] )
1778 audio_resample_close( this->audio_resample[i] );
1779 mlt_pool_release( this->audio_buffer[i] );
1780 av_free( this->decode_buffer[i] );
1781 producer_codec_close( this->audio_codec[i] );
1783 producer_codec_close( this->video_codec );
1784 producer_format_close( this->dummy_context );
1785 producer_format_close( this->audio_format );
1786 producer_format_close( this->video_format );
1789 parent->close = NULL;
1790 mlt_producer_close( parent );