2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2009 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Author: Dan Dennedy <dan@dennedy.org>
6 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <framework/mlt_producer.h>
25 #include <framework/mlt_frame.h>
26 #include <framework/mlt_profile.h>
27 #include <framework/mlt_log.h>
28 #include <framework/mlt_deque.h>
29 #include <framework/mlt_factory.h>
30 #include <framework/mlt_cache.h>
32 // ffmpeg Header files
38 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
39 # include "audioconvert.h"
45 // System header files
51 #if LIBAVUTIL_VERSION_INT < (50<<16)
52 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
53 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
56 #define POSITION_INITIAL (-2)
57 #define POSITION_INVALID (-1)
59 #define MAX_AUDIO_STREAMS (10)
60 #define MAX_VDPAU_SURFACES (10)
62 void avformat_lock( );
63 void avformat_unlock( );
65 struct producer_avformat_s
68 AVFormatContext *dummy_context;
69 AVFormatContext *audio_format;
70 AVFormatContext *video_format;
71 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
72 AVCodecContext *video_codec;
74 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
75 mlt_position audio_expected;
76 mlt_position video_expected;
86 int16_t *audio_buffer[ MAX_AUDIO_STREAMS ];
87 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
88 int16_t *decode_buffer[ MAX_AUDIO_STREAMS ];
89 int audio_used[ MAX_AUDIO_STREAMS ];
95 unsigned int invalid_pts_counter;
96 double resample_factor;
97 mlt_cache image_cache;
102 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
113 typedef struct producer_avformat_s *producer_avformat;
115 // Forward references.
116 static int producer_open( producer_avformat this, mlt_profile profile, char *file );
117 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
118 static void producer_avformat_close( producer_avformat );
119 static void producer_close( mlt_producer parent );
125 /** Constructor for libavformat.
128 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
132 // Report information about available demuxers and codecs as YAML Tiny
133 if ( file && strstr( file, "f-list" ) )
135 fprintf( stderr, "---\nformats:\n" );
136 AVInputFormat *format = NULL;
137 while ( ( format = av_iformat_next( format ) ) )
138 fprintf( stderr, " - %s\n", format->name );
139 fprintf( stderr, "...\n" );
142 if ( file && strstr( file, "acodec-list" ) )
144 fprintf( stderr, "---\naudio_codecs:\n" );
145 AVCodec *codec = NULL;
146 while ( ( codec = av_codec_next( codec ) ) )
147 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
148 fprintf( stderr, " - %s\n", codec->name );
149 fprintf( stderr, "...\n" );
152 if ( file && strstr( file, "vcodec-list" ) )
154 fprintf( stderr, "---\nvideo_codecs:\n" );
155 AVCodec *codec = NULL;
156 while ( ( codec = av_codec_next( codec ) ) )
157 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
158 fprintf( stderr, " - %s\n", codec->name );
159 fprintf( stderr, "...\n" );
163 // Check that we have a non-NULL argument
166 // Construct the producer
167 mlt_producer producer = calloc( 1, sizeof( struct mlt_producer_s ) );
168 producer_avformat this = calloc( 1, sizeof( struct producer_avformat_s ) );
171 if ( mlt_producer_init( producer, this ) == 0 )
173 this->parent = producer;
175 // Get the properties
176 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
178 // Set the resource property (required for all producers)
179 mlt_properties_set( properties, "resource", file );
181 // Register transport implementation with the producer
182 producer->close = (mlt_destructor) producer_close;
184 // Register our get_frame implementation
185 producer->get_frame = producer_get_frame;
187 if ( strcmp( service, "avformat-novalidate" ) )
190 if ( producer_open( this, profile, file ) != 0 )
193 mlt_producer_close( producer );
198 // Close the file to release resources for large playlists - reopen later as needed
200 if ( this->dummy_context )
201 av_close_input_file( this->dummy_context );
202 this->dummy_context = NULL;
203 if ( this->audio_format )
204 av_close_input_file( this->audio_format );
205 this->audio_format = NULL;
206 if ( this->video_format )
207 av_close_input_file( this->video_format );
208 this->video_format = NULL;
211 // Default the user-selectable indices from the auto-detected indices
212 mlt_properties_set_int( properties, "audio_index", this->audio_index );
213 mlt_properties_set_int( properties, "video_index", this->video_index );
216 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
218 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
224 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
226 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
234 /** Find the default streams.
237 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
242 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
244 // Allow for multiple audio and video streams in the file and select first of each (if available)
245 for( i = 0; i < context->nb_streams; i++ )
247 // Get the codec context
248 AVStream *stream = context->streams[ i ];
249 if ( ! stream ) continue;
250 AVCodecContext *codec_context = stream->codec;
251 if ( ! codec_context ) continue;
252 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
253 if ( ! codec ) continue;
255 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
257 // Determine the type and obtain the first index of each type
258 switch( codec_context->codec_type )
260 case CODEC_TYPE_VIDEO:
261 if ( *video_index < 0 )
263 mlt_properties_set( meta_media, key, "video" );
264 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
265 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
266 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
267 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
268 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
270 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
271 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
272 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
273 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
274 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
275 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
276 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
278 case CODEC_TYPE_AUDIO:
279 if ( *audio_index < 0 )
281 mlt_properties_set( meta_media, key, "audio" );
282 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
283 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
284 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
286 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
287 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
288 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
289 mlt_properties_set_int( meta_media, key, codec_context->channels );
294 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
295 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
296 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
297 mlt_properties_set( meta_media, key, codec->name );
298 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
299 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
300 mlt_properties_set( meta_media, key, codec->long_name );
302 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
303 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
304 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
305 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
306 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
307 // mlt_properties_set_int( meta_media, key, codec_context->profile );
308 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
309 // mlt_properties_set_int( meta_media, key, codec_context->level );
315 static inline int dv_is_pal( AVPacket *pkt )
317 return pkt->data[3] & 0x80;
320 static int dv_is_wide( AVPacket *pkt )
322 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
324 for ( ; i < pkt->size; i += 5 /* packet size */ )
326 if ( pkt->data[ i ] == 0x61 )
328 uint8_t x = pkt->data[ i + 2 ] & 0x7;
329 return ( x == 2 ) || ( x == 7 );
335 static double get_aspect_ratio( AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
337 double aspect_ratio = 1.0;
339 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
343 if ( dv_is_pal( pkt ) )
345 aspect_ratio = dv_is_wide( pkt )
346 ? 64.0/45.0 // 16:9 PAL
347 : 16.0/15.0; // 4:3 PAL
351 aspect_ratio = dv_is_wide( pkt )
352 ? 32.0/27.0 // 16:9 NTSC
353 : 8.0/9.0; // 4:3 NTSC
359 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
360 stream->sample_aspect_ratio;
362 codec_context->sample_aspect_ratio;
364 // Override FFmpeg's notion of DV aspect ratios, which are
365 // based upon a width of 704. Since we do not have a normaliser
366 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
367 // we just coerce the values to facilitate a passive behaviour through
368 // the rescale normaliser when using equivalent producers and consumers.
369 // = display_aspect / (width * height)
370 if ( ar.num == 10 && ar.den == 11 )
371 aspect_ratio = 8.0/9.0; // 4:3 NTSC
372 else if ( ar.num == 59 && ar.den == 54 )
373 aspect_ratio = 16.0/15.0; // 4:3 PAL
374 else if ( ar.num == 40 && ar.den == 33 )
375 aspect_ratio = 32.0/27.0; // 16:9 NTSC
376 else if ( ar.num == 118 && ar.den == 81 )
377 aspect_ratio = 64.0/45.0; // 16:9 PAL
382 AVRational codec_sar = codec_context->sample_aspect_ratio;
383 AVRational stream_sar =
384 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
385 stream->sample_aspect_ratio;
389 if ( codec_sar.num > 0 )
390 aspect_ratio = av_q2d( codec_sar );
391 else if ( stream_sar.num > 0 )
392 aspect_ratio = av_q2d( stream_sar );
400 static int producer_open( producer_avformat this, mlt_profile profile, char *file )
402 // Return an error code (0 == no error)
405 // Context for avformat
406 AVFormatContext *context = NULL;
408 // Get the properties
409 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this->parent );
411 // We will treat everything with the producer fps
412 double fps = mlt_profile_fps( profile );
414 // Lock the mutex now
417 // If "MRL", then create AVInputFormat
418 AVInputFormat *format = NULL;
419 AVFormatParameters *params = NULL;
420 char *standard = NULL;
421 char *mrl = strchr( file, ':' );
423 // AV option (0 = both, 1 = video, 2 = audio)
426 // Only if there is not a protocol specification that avformat can handle
427 if ( mrl && !url_exist( file ) )
429 // 'file' becomes format abbreviation
433 format = av_find_input_format( file );
435 // Eat the format designator
441 params = calloc( sizeof( AVFormatParameters ), 1 );
443 // These are required by video4linux (defaults)
445 params->height = 480;
446 params->time_base= (AVRational){1,25};
447 // params->device = file;
448 params->channels = 2;
449 params->sample_rate = 48000;
453 mrl = strchr( file, '?' );
457 char *name = strdup( ++mrl );
458 char *value = strchr( name, ':' );
463 char *t = strchr( value, '&' );
466 if ( !strcmp( name, "frame_rate" ) )
467 params->time_base.den = atoi( value );
468 else if ( !strcmp( name, "frame_rate_base" ) )
469 params->time_base.num = atoi( value );
470 else if ( !strcmp( name, "sample_rate" ) )
471 params->sample_rate = atoi( value );
472 else if ( !strcmp( name, "channels" ) )
473 params->channels = atoi( value );
474 else if ( !strcmp( name, "width" ) )
475 params->width = atoi( value );
476 else if ( !strcmp( name, "height" ) )
477 params->height = atoi( value );
478 else if ( !strcmp( name, "standard" ) )
480 standard = strdup( value );
481 params->standard = standard;
483 else if ( !strcmp( name, "av" ) )
487 mrl = strchr( mrl, '&' );
491 // Now attempt to open the file
492 error = av_open_input_file( &context, file, format, 0, params ) < 0;
494 // Cleanup AVFormatParameters
498 // If successful, then try to get additional info
501 // Get the stream info
502 error = av_find_stream_info( context ) < 0;
504 // Continue if no error
507 // We will default to the first audio and video streams found
508 int audio_index = -1;
509 int video_index = -1;
511 // Now set properties where we can (use default unknowns if required)
512 if ( context->duration != AV_NOPTS_VALUE )
514 // This isn't going to be accurate for all formats
515 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + 0.5 );
516 mlt_properties_set_position( properties, "out", frames - 1 );
517 mlt_properties_set_position( properties, "length", frames );
520 // Find default audio and video streams
521 find_default_streams( properties, context, &audio_index, &video_index );
523 if ( context->start_time != AV_NOPTS_VALUE )
524 this->start_time = context->start_time;
526 // Check if we're seekable (something funny about mpeg here :-/)
527 if ( strncmp( file, "pipe:", 5 ) &&
528 strncmp( file, "/dev/", 5 ) &&
529 strncmp( file, "http:", 5 ) &&
530 strncmp( file, "udp:", 4 ) &&
531 strncmp( file, "tcp:", 4 ) &&
532 strncmp( file, "rtsp:", 5 ) &&
533 strncmp( file, "rtp:", 4 ) )
535 this->seekable = av_seek_frame( context, -1, this->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
536 mlt_properties_set_int( properties, "seekable", this->seekable );
537 this->dummy_context = context;
538 av_open_input_file( &context, file, NULL, 0, NULL );
539 av_find_stream_info( context );
542 // Store selected audio and video indexes on properties
543 this->audio_index = audio_index;
544 this->video_index = video_index;
545 this->first_pts = -1;
546 this->last_position = POSITION_INITIAL;
548 // Fetch the width, height and aspect ratio
549 if ( video_index != -1 )
551 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
552 mlt_properties_set_int( properties, "width", codec_context->width );
553 mlt_properties_set_int( properties, "height", codec_context->height );
555 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
557 // Fetch the first frame of DV so we can read it directly
562 ret = av_read_frame( context, &pkt );
563 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
565 mlt_properties_set_double( properties, "aspect_ratio",
566 get_aspect_ratio( context->streams[ video_index ], codec_context, &pkt ) );
573 mlt_properties_set_double( properties, "aspect_ratio",
574 get_aspect_ratio( context->streams[ video_index ], codec_context, NULL ) );
579 if ( context->title )
580 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
581 if ( context->author )
582 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
583 if ( context->copyright )
584 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
585 if ( context->comment )
586 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
587 if ( context->album )
588 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
590 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
591 if ( context->track )
592 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
594 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
595 if ( av == 0 && audio_index != -1 && video_index != -1 )
597 // We'll use the open one as our video_format
598 this->video_format = context;
600 // And open again for our audio context
601 av_open_input_file( &context, file, NULL, 0, NULL );
602 av_find_stream_info( context );
605 this->audio_format = context;
607 else if ( av != 2 && video_index != -1 )
609 // We only have a video context
610 this->video_format = context;
612 else if ( audio_index != -1 )
614 // We only have an audio context
615 this->audio_format = context;
619 // Something has gone wrong
625 // Unlock the mutex now
631 /** Convert a frame position to a time code.
634 static double producer_time_of_frame( mlt_producer this, mlt_position position )
636 return ( double )position / mlt_producer_get_fps( this );
639 // Collect information about all audio streams
641 static void get_audio_streams_info( producer_avformat this )
643 // Fetch the audio format context
644 AVFormatContext *context = this->audio_format;
648 i < context->nb_streams;
651 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
653 AVCodecContext *codec_context = context->streams[i]->codec;
654 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
656 // If we don't have a codec and we can't initialise it, we can't do much more...
658 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
660 this->audio_streams++;
661 this->audio_max_stream = i;
662 this->total_channels += codec_context->channels;
663 if ( codec_context->channels > this->max_channel )
664 this->max_channel = codec_context->channels;
665 if ( codec_context->sample_rate > this->max_frequency )
666 this->max_frequency = codec_context->sample_rate;
667 avcodec_close( codec_context );
672 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
673 this->audio_streams, this->audio_max_stream, this->total_channels, this->max_channel );
675 // Other audio-specific initializations
676 this->resample_factor = 1.0;
679 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format *format, int width, int height )
682 if ( pix_fmt == PIX_FMT_RGB32 )
684 *format = mlt_image_rgb24a;
685 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
686 width, height, PIX_FMT_RGBA, SWS_BILINEAR, NULL, NULL, NULL);
688 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
689 sws_scale( context, frame->data, frame->linesize, 0, height,
690 output.data, output.linesize);
691 sws_freeContext( context );
693 else if ( *format == mlt_image_yuv420p )
695 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
696 width, height, PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL);
698 output.data[0] = buffer;
699 output.data[1] = buffer + width * height;
700 output.data[2] = buffer + ( 5 * width * height ) / 4;
701 output.linesize[0] = width;
702 output.linesize[1] = width >> 1;
703 output.linesize[2] = width >> 1;
704 sws_scale( context, frame->data, frame->linesize, 0, height,
705 output.data, output.linesize);
706 sws_freeContext( context );
708 else if ( *format == mlt_image_rgb24 )
710 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
711 width, height, PIX_FMT_RGB24, SWS_BILINEAR, NULL, NULL, NULL);
713 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
714 sws_scale( context, frame->data, frame->linesize, 0, height,
715 output.data, output.linesize);
716 sws_freeContext( context );
718 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
720 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
721 width, height, PIX_FMT_RGBA, SWS_BILINEAR, NULL, NULL, NULL);
723 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
724 sws_scale( context, frame->data, frame->linesize, 0, height,
725 output.data, output.linesize);
726 sws_freeContext( context );
730 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
731 width, height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
733 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
734 sws_scale( context, frame->data, frame->linesize, 0, height,
735 output.data, output.linesize);
736 sws_freeContext( context );
739 if ( *format == mlt_image_yuv420p )
742 pict.data[0] = buffer;
743 pict.data[1] = buffer + width * height;
744 pict.data[2] = buffer + ( 5 * width * height ) / 4;
745 pict.linesize[0] = width;
746 pict.linesize[1] = width >> 1;
747 pict.linesize[2] = width >> 1;
748 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
750 else if ( *format == mlt_image_rgb24 )
753 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
754 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
756 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
759 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
760 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
765 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
766 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
771 /** Allocate the image buffer and set it on the frame.
774 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
778 if ( codec_context->width == 0 || codec_context->height == 0 )
781 *width = codec_context->width;
782 *height = codec_context->height;
783 mlt_properties_set_int( frame_properties, "width", *width );
784 mlt_properties_set_int( frame_properties, "height", *height );
786 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
787 size = *width * ( *height + 1 ) * 4;
788 else switch ( *format )
790 case mlt_image_yuv420p:
791 size = *width * 3 * ( *height + 1 ) / 2;
793 case mlt_image_rgb24:
794 size = *width * ( *height + 1 ) * 3;
796 case mlt_image_rgb24a:
797 case mlt_image_opengl:
798 size = *width * ( *height + 1 ) * 4;
801 *format = mlt_image_yuv422;
802 size = *width * ( *height + 1 ) * 2;
806 // Construct the output image
807 *buffer = mlt_pool_alloc( size );
809 mlt_properties_set_data( frame_properties, "image", *buffer, size, mlt_pool_release, NULL );
816 /** Get an image from a frame.
819 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
822 producer_avformat this = mlt_frame_pop_service( frame );
823 mlt_producer producer = this->parent;
825 // Get the properties from the frame
826 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
828 // Obtain the frame number of this frame
829 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
831 // Get the producer properties
832 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;
843 // Get the image cache
844 if ( ! this->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
845 this->image_cache = mlt_cache_init();
846 if ( this->image_cache )
848 mlt_cache_item item = mlt_cache_get( this->image_cache, (void*) position );
849 *buffer = mlt_cache_item_data( item, format );
852 // Set the resolution
853 *width = codec_context->width;
854 *height = codec_context->height;
855 mlt_properties_set_int( frame_properties, "width", *width );
856 mlt_properties_set_int( frame_properties, "height", *height );
862 case mlt_image_yuv420p:
863 size = *width * 3 * ( *height + 1 ) / 2;
865 case mlt_image_rgb24:
866 size = *width * ( *height + 1 ) * 3;
868 case mlt_image_rgb24a:
869 case mlt_image_opengl:
870 size = *width * ( *height + 1 ) * 4;
873 *format = mlt_image_yuv422;
874 size = *width * ( *height + 1 ) * 2;
877 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
878 mlt_properties_set_data( frame_properties, "image", *buffer, size, NULL, NULL );
879 this->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
880 this->got_picture = 1;
893 // Special case pause handling flag
896 // Special case ffwd handling
899 // We may want to use the source fps if available
900 double source_fps = mlt_properties_get_double( properties, "source_fps" );
901 double fps = mlt_producer_get_fps( producer );
903 // This is the physical frame position in the source
904 int req_position = ( int )( position / fps * source_fps + 0.5 );
906 // Determines if we have to decode all frames in a sequence
907 // Temporary hack to improve intra frame only
908 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
909 strcmp( codec_context->codec->name, "dvvideo" ) &&
910 strcmp( codec_context->codec->name, "huffyuv" ) &&
911 strcmp( codec_context->codec->name, "mjpeg" ) &&
912 strcmp( codec_context->codec->name, "rawvideo" );
914 int last_position = this->last_position;
916 // Turn on usage of new seek API and PTS for seeking
917 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
918 if ( mlt_properties_get( properties, "new_seek" ) )
919 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
922 if ( position != this->video_expected || last_position < 0 )
924 if ( this->av_frame && position + 1 == this->video_expected )
926 // We're paused - use last image
929 else if ( !this->seekable && position > this->video_expected && ( position - this->video_expected ) < 250 )
931 // Fast forward - seeking is inefficient for small distances - just ignore following frames
932 ignore = ( int )( ( position - this->video_expected ) / fps * source_fps );
933 codec_context->skip_loop_filter = AVDISCARD_NONREF;
935 else if ( this->seekable && ( position < this->video_expected || position - this->video_expected >= 12 || last_position < 0 ) )
937 if ( use_new_seek && last_position == POSITION_INITIAL )
939 // find first key frame
943 while ( ret >= 0 && toscan-- > 0 )
945 ret = av_read_frame( context, &pkt );
946 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == this->video_index )
948 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) );
949 this->first_pts = pkt.pts;
952 av_free_packet( &pkt );
955 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
958 // Calculate the timestamp for the requested frame
962 timestamp = ( req_position - 0.1 / source_fps ) /
963 ( av_q2d( stream->time_base ) * source_fps );
964 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
965 if ( this->first_pts > 0 )
966 timestamp += this->first_pts;
967 else if ( context->start_time != AV_NOPTS_VALUE )
968 timestamp += context->start_time;
972 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
973 if ( context->start_time != AV_NOPTS_VALUE )
974 timestamp += context->start_time;
977 timestamp -= AV_TIME_BASE;
980 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
981 timestamp, position, this->video_expected, last_position );
983 // Seek to the timestamp
986 codec_context->skip_loop_filter = AVDISCARD_NONREF;
987 av_seek_frame( context, this->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
991 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
994 // Remove the cached info relating to the previous position
995 this->current_position = POSITION_INVALID;
996 this->last_position = POSITION_INVALID;
997 av_freep( &this->av_frame );
1001 // flush any pictures still in decode buffer
1002 avcodec_flush_buffers( codec_context );
1007 // Duplicate the last image if necessary (see comment on rawvideo below)
1008 if ( this->av_frame && this->av_frame->linesize[0] && this->got_picture && this->seekable
1010 || this->current_position == req_position
1011 || ( !use_new_seek && this->current_position > req_position ) ) )
1014 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1016 if ( this->vdpau && this->vdpau->buffer )
1019 picture.data[0] = this->vdpau->buffer;
1020 picture.data[2] = this->vdpau->buffer + codec_context->width * codec_context->height;
1021 picture.data[1] = this->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1022 picture.linesize[0] = codec_context->width;
1023 picture.linesize[1] = codec_context->width / 2;
1024 picture.linesize[2] = codec_context->width / 2;
1025 convert_image( (AVFrame*) &picture, *buffer, PIX_FMT_YUV420P, format, *width, *height );
1029 convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1031 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1036 int int_position = 0;
1037 int decode_errors = 0;
1038 int got_picture = 0;
1040 av_init_packet( &pkt );
1042 // Construct an AVFrame for YUV422 conversion
1043 if ( !this->av_frame )
1044 this->av_frame = avcodec_alloc_frame( );
1046 while( ret >= 0 && !got_picture )
1049 ret = av_read_frame( context, &pkt );
1051 // We only deal with video from the selected video_index
1052 if ( ret >= 0 && pkt.stream_index == this->video_index && pkt.size > 0 )
1054 // Determine time code of the packet
1057 int64_t pts = pkt.pts;
1058 if ( this->first_pts > 0 )
1059 pts -= this->first_pts;
1060 else if ( context->start_time != AV_NOPTS_VALUE )
1061 pts -= context->start_time;
1062 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1063 if ( pkt.pts == AV_NOPTS_VALUE )
1065 this->invalid_pts_counter++;
1066 if ( this->invalid_pts_counter > 20 )
1068 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1069 mlt_properties_set_int( properties, "new_seek", 0 );
1070 int_position = req_position;
1076 this->invalid_pts_counter = 0;
1078 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1079 pkt.pts, req_position, this->current_position, int_position );
1083 if ( pkt.dts != AV_NOPTS_VALUE )
1085 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1086 if ( context->start_time != AV_NOPTS_VALUE )
1087 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1088 last_position = this->last_position;
1089 if ( int_position == last_position )
1090 int_position = last_position + 1;
1094 int_position = req_position;
1096 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1097 pkt.dts, req_position, this->current_position, int_position );
1098 // Make a dumb assumption on streams that contain wild timestamps
1099 if ( abs( req_position - int_position ) > 999 )
1101 int_position = req_position;
1102 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1105 this->last_position = int_position;
1108 if ( must_decode || int_position >= req_position )
1111 if ( g_vdpau && this->vdpau )
1113 if ( g_vdpau->producer != this )
1115 vdpau_decoder_close();
1116 vdpau_decoder_init( this );
1119 this->vdpau->is_decoded = 0;
1122 codec_context->reordered_opaque = pkt.pts;
1123 if ( int_position >= req_position )
1124 codec_context->skip_loop_filter = AVDISCARD_NONE;
1125 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1126 ret = avcodec_decode_video2( codec_context, this->av_frame, &got_picture, &pkt );
1128 ret = avcodec_decode_video( codec_context, this->av_frame, &got_picture, pkt.data, pkt.size );
1130 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1133 if ( ++decode_errors <= 10 )
1146 // Determine time code of the packet
1147 int64_t pts = this->av_frame->reordered_opaque;
1148 if ( this->first_pts > 0 )
1149 pts -= this->first_pts;
1150 else if ( context->start_time != AV_NOPTS_VALUE )
1151 pts -= context->start_time;
1152 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1153 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, this->av_frame->key_frame );
1156 if ( int_position < req_position )
1161 else if ( int_position >= req_position )
1164 codec_context->skip_loop_filter = AVDISCARD_NONE;
1166 else if ( ignore -- )
1171 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1172 av_free_packet( &pkt );
1174 else if ( ret >= 0 )
1176 av_free_packet( &pkt );
1179 // Now handle the picture if we have one
1182 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1187 if ( this->vdpau->is_decoded )
1189 struct vdpau_render_state *render = (struct vdpau_render_state*) this->av_frame->data[0];
1191 uint32_t pitches[3];
1192 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1195 if ( !this->vdpau->buffer )
1196 this->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1197 picture.data[0] = planes[0] = this->vdpau->buffer;
1198 picture.data[2] = planes[1] = this->vdpau->buffer + codec_context->width * codec_context->height;
1199 picture.data[1] = planes[2] = this->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1200 picture.linesize[0] = pitches[0] = codec_context->width;
1201 picture.linesize[1] = pitches[1] = codec_context->width / 2;
1202 picture.linesize[2] = pitches[2] = codec_context->width / 2;
1204 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1205 if ( status == VDP_STATUS_OK )
1207 convert_image( (AVFrame*) &picture, *buffer, PIX_FMT_YUV420P, format, *width, *height );
1211 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1212 this->vdpau->is_decoded = 0;
1217 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1223 convert_image( this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1224 this->top_field_first |= this->av_frame->top_field_first;
1225 this->current_position = int_position;
1226 this->got_picture = 1;
1238 if ( this->got_picture && image_size > 0 && this->image_cache )
1240 // Copy buffer to image cache
1241 uint8_t *image = mlt_pool_alloc( image_size );
1242 memcpy( image, *buffer, image_size );
1243 mlt_cache_put( this->image_cache, (void*) position, image, *format, mlt_pool_release );
1247 // Set the progressive flag
1248 if ( mlt_properties_get( properties, "force_progressive" ) )
1249 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1250 else if ( this->av_frame )
1251 mlt_properties_set_int( frame_properties, "progressive", !this->av_frame->interlaced_frame );
1253 // Set the field order property for this frame
1254 mlt_properties_set_int( frame_properties, "top_field_first", this->top_field_first );
1256 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1257 this->video_expected = position + 1;
1259 return !this->got_picture;
1262 /** Process properties as AVOptions and apply to AV context obj
1265 static void apply_properties( void *obj, mlt_properties properties, int flags )
1268 int count = mlt_properties_count( properties );
1269 for ( i = 0; i < count; i++ )
1271 const char *opt_name = mlt_properties_get_name( properties, i );
1272 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1273 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1276 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1277 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1278 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1279 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1281 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1287 /** Initialize the video codec context.
1290 static int video_codec_init( producer_avformat this, int index, mlt_properties properties )
1292 // Initialise the codec if necessary
1293 if ( !this->video_codec )
1295 // Get the video stream
1296 AVStream *stream = this->video_format->streams[ index ];
1298 // Get codec context
1299 AVCodecContext *codec_context = stream->codec;
1302 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1304 if ( codec_context->codec_id == CODEC_ID_H264 )
1306 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1308 if ( vdpau_init( this ) )
1310 this->video_codec = codec_context;
1311 if ( !vdpau_decoder_init( this ) )
1312 vdpau_decoder_close();
1316 codec = avcodec_find_decoder( codec_context->codec_id );
1320 // Initialise multi-threading
1321 int thread_count = mlt_properties_get_int( properties, "threads" );
1322 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1323 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1324 if ( thread_count > 1 )
1326 avcodec_thread_init( codec_context, thread_count );
1327 codec_context->thread_count = thread_count;
1330 // If we don't have a codec and we can't initialise it, we can't do much more...
1332 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1334 // Now store the codec with its destructor
1335 this->video_codec = codec_context;
1339 // Remember that we can't use this later
1340 this->video_index = -1;
1344 // Process properties as AVOptions
1345 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1347 // Reset some image properties
1348 mlt_properties_set_int( properties, "width", this->video_codec->width );
1349 mlt_properties_set_int( properties, "height", this->video_codec->height );
1350 // For DV, we'll just use the saved aspect ratio
1351 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1352 mlt_properties_set_double( properties, "aspect_ratio", get_aspect_ratio( stream, this->video_codec, NULL ) );
1354 // Determine the fps first from the codec
1355 double source_fps = (double) this->video_codec->time_base.den /
1356 ( this->video_codec->time_base.num == 0 ? 1 : this->video_codec->time_base.num );
1358 if ( mlt_properties_get( properties, "force_fps" ) )
1360 source_fps = mlt_properties_get_double( properties, "force_fps" );
1361 stream->time_base = av_d2q( source_fps, 255 );
1365 // If the muxer reports a frame rate different than the codec
1366 double muxer_fps = av_q2d( stream->r_frame_rate );
1367 // Choose the lesser - the wrong tends to be off by some multiple of 10
1368 source_fps = FFMIN( source_fps, muxer_fps );
1371 // We'll use fps if it's available
1372 if ( source_fps > 0 )
1373 mlt_properties_set_double( properties, "source_fps", source_fps );
1375 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( this->parent ) );
1377 return this->video_codec && this->video_index > -1;
1380 /** Set up video handling.
1383 static void producer_set_up_video( producer_avformat this, mlt_frame frame )
1386 mlt_producer producer = this->parent;
1388 // Get the properties
1389 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1391 // Fetch the video format context
1392 AVFormatContext *context = this->video_format;
1394 // Get the video_index
1395 int index = mlt_properties_get_int( properties, "video_index" );
1397 // Reopen the file if necessary
1398 if ( !context && index > -1 )
1400 mlt_events_block( properties, producer );
1401 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1402 mlt_properties_get( properties, "resource" ) );
1403 context = this->video_format;
1404 if ( this->dummy_context )
1407 av_close_input_file( this->dummy_context );
1410 this->dummy_context = NULL;
1411 mlt_events_unblock( properties, producer );
1412 if ( this->audio_format )
1413 get_audio_streams_info( this );
1415 // Process properties as AVOptions
1416 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1419 // Exception handling for video_index
1420 if ( context && index >= (int) context->nb_streams )
1422 // Get the last video stream
1423 for ( index = context->nb_streams - 1;
1424 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1426 mlt_properties_set_int( properties, "video_index", index );
1428 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1430 // Invalidate the video stream
1432 mlt_properties_set_int( properties, "video_index", index );
1435 // Update the video properties if the index changed
1436 if ( index != this->video_index )
1438 // Reset the video properties if the index changed
1439 this->video_index = index;
1440 if ( this->video_codec )
1443 avcodec_close( this->video_codec );
1446 this->video_codec = NULL;
1449 // Get the frame properties
1450 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1453 if ( context && index > -1 && video_codec_init( this, index, properties ) )
1455 // Set the frame properties
1456 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1457 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1458 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1460 // Set the width and height
1461 mlt_properties_set_int( frame_properties, "width", this->video_codec->width );
1462 mlt_properties_set_int( frame_properties, "height", this->video_codec->height );
1463 mlt_properties_set_int( frame_properties, "real_width", this->video_codec->width );
1464 mlt_properties_set_int( frame_properties, "real_height", this->video_codec->height );
1465 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1467 // Add our image operation
1468 mlt_frame_push_service( frame, this );
1469 mlt_frame_push_get_image( frame, producer_get_image );
1473 // If something failed, use test card image
1474 mlt_properties_set_int( frame_properties, "test_image", 1 );
1478 static int seek_audio( producer_avformat this, mlt_position position, double timecode, int *ignore )
1482 // Seek if necessary
1483 if ( position != this->audio_expected )
1485 if ( position + 1 == this->audio_expected )
1487 // We're paused - silence required
1490 else if ( !this->seekable && position > this->audio_expected && ( position - this->audio_expected ) < 250 )
1492 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1493 *ignore = position - this->audio_expected;
1495 else if ( position < this->audio_expected || position - this->audio_expected >= 12 )
1497 AVFormatContext *context = this->audio_format;
1498 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1499 if ( context->start_time != AV_NOPTS_VALUE )
1500 timestamp += context->start_time;
1501 if ( timestamp < 0 )
1504 // Set to the real timecode
1505 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1508 // Clear the usage in the audio buffer
1509 int i = MAX_AUDIO_STREAMS + 1;
1511 this->audio_used[i - 1] = 0;
1517 static int decode_audio( producer_avformat this, int *ignore, AVPacket *pkt, int channels, int samples, double timecode, double fps )
1519 // Fetch the audio_format
1520 AVFormatContext *context = this->audio_format;
1522 // Get the current stream index
1523 int index = pkt->stream_index;
1525 // Get codec context
1526 AVCodecContext *codec_context = this->audio_codec[ index ];
1528 // Obtain the resample context if it exists (not always needed)
1529 ReSampleContext *resample = this->audio_resample[ index ];
1531 // Obtain the audio buffers
1532 int16_t *audio_buffer = this->audio_buffer[ index ];
1533 int16_t *decode_buffer = this->decode_buffer[ index ];
1535 int audio_used = this->audio_used[ index ];
1536 uint8_t *ptr = pkt->data;
1537 int len = pkt->size;
1540 while ( ptr && ret >= 0 && len > 0 )
1542 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1545 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1546 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, pkt );
1547 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1548 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1550 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1561 // If decoded successfully
1562 if ( data_size > 0 )
1564 // Figure out how many samples will be needed after resampling
1565 int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1566 int samples_needed = this->resample_factor * convert_samples + 1;
1568 // Resize audio buffer to prevent overflow
1569 if ( audio_used * channels + samples_needed > this->audio_buffer_size[ index ] )
1571 this->audio_buffer_size[ index ] *= 2;
1572 audio_buffer = this->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, this->audio_buffer_size[ index ] * sizeof(int16_t) );
1576 // Copy to audio buffer while resampling
1577 int16_t *source = decode_buffer;
1578 int16_t *dest = &audio_buffer[ audio_used * channels ];
1579 audio_used += audio_resample( resample, dest, source, convert_samples );
1583 // Straight copy to audio buffer
1584 memcpy( &audio_buffer[ audio_used * codec_context->channels ], decode_buffer, data_size );
1585 audio_used += convert_samples;
1589 while ( *ignore && audio_used > samples )
1592 audio_used -= samples;
1593 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) ],
1594 audio_used * sizeof( int16_t ) );
1599 // If we're behind, ignore this packet
1600 if ( pkt->pts >= 0 )
1602 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt->pts;
1603 int req_position = ( int )( timecode * fps + 0.5 );
1604 int int_position = ( int )( current_pts * fps + 0.5 );
1605 if ( context->start_time != AV_NOPTS_VALUE )
1606 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1608 if ( this->seekable && *ignore == 0 )
1610 if ( int_position < req_position )
1611 // We are behind, so skip some
1613 else if ( int_position > req_position + 2 )
1614 // We are ahead, so seek backwards some more
1615 seek_audio( this, req_position, timecode - 1.0, ignore );
1619 this->audio_used[ index ] = audio_used;
1624 /** Get the audio from a frame.
1627 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1630 producer_avformat this = mlt_frame_pop_audio( frame );
1632 // Obtain the frame number of this frame
1633 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1635 // Calculate the real time code
1636 double real_timecode = producer_time_of_frame( this->parent, position );
1638 // Get the producer fps
1639 double fps = mlt_producer_get_fps( this->parent );
1641 // Number of frames to ignore (for ffwd)
1644 // Flag for paused (silence)
1645 int paused = seek_audio( this, position, real_timecode, &ignore );
1647 // Fetch the audio_format
1648 AVFormatContext *context = this->audio_format;
1650 // Determine the tracks to use
1651 int index = this->audio_index;
1652 int index_max = this->audio_index + 1;
1653 if ( this->audio_index == INT_MAX )
1656 index_max = context->nb_streams;
1657 *channels = this->total_channels;
1658 *frequency = this->max_frequency;
1661 // Initialize the resamplers and buffers
1662 for ( ; index < index_max; index++ )
1664 // Get codec context
1665 AVCodecContext *codec_context = this->audio_codec[ index ];
1667 if ( codec_context && !this->audio_buffer[ index ] )
1669 // Check for resample and create if necessary
1670 if ( codec_context->channels <= 2 )
1672 // Determine by how much resampling will increase number of samples
1673 double resample_factor = this->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
1674 resample_factor *= (double) *frequency / codec_context->sample_rate;
1675 if ( resample_factor > this->resample_factor )
1676 this->resample_factor = resample_factor;
1678 // Create the resampler
1679 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1680 this->audio_resample[ index ] = av_audio_resample_init(
1681 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1682 codec_context->channels, *frequency, codec_context->sample_rate,
1683 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1685 this->audio_resample[ index ] = audio_resample_init(
1686 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1687 codec_context->channels, *frequency, codec_context->sample_rate );
1692 codec_context->request_channels = this->audio_index == INT_MAX ? codec_context->channels : *channels;
1695 // Check for audio buffer and create if necessary
1696 this->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1697 this->audio_buffer[ index ] = mlt_pool_alloc( this->audio_buffer_size[ index ] * sizeof( int16_t ) );
1699 // Check for decoder buffer and create if necessary
1700 this->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1704 // Get the audio if required
1711 av_init_packet( &pkt );
1713 // If not resampling, give consumer more than requested.
1714 // It requested number samples based on requested frame rate.
1715 // Do not clean this up with a samples *= ...!
1716 if ( this->audio_index != INT_MAX && ! this->audio_resample[ this->audio_index ] )
1717 *samples = *samples * this->audio_codec[ this->audio_index ]->sample_rate / *frequency;
1719 while ( ret >= 0 && !got_audio )
1721 // Check if the buffer already contains the samples required
1722 if ( this->audio_index != INT_MAX && this->audio_used[ this->audio_index ] >= *samples && ignore == 0 )
1729 ret = av_read_frame( context, &pkt );
1731 // We only deal with audio from the selected audio index
1732 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == this->audio_index ||
1733 ( this->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
1735 int channels2 = this->audio_index == INT_MAX ? this->audio_codec[pkt.stream_index]->channels : *channels;
1736 ret = decode_audio( this, &ignore, &pkt, channels2, *samples, real_timecode, fps );
1738 av_free_packet( &pkt );
1740 if ( this->audio_index == INT_MAX && ret >= 0 )
1742 // Determine if there is enough audio for all streams
1744 for ( index = 0; index < context->nb_streams; index++ )
1746 if ( this->audio_codec[ index ] && this->audio_used[ index ] < *samples )
1752 // Allocate and set the frame's audio buffer
1753 int size = *samples * *channels * sizeof(int16_t);
1754 *buffer = mlt_pool_alloc( size );
1755 *format = mlt_audio_s16;
1756 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
1758 // Interleave tracks if audio_index=all
1759 if ( this->audio_index == INT_MAX )
1761 int16_t *dest = *buffer;
1763 for ( i = 0; i < *samples; i++ )
1765 for ( index = 0; index < index_max; index++ )
1766 if ( this->audio_codec[ index ] )
1768 int current_channels = this->audio_codec[ index ]->channels;
1769 int16_t *src = this->audio_buffer[ index ] + i * current_channels;
1770 memcpy( dest, src, current_channels * sizeof(int16_t) );
1771 dest += current_channels;
1774 for ( index = 0; index < index_max; index++ )
1775 if ( this->audio_codec[ index ] && this->audio_used[ index ] >= *samples )
1777 int current_channels = this->audio_codec[ index ]->channels;
1778 int16_t *src = this->audio_buffer[ index ] + *samples * current_channels;
1779 this->audio_used[index] -= *samples;
1780 memmove( this->audio_buffer[ index ], src, this->audio_used[ index ] * current_channels * sizeof(int16_t) );
1783 // Copy a single track to the output buffer
1786 index = this->audio_index;
1788 // Now handle the audio if we have enough
1789 if ( this->audio_used[ index ] >= *samples )
1791 int16_t *src = this->audio_buffer[ index ];
1792 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
1793 this->audio_used[ index ] -= *samples;
1794 memmove( src, &src[ *samples * *channels ], this->audio_used[ index ] * *channels * sizeof(int16_t) );
1798 // Otherwise fill with silence
1799 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
1801 if ( !this->audio_resample[ index ] )
1803 // TODO: uncomment and remove following line when full multi-channel support is ready
1804 // *channels = codec_context->channels;
1805 *frequency = this->audio_codec[ index ]->sample_rate;
1811 // Get silence and don't touch the context
1812 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1815 // Regardless of speed (other than paused), we expect to get the next frame
1817 this->audio_expected = position + 1;
1822 /** Initialize the audio codec context.
1825 static int audio_codec_init( producer_avformat this, int index, mlt_properties properties )
1827 // Initialise the codec if necessary
1828 if ( !this->audio_codec[ index ] )
1830 // Get codec context
1831 AVCodecContext *codec_context = this->audio_format->streams[index]->codec;
1834 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1836 // If we don't have a codec and we can't initialise it, we can't do much more...
1838 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1840 // Now store the codec with its destructor
1841 if ( this->audio_codec[ index ] )
1842 avcodec_close( this->audio_codec[ index ] );
1843 this->audio_codec[ index ] = codec_context;
1847 // Remember that we can't use this later
1848 this->audio_index = -1;
1852 // Process properties as AVOptions
1853 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1855 return this->audio_codec[ index ] && this->audio_index > -1;
1858 /** Set up audio handling.
1861 static void producer_set_up_audio( producer_avformat this, mlt_frame frame )
1864 mlt_producer producer = this->parent;
1866 // Get the properties
1867 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1869 // Fetch the audio format context
1870 AVFormatContext *context = this->audio_format;
1872 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1874 // Get the audio_index
1875 int index = mlt_properties_get_int( properties, "audio_index" );
1877 // Handle all audio tracks
1878 if ( this->audio_index > -1 &&
1879 mlt_properties_get( properties, "audio_index" ) &&
1880 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
1883 // Reopen the file if necessary
1884 if ( !context && this->audio_index > -1 && index > -1 )
1886 mlt_events_block( properties, producer );
1887 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1888 mlt_properties_get( properties, "resource" ) );
1889 context = this->audio_format;
1890 if ( this->dummy_context )
1893 av_close_input_file( this->dummy_context );
1896 this->dummy_context = NULL;
1897 mlt_events_unblock( properties, producer );
1898 get_audio_streams_info( this );
1901 // Exception handling for audio_index
1902 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
1904 for ( index = context->nb_streams - 1;
1905 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
1907 mlt_properties_set_int( properties, "audio_index", index );
1909 if ( context && index > -1 && index < INT_MAX &&
1910 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1912 index = this->audio_index;
1913 mlt_properties_set_int( properties, "audio_index", index );
1916 // Update the audio properties if the index changed
1917 if ( context && index > -1 && index != this->audio_index )
1919 if ( this->audio_codec[ this->audio_index ] )
1922 avcodec_close( this->audio_codec[ this->audio_index ] );
1925 this->audio_codec[ this->audio_index ] = NULL;
1927 if ( this->audio_index != -1 )
1928 this->audio_index = index;
1933 if ( context && index == INT_MAX )
1935 mlt_properties_set_int( frame_properties, "frequency", this->max_frequency );
1936 mlt_properties_set_int( frame_properties, "channels", this->total_channels );
1937 for ( index = 0; index < context->nb_streams; index++ )
1939 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
1940 audio_codec_init( this, index, properties );
1943 else if ( context && index > -1 && audio_codec_init( this, index, properties ) )
1945 // Set the frame properties
1946 if ( index < INT_MAX )
1948 mlt_properties_set_int( frame_properties, "frequency", this->audio_codec[ index ]->sample_rate );
1949 mlt_properties_set_int( frame_properties, "channels", this->audio_codec[ index ]->channels );
1952 if ( context && index > -1 )
1954 // Add our audio operation
1955 mlt_frame_push_audio( frame, this );
1956 mlt_frame_push_audio( frame, producer_get_audio );
1960 /** Our get frame implementation.
1963 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
1965 // Access the private data
1966 mlt_service service = MLT_PRODUCER_SERVICE( producer );
1967 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
1968 producer_avformat this = mlt_cache_item_data( cache_item, NULL );
1973 this = calloc( 1, sizeof( struct producer_avformat_s ) );
1974 producer->child = this;
1975 this->parent = producer;
1976 mlt_service_cache_put( service, "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
1977 cache_item = mlt_service_cache_get( service, "producer_avformat" );
1980 // Create an empty frame
1981 *frame = mlt_frame_init( service);
1985 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
1989 mlt_cache_item_close( cache_item );
1993 // Update timecode on the frame we're creating
1994 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
1996 // Set the position of this producer
1997 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2000 producer_set_up_video( this, *frame );
2003 producer_set_up_audio( this, *frame );
2005 // Calculate the next timecode
2006 mlt_producer_prepare_next( producer );
2011 static void producer_avformat_close( producer_avformat this )
2013 mlt_log_debug( NULL, "producer_avformat_close\n" );
2015 av_free( this->av_frame );
2018 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2020 if ( this->audio_resample[i] )
2021 audio_resample_close( this->audio_resample[i] );
2022 mlt_pool_release( this->audio_buffer[i] );
2023 av_free( this->decode_buffer[i] );
2024 if ( this->audio_codec[i] )
2025 avcodec_close( this->audio_codec[i] );
2027 if ( this->video_codec )
2028 avcodec_close( this->video_codec );
2029 if ( this->dummy_context )
2030 av_close_input_file( this->dummy_context );
2031 if ( this->audio_format )
2032 av_close_input_file( this->audio_format );
2033 if ( this->video_format )
2034 av_close_input_file( this->video_format );
2037 vdpau_producer_close( this );
2039 if ( this->image_cache )
2040 mlt_cache_close( this->image_cache );
2044 static void producer_close( mlt_producer parent )
2047 parent->close = NULL;
2048 mlt_producer_close( parent );