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 struct SwsContext *swscale;
118 typedef struct producer_avformat_s *producer_avformat;
120 // Forward references.
121 static int producer_open( producer_avformat this, mlt_profile profile, char *file );
122 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
123 static void producer_avformat_close( producer_avformat );
124 static void producer_close( mlt_producer parent );
130 /** Constructor for libavformat.
133 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
137 // Report information about available demuxers and codecs as YAML Tiny
138 if ( file && strstr( file, "f-list" ) )
140 fprintf( stderr, "---\nformats:\n" );
141 AVInputFormat *format = NULL;
142 while ( ( format = av_iformat_next( format ) ) )
143 fprintf( stderr, " - %s\n", format->name );
144 fprintf( stderr, "...\n" );
147 if ( file && strstr( file, "acodec-list" ) )
149 fprintf( stderr, "---\naudio_codecs:\n" );
150 AVCodec *codec = NULL;
151 while ( ( codec = av_codec_next( codec ) ) )
152 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
153 fprintf( stderr, " - %s\n", codec->name );
154 fprintf( stderr, "...\n" );
157 if ( file && strstr( file, "vcodec-list" ) )
159 fprintf( stderr, "---\nvideo_codecs:\n" );
160 AVCodec *codec = NULL;
161 while ( ( codec = av_codec_next( codec ) ) )
162 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
163 fprintf( stderr, " - %s\n", codec->name );
164 fprintf( stderr, "...\n" );
168 // Check that we have a non-NULL argument
171 // Construct the producer
172 mlt_producer producer = calloc( 1, sizeof( struct mlt_producer_s ) );
173 producer_avformat this = calloc( 1, sizeof( struct producer_avformat_s ) );
176 if ( mlt_producer_init( producer, this ) == 0 )
178 this->parent = producer;
180 // Get the properties
181 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
183 // Set the resource property (required for all producers)
184 mlt_properties_set( properties, "resource", file );
186 // Register transport implementation with the producer
187 producer->close = (mlt_destructor) producer_close;
189 // Register our get_frame implementation
190 producer->get_frame = producer_get_frame;
192 if ( strcmp( service, "avformat-novalidate" ) )
195 if ( producer_open( this, profile, file ) != 0 )
198 mlt_producer_close( producer );
203 // Close the file to release resources for large playlists - reopen later as needed
205 if ( this->dummy_context )
206 av_close_input_file( this->dummy_context );
207 this->dummy_context = NULL;
208 if ( this->audio_format )
209 av_close_input_file( this->audio_format );
210 this->audio_format = NULL;
211 if ( this->video_format )
212 av_close_input_file( this->video_format );
213 this->video_format = NULL;
216 // Default the user-selectable indices from the auto-detected indices
217 mlt_properties_set_int( properties, "audio_index", this->audio_index );
218 mlt_properties_set_int( properties, "video_index", this->video_index );
221 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
223 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
229 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
231 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
239 /** Find the default streams.
242 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
247 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
249 // Allow for multiple audio and video streams in the file and select first of each (if available)
250 for( i = 0; i < context->nb_streams; i++ )
252 // Get the codec context
253 AVStream *stream = context->streams[ i ];
254 if ( ! stream ) continue;
255 AVCodecContext *codec_context = stream->codec;
256 if ( ! codec_context ) continue;
257 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
258 if ( ! codec ) continue;
260 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
262 // Determine the type and obtain the first index of each type
263 switch( codec_context->codec_type )
265 case CODEC_TYPE_VIDEO:
266 if ( *video_index < 0 )
268 mlt_properties_set( meta_media, key, "video" );
269 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
270 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
271 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
272 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
273 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
275 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
276 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
277 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
278 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
279 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
280 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
281 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
283 case CODEC_TYPE_AUDIO:
284 if ( *audio_index < 0 )
286 mlt_properties_set( meta_media, key, "audio" );
287 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
288 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
289 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
291 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
292 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
293 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
294 mlt_properties_set_int( meta_media, key, codec_context->channels );
299 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
300 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
301 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
302 mlt_properties_set( meta_media, key, codec->name );
303 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
304 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
305 mlt_properties_set( meta_media, key, codec->long_name );
307 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
308 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
309 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
310 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
311 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
312 // mlt_properties_set_int( meta_media, key, codec_context->profile );
313 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
314 // mlt_properties_set_int( meta_media, key, codec_context->level );
320 static inline int dv_is_pal( AVPacket *pkt )
322 return pkt->data[3] & 0x80;
325 static int dv_is_wide( AVPacket *pkt )
327 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
329 for ( ; i < pkt->size; i += 5 /* packet size */ )
331 if ( pkt->data[ i ] == 0x61 )
333 uint8_t x = pkt->data[ i + 2 ] & 0x7;
334 return ( x == 2 ) || ( x == 7 );
340 static double get_aspect_ratio( AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
342 double aspect_ratio = 1.0;
344 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
348 if ( dv_is_pal( pkt ) )
350 aspect_ratio = dv_is_wide( pkt )
351 ? 64.0/45.0 // 16:9 PAL
352 : 16.0/15.0; // 4:3 PAL
356 aspect_ratio = dv_is_wide( pkt )
357 ? 32.0/27.0 // 16:9 NTSC
358 : 8.0/9.0; // 4:3 NTSC
364 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
365 stream->sample_aspect_ratio;
367 codec_context->sample_aspect_ratio;
369 // Override FFmpeg's notion of DV aspect ratios, which are
370 // based upon a width of 704. Since we do not have a normaliser
371 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
372 // we just coerce the values to facilitate a passive behaviour through
373 // the rescale normaliser when using equivalent producers and consumers.
374 // = display_aspect / (width * height)
375 if ( ar.num == 10 && ar.den == 11 )
376 aspect_ratio = 8.0/9.0; // 4:3 NTSC
377 else if ( ar.num == 59 && ar.den == 54 )
378 aspect_ratio = 16.0/15.0; // 4:3 PAL
379 else if ( ar.num == 40 && ar.den == 33 )
380 aspect_ratio = 32.0/27.0; // 16:9 NTSC
381 else if ( ar.num == 118 && ar.den == 81 )
382 aspect_ratio = 64.0/45.0; // 16:9 PAL
387 AVRational codec_sar = codec_context->sample_aspect_ratio;
388 AVRational stream_sar =
389 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
390 stream->sample_aspect_ratio;
394 if ( codec_sar.num > 0 )
395 aspect_ratio = av_q2d( codec_sar );
396 else if ( stream_sar.num > 0 )
397 aspect_ratio = av_q2d( stream_sar );
405 static int producer_open( producer_avformat this, mlt_profile profile, char *file )
407 // Return an error code (0 == no error)
410 // Context for avformat
411 AVFormatContext *context = NULL;
413 // Get the properties
414 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this->parent );
416 // We will treat everything with the producer fps
417 double fps = mlt_profile_fps( profile );
419 // Lock the mutex now
422 // If "MRL", then create AVInputFormat
423 AVInputFormat *format = NULL;
424 AVFormatParameters *params = NULL;
425 char *standard = NULL;
426 char *mrl = strchr( file, ':' );
428 // AV option (0 = both, 1 = video, 2 = audio)
431 // Only if there is not a protocol specification that avformat can handle
432 if ( mrl && !url_exist( file ) )
434 // 'file' becomes format abbreviation
438 format = av_find_input_format( file );
440 // Eat the format designator
446 params = calloc( sizeof( AVFormatParameters ), 1 );
448 // These are required by video4linux (defaults)
450 params->height = 480;
451 params->time_base= (AVRational){1,25};
452 // params->device = file;
453 params->channels = 2;
454 params->sample_rate = 48000;
458 mrl = strchr( file, '?' );
462 char *name = strdup( ++mrl );
463 char *value = strchr( name, ':' );
468 char *t = strchr( value, '&' );
471 if ( !strcmp( name, "frame_rate" ) )
472 params->time_base.den = atoi( value );
473 else if ( !strcmp( name, "frame_rate_base" ) )
474 params->time_base.num = atoi( value );
475 else if ( !strcmp( name, "sample_rate" ) )
476 params->sample_rate = atoi( value );
477 else if ( !strcmp( name, "channels" ) )
478 params->channels = atoi( value );
479 else if ( !strcmp( name, "width" ) )
480 params->width = atoi( value );
481 else if ( !strcmp( name, "height" ) )
482 params->height = atoi( value );
483 else if ( !strcmp( name, "standard" ) )
485 standard = strdup( value );
486 params->standard = standard;
488 else if ( !strcmp( name, "av" ) )
492 mrl = strchr( mrl, '&' );
496 // Now attempt to open the file
497 error = av_open_input_file( &context, file, format, 0, params ) < 0;
499 // Cleanup AVFormatParameters
503 // If successful, then try to get additional info
506 // Get the stream info
507 error = av_find_stream_info( context ) < 0;
509 // Continue if no error
512 // We will default to the first audio and video streams found
513 int audio_index = -1;
514 int video_index = -1;
516 // Now set properties where we can (use default unknowns if required)
517 if ( context->duration != AV_NOPTS_VALUE )
519 // This isn't going to be accurate for all formats
520 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + 0.5 );
521 mlt_properties_set_position( properties, "out", frames - 1 );
522 mlt_properties_set_position( properties, "length", frames );
525 // Find default audio and video streams
526 find_default_streams( properties, context, &audio_index, &video_index );
528 if ( context->start_time != AV_NOPTS_VALUE )
529 this->start_time = context->start_time;
531 // Check if we're seekable (something funny about mpeg here :-/)
532 if ( strncmp( file, "pipe:", 5 ) &&
533 strncmp( file, "/dev/", 5 ) &&
534 strncmp( file, "http:", 5 ) &&
535 strncmp( file, "udp:", 4 ) &&
536 strncmp( file, "tcp:", 4 ) &&
537 strncmp( file, "rtsp:", 5 ) &&
538 strncmp( file, "rtp:", 4 ) )
540 this->seekable = av_seek_frame( context, -1, this->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
541 mlt_properties_set_int( properties, "seekable", this->seekable );
542 this->dummy_context = context;
543 av_open_input_file( &context, file, NULL, 0, NULL );
544 av_find_stream_info( context );
547 // Store selected audio and video indexes on properties
548 this->audio_index = audio_index;
549 this->video_index = video_index;
550 this->first_pts = -1;
551 this->last_position = POSITION_INITIAL;
553 // Fetch the width, height and aspect ratio
554 if ( video_index != -1 )
556 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
557 mlt_properties_set_int( properties, "width", codec_context->width );
558 mlt_properties_set_int( properties, "height", codec_context->height );
560 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
562 // Fetch the first frame of DV so we can read it directly
567 ret = av_read_frame( context, &pkt );
568 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
570 mlt_properties_set_double( properties, "aspect_ratio",
571 get_aspect_ratio( context->streams[ video_index ], codec_context, &pkt ) );
578 mlt_properties_set_double( properties, "aspect_ratio",
579 get_aspect_ratio( context->streams[ video_index ], codec_context, NULL ) );
584 if ( context->title )
585 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
586 if ( context->author )
587 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
588 if ( context->copyright )
589 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
590 if ( context->comment )
591 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
592 if ( context->album )
593 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
595 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
596 if ( context->track )
597 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
599 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
600 if ( av == 0 && audio_index != -1 && video_index != -1 )
602 // We'll use the open one as our video_format
603 this->video_format = context;
605 // And open again for our audio context
606 av_open_input_file( &context, file, NULL, 0, NULL );
607 av_find_stream_info( context );
610 this->audio_format = context;
612 else if ( av != 2 && video_index != -1 )
614 // We only have a video context
615 this->video_format = context;
617 else if ( audio_index != -1 )
619 // We only have an audio context
620 this->audio_format = context;
624 // Something has gone wrong
630 // Unlock the mutex now
636 /** Convert a frame position to a time code.
639 static double producer_time_of_frame( mlt_producer this, mlt_position position )
641 return ( double )position / mlt_producer_get_fps( this );
644 // Collect information about all audio streams
646 static void get_audio_streams_info( producer_avformat this )
648 // Fetch the audio format context
649 AVFormatContext *context = this->audio_format;
653 i < context->nb_streams;
656 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
658 AVCodecContext *codec_context = context->streams[i]->codec;
659 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
661 // If we don't have a codec and we can't initialise it, we can't do much more...
663 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
665 this->audio_streams++;
666 this->audio_max_stream = i;
667 this->total_channels += codec_context->channels;
668 if ( codec_context->channels > this->max_channel )
669 this->max_channel = codec_context->channels;
670 if ( codec_context->sample_rate > this->max_frequency )
671 this->max_frequency = codec_context->sample_rate;
672 avcodec_close( codec_context );
677 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
678 this->audio_streams, this->audio_max_stream, this->total_channels, this->max_channel );
680 // Other audio-specific initializations
681 this->resample_factor = 1.0;
684 static inline void convert_image( void **ctx, AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format *format, int width, int height )
687 struct SwsContext **context = ctx;
688 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
691 flags |= SWS_CPU_CAPS_MMX;
694 flags |= SWS_CPU_CAPS_MMX2;
697 if ( pix_fmt == PIX_FMT_RGB32 )
699 *format = mlt_image_rgb24a;
700 *context = sws_getCachedContext( *context, width, height, pix_fmt,
701 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
703 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
704 sws_scale( *context, frame->data, frame->linesize, 0, height,
705 output.data, output.linesize);
707 else if ( *format == mlt_image_yuv420p )
709 *context = sws_getCachedContext( *context, width, height, pix_fmt,
710 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
712 output.data[0] = buffer;
713 output.data[1] = buffer + width * height;
714 output.data[2] = buffer + ( 5 * width * height ) / 4;
715 output.linesize[0] = width;
716 output.linesize[1] = width >> 1;
717 output.linesize[2] = width >> 1;
718 sws_scale( *context, frame->data, frame->linesize, 0, height,
719 output.data, output.linesize);
721 else if ( *format == mlt_image_rgb24 )
723 *context = sws_getCachedContext( *context, width, height, pix_fmt,
724 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
726 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
727 sws_scale( *context, frame->data, frame->linesize, 0, height,
728 output.data, output.linesize);
730 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
732 *context = sws_getCachedContext( *context, width, height, pix_fmt,
733 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
735 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
736 sws_scale( *context, frame->data, frame->linesize, 0, height,
737 output.data, output.linesize);
741 *context = sws_getCachedContext( *context, width, height, pix_fmt,
742 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
744 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
745 sws_scale( *context, frame->data, frame->linesize, 0, height,
746 output.data, output.linesize);
749 if ( *format == mlt_image_yuv420p )
752 pict.data[0] = buffer;
753 pict.data[1] = buffer + width * height;
754 pict.data[2] = buffer + ( 5 * width * height ) / 4;
755 pict.linesize[0] = width;
756 pict.linesize[1] = width >> 1;
757 pict.linesize[2] = width >> 1;
758 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
760 else if ( *format == mlt_image_rgb24 )
763 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
764 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
766 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
769 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
770 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
775 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
776 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
781 /** Allocate the image buffer and set it on the frame.
784 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
788 if ( codec_context->width == 0 || codec_context->height == 0 )
791 *width = codec_context->width;
792 *height = codec_context->height;
794 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
795 size = *width * ( *height + 1 ) * 4;
796 else switch ( *format )
798 case mlt_image_yuv420p:
799 size = *width * 3 * ( *height + 1 ) / 2;
801 case mlt_image_rgb24:
802 size = *width * ( *height + 1 ) * 3;
804 case mlt_image_rgb24a:
805 case mlt_image_opengl:
806 size = *width * ( *height + 1 ) * 4;
809 *format = mlt_image_yuv422;
810 size = *width * ( *height + 1 ) * 2;
814 // Construct the output image
815 *buffer = mlt_pool_alloc( size );
817 mlt_properties_set_data( frame_properties, "image", *buffer, size, mlt_pool_release, NULL );
824 /** Get an image from a frame.
827 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
830 producer_avformat this = mlt_frame_pop_service( frame );
831 mlt_producer producer = this->parent;
833 // Get the properties from the frame
834 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
836 // Obtain the frame number of this frame
837 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
839 // Get the producer properties
840 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
842 // Fetch the video format context
843 AVFormatContext *context = this->video_format;
845 // Get the video stream
846 AVStream *stream = context->streams[ this->video_index ];
849 AVCodecContext *codec_context = stream->codec;
851 // Get the image cache
852 if ( ! this->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
853 this->image_cache = mlt_cache_init();
854 if ( this->image_cache )
856 mlt_cache_item item = mlt_cache_get( this->image_cache, (void*) position );
857 *buffer = mlt_cache_item_data( item, (int*) format );
860 // Set the resolution
861 *width = codec_context->width;
862 *height = codec_context->height;
864 // Workaround 1088 encodings missing cropping info.
865 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
872 case mlt_image_yuv420p:
873 size = *width * 3 * ( *height + 1 ) / 2;
875 case mlt_image_rgb24:
876 size = *width * ( *height + 1 ) * 3;
878 case mlt_image_rgb24a:
879 case mlt_image_opengl:
880 size = *width * ( *height + 1 ) * 4;
883 *format = mlt_image_yuv422;
884 size = *width * ( *height + 1 ) * 2;
887 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
888 mlt_properties_set_data( frame_properties, "image", *buffer, size, NULL, NULL );
889 this->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
890 this->got_picture = 1;
903 // Special case pause handling flag
906 // Special case ffwd handling
909 // We may want to use the source fps if available
910 double source_fps = mlt_properties_get_double( properties, "source_fps" );
911 double fps = mlt_producer_get_fps( producer );
913 // This is the physical frame position in the source
914 int req_position = ( int )( position / fps * source_fps + 0.5 );
916 // Determines if we have to decode all frames in a sequence
917 // Temporary hack to improve intra frame only
918 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
919 strcmp( codec_context->codec->name, "dvvideo" ) &&
920 strcmp( codec_context->codec->name, "huffyuv" ) &&
921 strcmp( codec_context->codec->name, "mjpeg" ) &&
922 strcmp( codec_context->codec->name, "rawvideo" );
924 int last_position = this->last_position;
926 // Turn on usage of new seek API and PTS for seeking
927 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
928 if ( mlt_properties_get( properties, "new_seek" ) )
929 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
932 if ( position != this->video_expected || last_position < 0 )
934 if ( this->av_frame && position + 1 == this->video_expected )
936 // We're paused - use last image
939 else if ( !this->seekable && position > this->video_expected && ( position - this->video_expected ) < 250 )
941 // Fast forward - seeking is inefficient for small distances - just ignore following frames
942 ignore = ( int )( ( position - this->video_expected ) / fps * source_fps );
943 codec_context->skip_loop_filter = AVDISCARD_NONREF;
945 else if ( this->seekable && ( position < this->video_expected || position - this->video_expected >= 12 || last_position < 0 ) )
947 if ( use_new_seek && last_position == POSITION_INITIAL )
949 // find first key frame
953 while ( ret >= 0 && toscan-- > 0 )
955 ret = av_read_frame( context, &pkt );
956 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == this->video_index )
958 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) );
959 this->first_pts = pkt.pts;
962 av_free_packet( &pkt );
965 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
968 // Calculate the timestamp for the requested frame
972 timestamp = ( req_position - 0.1 / source_fps ) /
973 ( av_q2d( stream->time_base ) * source_fps );
974 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
975 if ( this->first_pts > 0 )
976 timestamp += this->first_pts;
977 else if ( context->start_time != AV_NOPTS_VALUE )
978 timestamp += context->start_time;
982 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
983 if ( context->start_time != AV_NOPTS_VALUE )
984 timestamp += context->start_time;
987 timestamp -= AV_TIME_BASE;
990 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
991 timestamp, position, this->video_expected, last_position );
993 // Seek to the timestamp
996 codec_context->skip_loop_filter = AVDISCARD_NONREF;
997 av_seek_frame( context, this->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1001 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1004 // Remove the cached info relating to the previous position
1005 this->current_position = POSITION_INVALID;
1006 this->last_position = POSITION_INVALID;
1007 av_freep( &this->av_frame );
1011 // flush any pictures still in decode buffer
1012 avcodec_flush_buffers( codec_context );
1017 // Duplicate the last image if necessary (see comment on rawvideo below)
1018 if ( this->av_frame && this->av_frame->linesize[0] && this->got_picture && this->seekable
1020 || this->current_position == req_position
1021 || ( !use_new_seek && this->current_position > req_position ) ) )
1024 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1026 // Workaround 1088 encodings missing cropping info.
1027 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1030 if ( this->vdpau && this->vdpau->buffer )
1033 picture.data[0] = this->vdpau->buffer;
1034 picture.data[2] = this->vdpau->buffer + codec_context->width * codec_context->height;
1035 picture.data[1] = this->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1036 picture.linesize[0] = codec_context->width;
1037 picture.linesize[1] = codec_context->width / 2;
1038 picture.linesize[2] = codec_context->width / 2;
1039 convert_image( (void**) &this->swscale, (AVFrame*) &picture, *buffer, PIX_FMT_YUV420P, format, *width, *height );
1043 convert_image( (void**) &this->swscale, this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1046 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1051 int int_position = 0;
1052 int decode_errors = 0;
1053 int got_picture = 0;
1055 av_init_packet( &pkt );
1057 // Construct an AVFrame for YUV422 conversion
1058 if ( !this->av_frame )
1059 this->av_frame = avcodec_alloc_frame( );
1061 while( ret >= 0 && !got_picture )
1064 ret = av_read_frame( context, &pkt );
1066 // We only deal with video from the selected video_index
1067 if ( ret >= 0 && pkt.stream_index == this->video_index && pkt.size > 0 )
1069 // Determine time code of the packet
1072 int64_t pts = pkt.pts;
1073 if ( this->first_pts > 0 )
1074 pts -= this->first_pts;
1075 else if ( context->start_time != AV_NOPTS_VALUE )
1076 pts -= context->start_time;
1077 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1078 if ( pkt.pts == AV_NOPTS_VALUE )
1080 this->invalid_pts_counter++;
1081 if ( this->invalid_pts_counter > 20 )
1083 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1084 mlt_properties_set_int( properties, "new_seek", 0 );
1085 int_position = req_position;
1091 this->invalid_pts_counter = 0;
1093 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1094 pkt.pts, req_position, this->current_position, int_position );
1098 if ( pkt.dts != AV_NOPTS_VALUE )
1100 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1101 if ( context->start_time != AV_NOPTS_VALUE )
1102 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1103 last_position = this->last_position;
1104 if ( int_position == last_position )
1105 int_position = last_position + 1;
1109 int_position = req_position;
1111 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1112 pkt.dts, req_position, this->current_position, int_position );
1113 // Make a dumb assumption on streams that contain wild timestamps
1114 if ( abs( req_position - int_position ) > 999 )
1116 int_position = req_position;
1117 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1120 this->last_position = int_position;
1123 if ( must_decode || int_position >= req_position )
1126 if ( g_vdpau && this->vdpau )
1128 if ( g_vdpau->producer != this )
1130 vdpau_decoder_close();
1131 vdpau_decoder_init( this );
1134 this->vdpau->is_decoded = 0;
1137 codec_context->reordered_opaque = pkt.pts;
1138 if ( int_position >= req_position )
1139 codec_context->skip_loop_filter = AVDISCARD_NONE;
1140 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1141 ret = avcodec_decode_video2( codec_context, this->av_frame, &got_picture, &pkt );
1143 ret = avcodec_decode_video( codec_context, this->av_frame, &got_picture, pkt.data, pkt.size );
1145 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1148 if ( ++decode_errors <= 10 )
1161 // Determine time code of the packet
1162 int64_t pts = this->av_frame->reordered_opaque;
1163 if ( this->first_pts > 0 )
1164 pts -= this->first_pts;
1165 else if ( context->start_time != AV_NOPTS_VALUE )
1166 pts -= context->start_time;
1167 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1168 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, this->av_frame->key_frame );
1171 if ( int_position < req_position )
1176 else if ( int_position >= req_position )
1179 codec_context->skip_loop_filter = AVDISCARD_NONE;
1181 else if ( ignore -- )
1186 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1187 av_free_packet( &pkt );
1189 else if ( ret >= 0 )
1191 av_free_packet( &pkt );
1194 // Now handle the picture if we have one
1197 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1199 // Workaround 1088 encodings missing cropping info.
1200 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1205 if ( this->vdpau->is_decoded )
1207 struct vdpau_render_state *render = (struct vdpau_render_state*) this->av_frame->data[0];
1209 uint32_t pitches[3];
1210 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1213 if ( !this->vdpau->buffer )
1214 this->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1215 picture.data[0] = planes[0] = this->vdpau->buffer;
1216 picture.data[2] = planes[1] = this->vdpau->buffer + codec_context->width * codec_context->height;
1217 picture.data[1] = planes[2] = this->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1218 picture.linesize[0] = pitches[0] = codec_context->width;
1219 picture.linesize[1] = pitches[1] = codec_context->width / 2;
1220 picture.linesize[2] = pitches[2] = codec_context->width / 2;
1222 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1223 if ( status == VDP_STATUS_OK )
1225 convert_image( (void**) &this->swscale, (AVFrame*) &picture, *buffer, PIX_FMT_YUV420P, format, *width, *height );
1229 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1230 this->vdpau->is_decoded = 0;
1235 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1241 convert_image( (void**) &this->swscale, this->av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
1242 this->top_field_first |= this->av_frame->top_field_first;
1243 this->current_position = int_position;
1244 this->got_picture = 1;
1256 if ( this->got_picture && image_size > 0 && this->image_cache )
1258 // Copy buffer to image cache
1259 uint8_t *image = mlt_pool_alloc( image_size );
1260 memcpy( image, *buffer, image_size );
1261 mlt_cache_put( this->image_cache, (void*) position, image, *format, mlt_pool_release );
1264 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1265 this->video_expected = position + 1;
1268 // Set the progressive flag
1269 if ( mlt_properties_get( properties, "force_progressive" ) )
1270 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1271 else if ( this->av_frame )
1272 mlt_properties_set_int( frame_properties, "progressive", !this->av_frame->interlaced_frame );
1274 // Set the field order property for this frame
1275 mlt_properties_set_int( frame_properties, "top_field_first", this->top_field_first );
1277 return !this->got_picture;
1280 /** Process properties as AVOptions and apply to AV context obj
1283 static void apply_properties( void *obj, mlt_properties properties, int flags )
1286 int count = mlt_properties_count( properties );
1287 for ( i = 0; i < count; i++ )
1289 const char *opt_name = mlt_properties_get_name( properties, i );
1290 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1291 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1294 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1295 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1296 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1297 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1299 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1305 /** Initialize the video codec context.
1308 static int video_codec_init( producer_avformat this, int index, mlt_properties properties )
1310 // Initialise the codec if necessary
1311 if ( !this->video_codec )
1313 // Get the video stream
1314 AVStream *stream = this->video_format->streams[ index ];
1316 // Get codec context
1317 AVCodecContext *codec_context = stream->codec;
1320 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1322 if ( codec_context->codec_id == CODEC_ID_H264 )
1324 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1326 if ( vdpau_init( this ) )
1328 this->video_codec = codec_context;
1329 if ( !vdpau_decoder_init( this ) )
1330 vdpau_decoder_close();
1334 codec = avcodec_find_decoder( codec_context->codec_id );
1338 // Initialise multi-threading
1339 int thread_count = mlt_properties_get_int( properties, "threads" );
1340 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1341 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1342 if ( thread_count > 1 )
1344 avcodec_thread_init( codec_context, thread_count );
1345 codec_context->thread_count = thread_count;
1348 // If we don't have a codec and we can't initialise it, we can't do much more...
1350 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1352 // Now store the codec with its destructor
1353 this->video_codec = codec_context;
1357 // Remember that we can't use this later
1358 this->video_index = -1;
1362 // Process properties as AVOptions
1363 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1365 // Reset some image properties
1366 mlt_properties_set_int( properties, "width", this->video_codec->width );
1367 mlt_properties_set_int( properties, "height", this->video_codec->height );
1368 // For DV, we'll just use the saved aspect ratio
1369 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1370 mlt_properties_set_double( properties, "aspect_ratio", get_aspect_ratio( stream, this->video_codec, NULL ) );
1372 // Determine the fps first from the codec
1373 double source_fps = (double) this->video_codec->time_base.den /
1374 ( this->video_codec->time_base.num == 0 ? 1 : this->video_codec->time_base.num );
1376 if ( mlt_properties_get( properties, "force_fps" ) )
1378 source_fps = mlt_properties_get_double( properties, "force_fps" );
1379 stream->time_base = av_d2q( source_fps, 255 );
1383 // If the muxer reports a frame rate different than the codec
1384 double muxer_fps = av_q2d( stream->r_frame_rate );
1385 // Choose the lesser - the wrong tends to be off by some multiple of 10
1386 source_fps = FFMIN( source_fps, muxer_fps );
1389 // We'll use fps if it's available
1390 if ( source_fps > 0 )
1391 mlt_properties_set_double( properties, "source_fps", source_fps );
1393 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( this->parent ) );
1395 return this->video_codec && this->video_index > -1;
1398 /** Set up video handling.
1401 static void producer_set_up_video( producer_avformat this, mlt_frame frame )
1404 mlt_producer producer = this->parent;
1406 // Get the properties
1407 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1409 // Fetch the video format context
1410 AVFormatContext *context = this->video_format;
1412 // Get the video_index
1413 int index = mlt_properties_get_int( properties, "video_index" );
1415 // Reopen the file if necessary
1416 if ( !context && index > -1 )
1418 mlt_events_block( properties, producer );
1419 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1420 mlt_properties_get( properties, "resource" ) );
1421 context = this->video_format;
1422 if ( this->dummy_context )
1425 av_close_input_file( this->dummy_context );
1428 this->dummy_context = NULL;
1429 mlt_events_unblock( properties, producer );
1430 if ( this->audio_format )
1431 get_audio_streams_info( this );
1433 // Process properties as AVOptions
1434 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1437 // Exception handling for video_index
1438 if ( context && index >= (int) context->nb_streams )
1440 // Get the last video stream
1441 for ( index = context->nb_streams - 1;
1442 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1444 mlt_properties_set_int( properties, "video_index", index );
1446 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1448 // Invalidate the video stream
1450 mlt_properties_set_int( properties, "video_index", index );
1453 // Update the video properties if the index changed
1454 if ( index != this->video_index )
1456 // Reset the video properties if the index changed
1457 this->video_index = index;
1458 if ( this->video_codec )
1461 avcodec_close( this->video_codec );
1464 this->video_codec = NULL;
1467 // Get the frame properties
1468 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1471 if ( context && index > -1 && video_codec_init( this, index, properties ) )
1473 // Set the frame properties
1474 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1475 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1476 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1478 // Set the width and height
1479 mlt_properties_set_int( frame_properties, "width", this->video_codec->width );
1480 mlt_properties_set_int( frame_properties, "height", this->video_codec->height );
1481 mlt_properties_set_int( frame_properties, "real_width", this->video_codec->width );
1482 mlt_properties_set_int( frame_properties, "real_height", this->video_codec->height );
1483 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1485 // Workaround 1088 encodings missing cropping info.
1486 if ( this->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1487 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1489 // Add our image operation
1490 mlt_frame_push_service( frame, this );
1491 mlt_frame_push_get_image( frame, producer_get_image );
1495 // If something failed, use test card image
1496 mlt_properties_set_int( frame_properties, "test_image", 1 );
1500 static int seek_audio( producer_avformat this, mlt_position position, double timecode, int *ignore )
1504 // Seek if necessary
1505 if ( position != this->audio_expected )
1507 if ( position + 1 == this->audio_expected )
1509 // We're paused - silence required
1512 else if ( !this->seekable && position > this->audio_expected && ( position - this->audio_expected ) < 250 )
1514 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1515 *ignore = position - this->audio_expected;
1517 else if ( position < this->audio_expected || position - this->audio_expected >= 12 )
1519 AVFormatContext *context = this->audio_format;
1520 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1521 if ( context->start_time != AV_NOPTS_VALUE )
1522 timestamp += context->start_time;
1523 if ( timestamp < 0 )
1526 // Set to the real timecode
1527 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1530 // Clear the usage in the audio buffer
1531 int i = MAX_AUDIO_STREAMS + 1;
1533 this->audio_used[i - 1] = 0;
1539 static int decode_audio( producer_avformat this, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1541 // Fetch the audio_format
1542 AVFormatContext *context = this->audio_format;
1544 // Get the current stream index
1545 int index = pkt.stream_index;
1547 // Get codec context
1548 AVCodecContext *codec_context = this->audio_codec[ index ];
1550 // Obtain the resample context if it exists (not always needed)
1551 ReSampleContext *resample = this->audio_resample[ index ];
1553 // Obtain the audio buffers
1554 int16_t *audio_buffer = this->audio_buffer[ index ];
1555 int16_t *decode_buffer = this->decode_buffer[ index ];
1557 int audio_used = this->audio_used[ index ];
1558 uint8_t *ptr = pkt.data;
1562 while ( ptr && ret >= 0 && len > 0 )
1564 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1567 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1568 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, &pkt );
1569 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1570 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1572 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1576 mlt_log_warning( MLT_PRODUCER_SERVICE(this->parent), "audio decoding error %d\n", ret );
1580 pkt.size = len -= ret;
1581 pkt.data = ptr += ret;
1583 // If decoded successfully
1584 if ( data_size > 0 )
1586 // Figure out how many samples will be needed after resampling
1587 int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1588 int samples_needed = this->resample_factor * convert_samples + 1;
1590 // Resize audio buffer to prevent overflow
1591 if ( audio_used * channels + samples_needed > this->audio_buffer_size[ index ] )
1593 this->audio_buffer_size[ index ] *= 2;
1594 audio_buffer = this->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, this->audio_buffer_size[ index ] * sizeof(int16_t) );
1598 // Copy to audio buffer while resampling
1599 int16_t *source = decode_buffer;
1600 int16_t *dest = &audio_buffer[ audio_used * channels ];
1601 audio_used += audio_resample( resample, dest, source, convert_samples );
1605 // Straight copy to audio buffer
1606 memcpy( &audio_buffer[ audio_used * codec_context->channels ], decode_buffer, data_size );
1607 audio_used += convert_samples;
1611 while ( *ignore && audio_used > samples )
1614 audio_used -= samples;
1615 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) ],
1616 audio_used * sizeof( int16_t ) );
1621 // If we're behind, ignore this packet
1624 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
1625 int req_position = ( int )( timecode * fps + 0.5 );
1626 int int_position = ( int )( current_pts * fps + 0.5 );
1627 if ( context->start_time != AV_NOPTS_VALUE )
1628 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1630 if ( this->seekable && *ignore == 0 )
1632 if ( int_position < req_position )
1633 // We are behind, so skip some
1635 else if ( int_position > req_position + 2 )
1636 // We are ahead, so seek backwards some more
1637 seek_audio( this, req_position, timecode - 1.0, ignore );
1641 this->audio_used[ index ] = audio_used;
1646 /** Get the audio from a frame.
1649 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1652 producer_avformat this = mlt_frame_pop_audio( frame );
1654 // Obtain the frame number of this frame
1655 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1657 // Calculate the real time code
1658 double real_timecode = producer_time_of_frame( this->parent, position );
1660 // Get the producer fps
1661 double fps = mlt_producer_get_fps( this->parent );
1663 // Number of frames to ignore (for ffwd)
1666 // Flag for paused (silence)
1667 int paused = seek_audio( this, position, real_timecode, &ignore );
1669 // Fetch the audio_format
1670 AVFormatContext *context = this->audio_format;
1672 // Determine the tracks to use
1673 int index = this->audio_index;
1674 int index_max = this->audio_index + 1;
1675 if ( this->audio_index == INT_MAX )
1678 index_max = context->nb_streams;
1679 *channels = this->total_channels;
1680 *frequency = this->max_frequency;
1683 // Initialize the resamplers and buffers
1684 for ( ; index < index_max; index++ )
1686 // Get codec context
1687 AVCodecContext *codec_context = this->audio_codec[ index ];
1689 if ( codec_context && !this->audio_buffer[ index ] )
1691 // Check for resample and create if necessary
1692 if ( codec_context->channels <= 2 )
1694 // Determine by how much resampling will increase number of samples
1695 double resample_factor = this->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
1696 resample_factor *= (double) *frequency / codec_context->sample_rate;
1697 if ( resample_factor > this->resample_factor )
1698 this->resample_factor = resample_factor;
1700 // Create the resampler
1701 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1702 this->audio_resample[ index ] = av_audio_resample_init(
1703 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1704 codec_context->channels, *frequency, codec_context->sample_rate,
1705 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1707 this->audio_resample[ index ] = audio_resample_init(
1708 this->audio_index == INT_MAX ? codec_context->channels : *channels,
1709 codec_context->channels, *frequency, codec_context->sample_rate );
1714 codec_context->request_channels = this->audio_index == INT_MAX ? codec_context->channels : *channels;
1717 // Check for audio buffer and create if necessary
1718 this->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1719 this->audio_buffer[ index ] = mlt_pool_alloc( this->audio_buffer_size[ index ] * sizeof( int16_t ) );
1721 // Check for decoder buffer and create if necessary
1722 this->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1726 // Get the audio if required
1733 av_init_packet( &pkt );
1735 // If not resampling, give consumer more than requested.
1736 // It requested number samples based on requested frame rate.
1737 // Do not clean this up with a samples *= ...!
1738 if ( this->audio_index != INT_MAX && ! this->audio_resample[ this->audio_index ] )
1739 *samples = *samples * this->audio_codec[ this->audio_index ]->sample_rate / *frequency;
1741 while ( ret >= 0 && !got_audio )
1743 // Check if the buffer already contains the samples required
1744 if ( this->audio_index != INT_MAX && this->audio_used[ this->audio_index ] >= *samples && ignore == 0 )
1751 ret = av_read_frame( context, &pkt );
1753 // We only deal with audio from the selected audio index
1754 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == this->audio_index ||
1755 ( this->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
1757 int channels2 = this->audio_index == INT_MAX ? this->audio_codec[pkt.stream_index]->channels : *channels;
1758 ret = decode_audio( this, &ignore, pkt, channels2, *samples, real_timecode, fps );
1760 av_free_packet( &pkt );
1762 if ( this->audio_index == INT_MAX && ret >= 0 )
1764 // Determine if there is enough audio for all streams
1766 for ( index = 0; index < context->nb_streams; index++ )
1768 if ( this->audio_codec[ index ] && this->audio_used[ index ] < *samples )
1774 // Allocate and set the frame's audio buffer
1775 int size = *samples * *channels * sizeof(int16_t);
1776 *buffer = mlt_pool_alloc( size );
1777 *format = mlt_audio_s16;
1778 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
1780 // Interleave tracks if audio_index=all
1781 if ( this->audio_index == INT_MAX )
1783 int16_t *dest = *buffer;
1785 for ( i = 0; i < *samples; i++ )
1787 for ( index = 0; index < index_max; index++ )
1788 if ( this->audio_codec[ index ] )
1790 int current_channels = this->audio_codec[ index ]->channels;
1791 int16_t *src = this->audio_buffer[ index ] + i * current_channels;
1792 memcpy( dest, src, current_channels * sizeof(int16_t) );
1793 dest += current_channels;
1796 for ( index = 0; index < index_max; index++ )
1797 if ( this->audio_codec[ index ] && this->audio_used[ index ] >= *samples )
1799 int current_channels = this->audio_codec[ index ]->channels;
1800 int16_t *src = this->audio_buffer[ index ] + *samples * current_channels;
1801 this->audio_used[index] -= *samples;
1802 memmove( this->audio_buffer[ index ], src, this->audio_used[ index ] * current_channels * sizeof(int16_t) );
1805 // Copy a single track to the output buffer
1808 index = this->audio_index;
1810 // Now handle the audio if we have enough
1811 if ( this->audio_used[ index ] >= *samples )
1813 int16_t *src = this->audio_buffer[ index ];
1814 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
1815 this->audio_used[ index ] -= *samples;
1816 memmove( src, &src[ *samples * *channels ], this->audio_used[ index ] * *channels * sizeof(int16_t) );
1820 // Otherwise fill with silence
1821 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
1823 if ( !this->audio_resample[ index ] )
1825 // TODO: uncomment and remove following line when full multi-channel support is ready
1826 // *channels = codec_context->channels;
1827 *frequency = this->audio_codec[ index ]->sample_rate;
1833 // Get silence and don't touch the context
1834 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1837 // Regardless of speed (other than paused), we expect to get the next frame
1839 this->audio_expected = position + 1;
1844 /** Initialize the audio codec context.
1847 static int audio_codec_init( producer_avformat this, int index, mlt_properties properties )
1849 // Initialise the codec if necessary
1850 if ( !this->audio_codec[ index ] )
1852 // Get codec context
1853 AVCodecContext *codec_context = this->audio_format->streams[index]->codec;
1856 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1858 // If we don't have a codec and we can't initialise it, we can't do much more...
1860 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1862 // Now store the codec with its destructor
1863 if ( this->audio_codec[ index ] )
1864 avcodec_close( this->audio_codec[ index ] );
1865 this->audio_codec[ index ] = codec_context;
1869 // Remember that we can't use this later
1870 this->audio_index = -1;
1874 // Process properties as AVOptions
1875 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1877 return this->audio_codec[ index ] && this->audio_index > -1;
1880 /** Set up audio handling.
1883 static void producer_set_up_audio( producer_avformat this, mlt_frame frame )
1886 mlt_producer producer = this->parent;
1888 // Get the properties
1889 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1891 // Fetch the audio format context
1892 AVFormatContext *context = this->audio_format;
1894 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1896 // Get the audio_index
1897 int index = mlt_properties_get_int( properties, "audio_index" );
1899 // Handle all audio tracks
1900 if ( this->audio_index > -1 &&
1901 mlt_properties_get( properties, "audio_index" ) &&
1902 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
1905 // Reopen the file if necessary
1906 if ( !context && this->audio_index > -1 && index > -1 )
1908 mlt_events_block( properties, producer );
1909 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1910 mlt_properties_get( properties, "resource" ) );
1911 context = this->audio_format;
1912 if ( this->dummy_context )
1915 av_close_input_file( this->dummy_context );
1918 this->dummy_context = NULL;
1919 mlt_events_unblock( properties, producer );
1920 get_audio_streams_info( this );
1923 // Exception handling for audio_index
1924 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
1926 for ( index = context->nb_streams - 1;
1927 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
1929 mlt_properties_set_int( properties, "audio_index", index );
1931 if ( context && index > -1 && index < INT_MAX &&
1932 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1934 index = this->audio_index;
1935 mlt_properties_set_int( properties, "audio_index", index );
1938 // Update the audio properties if the index changed
1939 if ( context && index > -1 && index != this->audio_index )
1941 if ( this->audio_codec[ this->audio_index ] )
1944 avcodec_close( this->audio_codec[ this->audio_index ] );
1947 this->audio_codec[ this->audio_index ] = NULL;
1949 if ( this->audio_index != -1 )
1950 this->audio_index = index;
1955 if ( context && index == INT_MAX )
1957 mlt_properties_set_int( frame_properties, "frequency", this->max_frequency );
1958 mlt_properties_set_int( frame_properties, "channels", this->total_channels );
1959 for ( index = 0; index < context->nb_streams; index++ )
1961 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
1962 audio_codec_init( this, index, properties );
1965 else if ( context && index > -1 && audio_codec_init( this, index, properties ) )
1967 // Set the frame properties
1968 if ( index < INT_MAX )
1970 mlt_properties_set_int( frame_properties, "frequency", this->audio_codec[ index ]->sample_rate );
1971 mlt_properties_set_int( frame_properties, "channels", this->audio_codec[ index ]->channels );
1974 if ( context && index > -1 )
1976 // Add our audio operation
1977 mlt_frame_push_audio( frame, this );
1978 mlt_frame_push_audio( frame, producer_get_audio );
1982 /** Our get frame implementation.
1985 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
1987 // Access the private data
1988 mlt_service service = MLT_PRODUCER_SERVICE( producer );
1989 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
1990 producer_avformat this = mlt_cache_item_data( cache_item, NULL );
1995 this = calloc( 1, sizeof( struct producer_avformat_s ) );
1996 producer->child = this;
1997 this->parent = producer;
1998 mlt_service_cache_put( service, "producer_avformat", this, 0, (mlt_destructor) producer_avformat_close );
1999 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2002 // Create an empty frame
2003 *frame = mlt_frame_init( service);
2007 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2011 mlt_cache_item_close( cache_item );
2015 // Update timecode on the frame we're creating
2016 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2018 // Set the position of this producer
2019 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2022 producer_set_up_video( this, *frame );
2025 producer_set_up_audio( this, *frame );
2027 // Calculate the next timecode
2028 mlt_producer_prepare_next( producer );
2033 static void producer_avformat_close( producer_avformat this )
2035 mlt_log_debug( NULL, "producer_avformat_close\n" );
2037 av_free( this->av_frame );
2040 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2042 if ( this->audio_resample[i] )
2043 audio_resample_close( this->audio_resample[i] );
2044 mlt_pool_release( this->audio_buffer[i] );
2045 av_free( this->decode_buffer[i] );
2046 if ( this->audio_codec[i] )
2047 avcodec_close( this->audio_codec[i] );
2049 if ( this->video_codec )
2050 avcodec_close( this->video_codec );
2051 if ( this->dummy_context )
2052 av_close_input_file( this->dummy_context );
2053 if ( this->audio_format )
2054 av_close_input_file( this->audio_format );
2055 if ( this->video_format )
2056 av_close_input_file( this->video_format );
2059 vdpau_producer_close( this );
2062 sws_freeContext( this->swscale );
2064 if ( this->image_cache )
2065 mlt_cache_close( this->image_cache );
2069 static void producer_close( mlt_producer parent )
2072 parent->close = NULL;
2073 mlt_producer_close( parent );