2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include <framework/mlt_producer.h>
24 #include <framework/mlt_frame.h>
25 #include <framework/mlt_profile.h>
26 #include <framework/mlt_log.h>
28 // ffmpeg Header files
34 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
35 # include "audioconvert.h"
38 // System header files
43 #if LIBAVUTIL_VERSION_INT < (50<<16)
44 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
45 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
48 void avformat_lock( );
49 void avformat_unlock( );
51 // Forward references.
52 static int producer_open( mlt_producer this, mlt_profile profile, char *file );
53 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
55 /** Constructor for libavformat.
58 mlt_producer producer_avformat_init( mlt_profile profile, char *file )
62 // Report information about available demuxers and codecs as YAML Tiny
63 if ( file && strstr( file, "f-list" ) )
65 fprintf( stderr, "---\nformats:\n" );
66 AVInputFormat *format = NULL;
67 while ( ( format = av_iformat_next( format ) ) )
68 fprintf( stderr, " - %s\n", format->name );
69 fprintf( stderr, "...\n" );
72 if ( file && strstr( file, "acodec-list" ) )
74 fprintf( stderr, "---\naudio_codecs:\n" );
75 AVCodec *codec = NULL;
76 while ( ( codec = av_codec_next( codec ) ) )
77 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
78 fprintf( stderr, " - %s\n", codec->name );
79 fprintf( stderr, "...\n" );
82 if ( file && strstr( file, "vcodec-list" ) )
84 fprintf( stderr, "---\nvideo_codecs:\n" );
85 AVCodec *codec = NULL;
86 while ( ( codec = av_codec_next( codec ) ) )
87 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
88 fprintf( stderr, " - %s\n", codec->name );
89 fprintf( stderr, "...\n" );
95 mlt_producer this = NULL;
97 // Check that we have a non-NULL argument
100 // Construct the producer
101 this = calloc( 1, sizeof( struct mlt_producer_s ) );
104 if ( mlt_producer_init( this, NULL ) == 0 )
106 // Get the properties
107 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
109 // Set the resource property (required for all producers)
110 mlt_properties_set( properties, "resource", file );
112 // Register our get_frame implementation
113 this->get_frame = producer_get_frame;
116 if ( producer_open( this, profile, file ) != 0 )
119 mlt_producer_close( this );
124 // Close the file to release resources for large playlists - reopen later as needed
125 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
126 mlt_properties_set_data( properties, "audio_context", NULL, 0, NULL, NULL );
127 mlt_properties_set_data( properties, "video_context", NULL, 0, NULL, NULL );
129 // Default the user-selectable indices from the auto-detected indices
130 mlt_properties_set_int( properties, "audio_index", mlt_properties_get_int( properties, "_audio_index" ) );
131 mlt_properties_set_int( properties, "video_index", mlt_properties_get_int( properties, "_video_index" ) );
139 /** Find the default streams.
142 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
147 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
149 // Allow for multiple audio and video streams in the file and select first of each (if available)
150 for( i = 0; i < context->nb_streams; i++ )
152 // Get the codec context
153 AVStream *stream = context->streams[ i ];
154 if ( ! stream ) continue;
155 AVCodecContext *codec_context = stream->codec;
156 if ( ! codec_context ) continue;
157 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
158 if ( ! codec ) continue;
160 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
162 // Determine the type and obtain the first index of each type
163 switch( codec_context->codec_type )
165 case CODEC_TYPE_VIDEO:
166 if ( *video_index < 0 )
168 mlt_properties_set( meta_media, key, "video" );
169 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
170 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
171 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
172 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
173 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
175 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
176 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
177 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
178 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
180 case CODEC_TYPE_AUDIO:
181 if ( *audio_index < 0 )
183 mlt_properties_set( meta_media, key, "audio" );
184 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
185 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
186 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
188 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
189 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
190 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
191 mlt_properties_set_int( meta_media, key, codec_context->channels );
196 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
197 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
198 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
199 mlt_properties_set( meta_media, key, codec->name );
200 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
201 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
202 mlt_properties_set( meta_media, key, codec->long_name );
204 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
205 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
206 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
207 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
208 snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
209 mlt_properties_set_int( meta_media, key, codec_context->profile );
210 snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
211 mlt_properties_set_int( meta_media, key, codec_context->level );
217 /** Producer file destructor.
220 static void producer_file_close( void *context )
222 if ( context != NULL )
224 // Lock the mutex now
228 av_close_input_file( context );
230 // Unlock the mutex now
235 /** Producer file destructor.
238 static void producer_codec_close( void *codec )
242 // Lock the mutex now
246 avcodec_close( codec );
248 // Unlock the mutex now
253 static inline int dv_is_pal( AVPacket *pkt )
255 return pkt->data[3] & 0x80;
258 static int dv_is_wide( AVPacket *pkt )
260 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
262 for ( ; i < pkt->size; i += 5 /* packet size */ )
264 if ( pkt->data[ i ] == 0x61 )
266 uint8_t x = pkt->data[ i + 2 ] & 0x7;
267 return ( x == 2 ) || ( x == 7 );
273 static double get_aspect_ratio( AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
275 double aspect_ratio = 1.0;
277 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
281 if ( dv_is_pal( pkt ) )
283 aspect_ratio = dv_is_wide( pkt )
284 ? 64.0/45.0 // 16:9 PAL
285 : 16.0/15.0; // 4:3 PAL
289 aspect_ratio = dv_is_wide( pkt )
290 ? 32.0/27.0 // 16:9 NTSC
291 : 8.0/9.0; // 4:3 NTSC
297 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
298 stream->sample_aspect_ratio;
300 codec_context->sample_aspect_ratio;
302 // Override FFmpeg's notion of DV aspect ratios, which are
303 // based upon a width of 704. Since we do not have a normaliser
304 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
305 // we just coerce the values to facilitate a passive behaviour through
306 // the rescale normaliser when using equivalent producers and consumers.
307 // = display_aspect / (width * height)
308 if ( ar.num == 10 && ar.den == 11 )
309 aspect_ratio = 8.0/9.0; // 4:3 NTSC
310 else if ( ar.num == 59 && ar.den == 54 )
311 aspect_ratio = 16.0/15.0; // 4:3 PAL
312 else if ( ar.num == 40 && ar.den == 33 )
313 aspect_ratio = 32.0/27.0; // 16:9 NTSC
314 else if ( ar.num == 118 && ar.den == 81 )
315 aspect_ratio = 64.0/45.0; // 16:9 PAL
320 AVRational codec_sar = codec_context->sample_aspect_ratio;
321 AVRational stream_sar =
322 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
323 stream->sample_aspect_ratio;
327 if ( codec_sar.num > 0 )
328 aspect_ratio = av_q2d( codec_sar );
329 else if ( stream_sar.num > 0 )
330 aspect_ratio = av_q2d( stream_sar );
338 static int producer_open( mlt_producer this, mlt_profile profile, char *file )
340 // Return an error code (0 == no error)
343 // Context for avformat
344 AVFormatContext *context = NULL;
346 // Get the properties
347 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
349 // We will treat everything with the producer fps
350 double fps = mlt_profile_fps( profile );
352 // Lock the mutex now
355 // If "MRL", then create AVInputFormat
356 AVInputFormat *format = NULL;
357 AVFormatParameters *params = NULL;
358 char *standard = NULL;
359 char *mrl = strchr( file, ':' );
361 // AV option (0 = both, 1 = video, 2 = audio)
364 // Only if there is not a protocol specification that avformat can handle
365 if ( mrl && !url_exist( file ) )
367 // 'file' becomes format abbreviation
371 format = av_find_input_format( file );
373 // Eat the format designator
379 params = calloc( sizeof( AVFormatParameters ), 1 );
381 // These are required by video4linux (defaults)
383 params->height = 480;
384 params->time_base= (AVRational){1,25};
385 // params->device = file;
386 params->channels = 2;
387 params->sample_rate = 48000;
390 // XXX: this does not work anymore since avdevice
391 // TODO: make producer_avddevice?
393 mrl = strchr( file, '?' );
397 char *name = strdup( ++mrl );
398 char *value = strchr( name, ':' );
403 char *t = strchr( value, '&' );
406 if ( !strcmp( name, "frame_rate" ) )
407 params->time_base.den = atoi( value );
408 else if ( !strcmp( name, "frame_rate_base" ) )
409 params->time_base.num = atoi( value );
410 else if ( !strcmp( name, "sample_rate" ) )
411 params->sample_rate = atoi( value );
412 else if ( !strcmp( name, "channels" ) )
413 params->channels = atoi( value );
414 else if ( !strcmp( name, "width" ) )
415 params->width = atoi( value );
416 else if ( !strcmp( name, "height" ) )
417 params->height = atoi( value );
418 else if ( !strcmp( name, "standard" ) )
420 standard = strdup( value );
421 params->standard = standard;
423 else if ( !strcmp( name, "av" ) )
427 mrl = strchr( mrl, '&' );
431 // Now attempt to open the file
432 error = av_open_input_file( &context, file, format, 0, params ) < 0;
434 // Cleanup AVFormatParameters
438 // If successful, then try to get additional info
441 // Get the stream info
442 error = av_find_stream_info( context ) < 0;
444 // Continue if no error
447 // We will default to the first audio and video streams found
448 int audio_index = -1;
449 int video_index = -1;
452 // Now set properties where we can (use default unknowns if required)
453 if ( context->duration != AV_NOPTS_VALUE )
455 // This isn't going to be accurate for all formats
456 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + 0.5 );
457 mlt_properties_set_position( properties, "out", frames - 1 );
458 mlt_properties_set_position( properties, "length", frames );
461 // Find default audio and video streams
462 find_default_streams( properties, context, &audio_index, &video_index );
464 if ( context->start_time != AV_NOPTS_VALUE )
465 mlt_properties_set_double( properties, "_start_time", context->start_time );
467 // Check if we're seekable (something funny about mpeg here :-/)
468 if ( strcmp( file, "pipe:" ) && strncmp( file, "http://", 6 ) && strncmp( file, "udp:", 4 ) && strncmp( file, "tcp:", 4 ) && strncmp( file, "rtsp:", 5 ) && strncmp( file, "rtp:", 4 ) )
470 mlt_properties_set_int( properties, "seekable", av_seek_frame( context, -1, mlt_properties_get_double( properties, "_start_time" ), AVSEEK_FLAG_BACKWARD ) >= 0 );
471 mlt_properties_set_data( properties, "dummy_context", context, 0, producer_file_close, NULL );
472 av_open_input_file( &context, file, NULL, 0, NULL );
473 av_find_stream_info( context );
478 // Store selected audio and video indexes on properties
479 mlt_properties_set_int( properties, "_audio_index", audio_index );
480 mlt_properties_set_int( properties, "_video_index", video_index );
481 mlt_properties_set_int( properties, "_last_position", -1 );
483 // Fetch the width, height and aspect ratio
484 if ( video_index != -1 )
486 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
487 mlt_properties_set_int( properties, "width", codec_context->width );
488 mlt_properties_set_int( properties, "height", codec_context->height );
490 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
492 // Fetch the first frame of DV so we can read it directly
497 ret = av_read_frame( context, &pkt );
498 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
500 mlt_properties_set_double( properties, "aspect_ratio",
501 get_aspect_ratio( context->streams[ video_index ], codec_context, &pkt ) );
508 mlt_properties_set_double( properties, "aspect_ratio",
509 get_aspect_ratio( context->streams[ video_index ], codec_context, NULL ) );
514 if (context->title != NULL)
515 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
516 if (context->author != NULL)
517 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
518 if (context->copyright != NULL)
519 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
520 if (context->comment != NULL)
521 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
522 if (context->album != NULL)
523 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
524 if (context->year != 0)
525 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
526 if (context->track != 0)
527 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
529 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
530 if ( av == 0 && audio_index != -1 && video_index != -1 )
532 // We'll use the open one as our video_context
533 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
535 // And open again for our audio context
536 av_open_input_file( &context, file, NULL, 0, NULL );
537 av_find_stream_info( context );
540 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
542 else if ( av != 2 && video_index != -1 )
544 // We only have a video context
545 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
547 else if ( audio_index != -1 )
549 // We only have an audio context
550 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
554 // Something has gone wrong
558 mlt_properties_set_int( properties, "av_bypass", av_bypass );
562 // Unlock the mutex now
568 /** Convert a frame position to a time code.
571 static double producer_time_of_frame( mlt_producer this, mlt_position position )
573 return ( double )position / mlt_producer_get_fps( this );
576 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format *format, int width, int height )
579 if ( pix_fmt == PIX_FMT_RGB32 )
581 *format = mlt_image_rgb24a;
582 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
583 width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
585 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
586 sws_scale( context, frame->data, frame->linesize, 0, height,
587 output.data, output.linesize);
588 sws_freeContext( context );
590 else if ( *format == mlt_image_yuv420p )
592 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
593 width, height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
595 output.data[0] = buffer;
596 output.data[1] = buffer + width * height;
597 output.data[2] = buffer + ( 3 * width * height ) / 2;
598 output.linesize[0] = width;
599 output.linesize[1] = width >> 1;
600 output.linesize[2] = width >> 1;
601 sws_scale( context, frame->data, frame->linesize, 0, height,
602 output.data, output.linesize);
603 sws_freeContext( context );
605 else if ( *format == mlt_image_rgb24 )
607 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
608 width, height, PIX_FMT_RGB24, SWS_FAST_BILINEAR, NULL, NULL, NULL);
610 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
611 sws_scale( context, frame->data, frame->linesize, 0, height,
612 output.data, output.linesize);
613 sws_freeContext( context );
615 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
617 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
618 width, height, PIX_FMT_RGBA, SWS_FAST_BILINEAR, NULL, NULL, NULL);
620 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
621 sws_scale( context, frame->data, frame->linesize, 0, height,
622 output.data, output.linesize);
623 sws_freeContext( context );
627 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
628 width, height, PIX_FMT_YUYV422, SWS_FAST_BILINEAR, NULL, NULL, NULL);
630 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
631 sws_scale( context, frame->data, frame->linesize, 0, height,
632 output.data, output.linesize);
633 sws_freeContext( context );
636 if ( *format == mlt_image_yuv420p )
639 pict.data[0] = buffer;
640 pict.data[1] = buffer + width * height;
641 pict.data[2] = buffer + ( 3 * width * height ) / 2;
642 pict.linesize[0] = width;
643 pict.linesize[1] = width >> 1;
644 pict.linesize[2] = width >> 1;
645 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
647 else if ( *format == mlt_image_rgb24 )
650 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
651 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
653 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
656 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
657 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
662 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
663 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
668 /** Allocate the image buffer and set it on the frame.
671 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
675 if ( codec_context->width == 0 || codec_context->height == 0 )
678 *width = codec_context->width;
679 *height = codec_context->height;
680 mlt_properties_set_int( frame_properties, "width", *width );
681 mlt_properties_set_int( frame_properties, "height", *height );
683 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
684 size = *width * ( *height + 1 ) * 4;
685 else switch ( *format )
687 case mlt_image_yuv420p:
688 size = *width * 3 * ( *height + 1 ) / 2;
690 case mlt_image_rgb24:
691 size = *width * ( *height + 1 ) * 3;
693 case mlt_image_rgb24a:
694 case mlt_image_opengl:
695 size = *width * ( *height + 1 ) * 4;
698 *format = mlt_image_yuv422;
699 size = *width * ( *height + 1 ) * 2;
703 // Construct the output image
704 *buffer = mlt_pool_alloc( size );
706 mlt_properties_set_data( frame_properties, "image", *buffer, size, (mlt_destructor)mlt_pool_release, NULL );
713 /** Get an image from a frame.
716 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
718 // Get the properties from the frame
719 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
721 // Obtain the frame number of this frame
722 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
725 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
727 // Get the producer properties
728 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
730 // Fetch the video_context
731 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
733 // Get the video_index
734 int index = mlt_properties_get_int( properties, "video_index" );
736 // Obtain the expected frame numer
737 mlt_position expected = mlt_properties_get_position( properties, "_video_expected" );
739 // Get the video stream
740 AVStream *stream = context->streams[ index ];
743 AVCodecContext *codec_context = stream->codec;
748 // Get the conversion frame
749 AVFrame *av_frame = mlt_properties_get_data( properties, "av_frame", NULL );
751 // Special case pause handling flag
754 // Special case ffwd handling
757 // We may want to use the source fps if available
758 double source_fps = mlt_properties_get_double( properties, "source_fps" );
759 double fps = mlt_producer_get_fps( this );
761 // This is the physical frame position in the source
762 int req_position = ( int )( position / fps * source_fps + 0.5 );
764 // Get the seekable status
765 int seekable = mlt_properties_get_int( properties, "seekable" );
767 // Hopefully provide better support for streams...
768 int av_bypass = mlt_properties_get_int( properties, "av_bypass" );
770 // Determines if we have to decode all frames in a sequence
773 // Temporary hack to improve intra frame only
774 must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
775 strcmp( codec_context->codec->name, "dvvideo" ) &&
776 strcmp( codec_context->codec->name, "huffyuv" ) &&
777 strcmp( codec_context->codec->name, "mjpeg" ) &&
778 strcmp( codec_context->codec->name, "rawvideo" );
780 int last_position = mlt_properties_get_int( properties, "_last_position" );
783 if ( position != expected || last_position == -1 )
785 if ( av_frame != NULL && position + 1 == expected )
787 // We're paused - use last image
790 else if ( !seekable && position > expected && ( position - expected ) < 250 )
792 // Fast forward - seeking is inefficient for small distances - just ignore following frames
793 ignore = ( int )( ( position - expected ) / fps * source_fps );
795 else if ( seekable && ( position < expected || position - expected >= 12 || last_position == -1 ) )
797 // Calculate the timestamp for the requested frame
798 int64_t timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
799 if ( ( uint64_t )context->start_time != AV_NOPTS_VALUE )
800 timestamp += context->start_time;
802 timestamp -= AV_TIME_BASE;
806 // Set to the timestamp
807 mlt_log_debug( MLT_PRODUCER_SERVICE( this ), "seeking timestamp %lld position %d expected %d last_pos %d\n",
808 timestamp, position, expected, last_position );
809 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
811 // Remove the cached info relating to the previous position
812 mlt_properties_set_int( properties, "_current_position", -1 );
813 mlt_properties_set_int( properties, "_last_position", -1 );
814 mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
819 // Duplicate the last image if necessary (see comment on rawvideo below)
820 int current_position = mlt_properties_get_int( properties, "_current_position" );
821 int got_picture = mlt_properties_get_int( properties, "_got_picture" );
822 if ( av_frame != NULL && got_picture && ( paused || current_position >= req_position ) && av_bypass == 0 )
825 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
826 convert_image( av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
828 mlt_frame_get_image( frame, buffer, format, width, height, writable );
833 int int_position = 0;
836 av_init_packet( &pkt );
838 // Construct an AVFrame for YUV422 conversion
839 if ( av_frame == NULL )
840 av_frame = avcodec_alloc_frame( );
842 while( ret >= 0 && !got_picture )
845 ret = av_read_frame( context, &pkt );
847 // We only deal with video from the selected video_index
848 if ( ret >= 0 && pkt.stream_index == index && pkt.size > 0 )
850 // Determine time code of the packet
851 if (pkt.dts != AV_NOPTS_VALUE)
853 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
854 if ( context->start_time != AV_NOPTS_VALUE )
855 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
856 last_position = mlt_properties_get_int( properties, "_last_position" );
857 if ( int_position == last_position )
858 int_position = last_position + 1;
862 int_position = req_position;
864 // Make a dumb assumption on streams that contain wild timestamps
865 if ( (unsigned) req_position - (unsigned) int_position > 999 )
866 int_position = req_position;
867 mlt_properties_set_int( properties, "_last_position", int_position );
870 if ( must_decode || int_position >= req_position )
871 ret = avcodec_decode_video( codec_context, av_frame, &got_picture, pkt.data, pkt.size );
876 if ( int_position < req_position )
881 else if ( int_position >= req_position )
885 else if ( ignore -- )
890 mlt_log_debug( MLT_PRODUCER_SERVICE(this), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d got_pic %d key %d\n",
891 pkt.dts, req_position, current_position, int_position, got_picture, pkt.flags & PKT_FLAG_KEY );
892 av_free_packet( &pkt );
896 av_free_packet( &pkt );
899 // Now handle the picture if we have one
902 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
904 convert_image( av_frame, *buffer, codec_context->pix_fmt, format, *width, *height );
905 if ( !mlt_properties_get( properties, "force_progressive" ) )
906 mlt_properties_set_int( frame_properties, "progressive", !av_frame->interlaced_frame );
907 mlt_properties_set_int( properties, "top_field_first", av_frame->top_field_first );
908 mlt_properties_set_int( properties, "_current_position", int_position );
909 mlt_properties_set_int( properties, "_got_picture", 1 );
910 mlt_properties_set_data( properties, "av_frame", av_frame, 0, av_free, NULL );
919 mlt_frame_get_image( frame, buffer, format, width, height, writable );
922 // Very untidy - for rawvideo, the packet contains the frame, hence the free packet
923 // above will break the pause behaviour - so we wipe the frame now
924 if ( !strcmp( codec_context->codec->name, "rawvideo" ) )
925 mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
927 // Set the field order property for this frame
928 mlt_properties_set_int( frame_properties, "top_field_first", mlt_properties_get_int( properties, "top_field_first" ) );
930 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
931 mlt_properties_set_position( properties, "_video_expected", position + 1 );
936 /** Process properties as AVOptions and apply to AV context obj
939 static void apply_properties( void *obj, mlt_properties properties, int flags )
942 int count = mlt_properties_count( properties );
943 for ( i = 0; i < count; i++ )
945 const char *opt_name = mlt_properties_get_name( properties, i );
946 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
948 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
949 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
950 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
951 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
953 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
958 /** Set up video handling.
961 static void producer_set_up_video( mlt_producer this, mlt_frame frame )
963 // Get the properties
964 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
966 // Fetch the video_context
967 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
969 // Get the video_index
970 int index = mlt_properties_get_int( properties, "video_index" );
972 // Reopen the file if necessary
973 if ( !context && index > -1 )
975 mlt_events_block( properties, this );
976 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(this) ),
977 mlt_properties_get( properties, "resource" ) );
978 context = mlt_properties_get_data( properties, "video_context", NULL );
979 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
980 mlt_events_unblock( properties, this );
982 // Process properties as AVOptions
983 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
986 // Exception handling for video_index
987 if ( context && index >= (int) context->nb_streams )
989 // Get the last video stream
990 for ( index = context->nb_streams - 1; index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO; --index );
991 mlt_properties_set_int( properties, "video_index", index );
993 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
995 // Invalidate the video stream
997 mlt_properties_set_int( properties, "video_index", index );
1000 // Get the frame properties
1001 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1003 if ( context && index > -1 )
1005 // Get the video stream
1006 AVStream *stream = context->streams[ index ];
1008 // Get codec context
1009 AVCodecContext *codec_context = stream->codec;
1012 AVCodec *codec = mlt_properties_get_data( properties, "video_codec", NULL );
1014 // Update the video properties if the index changed
1015 if ( index != mlt_properties_get_int( properties, "_video_index" ) )
1017 // Reset the video properties if the index changed
1018 mlt_properties_set_int( properties, "_video_index", index );
1019 mlt_properties_set_data( properties, "video_codec", NULL, 0, NULL, NULL );
1020 mlt_properties_set_int( properties, "width", codec_context->width );
1021 mlt_properties_set_int( properties, "height", codec_context->height );
1022 // TODO: get the first usable AVPacket and reset the stream position
1023 mlt_properties_set_double( properties, "aspect_ratio",
1024 get_aspect_ratio( context->streams[ index ], codec_context, NULL ) );
1028 // Initialise the codec if necessary
1029 if ( codec == NULL )
1031 // Initialise multi-threading
1032 int thread_count = mlt_properties_get_int( properties, "threads" );
1033 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1034 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1035 if ( thread_count > 1 )
1037 avcodec_thread_init( codec_context, thread_count );
1038 codec_context->thread_count = thread_count;
1042 codec = avcodec_find_decoder( codec_context->codec_id );
1044 // If we don't have a codec and we can't initialise it, we can't do much more...
1046 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
1048 // Now store the codec with its destructor
1049 mlt_properties_set_data( properties, "video_codec", codec_context, 0, producer_codec_close, NULL );
1053 // Remember that we can't use this later
1054 mlt_properties_set_int( properties, "video_index", -1 );
1059 // Process properties as AVOptions
1060 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1063 // No codec, no show...
1064 if ( codec && index > -1 )
1066 double source_fps = 0;
1067 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1068 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1069 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1071 // Determine the fps
1072 source_fps = ( double )codec_context->time_base.den / ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num );
1074 // We'll use fps if it's available
1075 if ( source_fps > 0 )
1076 mlt_properties_set_double( properties, "source_fps", source_fps );
1078 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( this ) );
1079 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
1081 // Set the width and height
1082 mlt_properties_set_int( frame_properties, "width", codec_context->width );
1083 mlt_properties_set_int( frame_properties, "height", codec_context->height );
1084 mlt_properties_set_int( frame_properties, "real_width", codec_context->width );
1085 mlt_properties_set_int( frame_properties, "real_height", codec_context->height );
1086 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1087 if ( mlt_properties_get( properties, "force_progressive" ) )
1088 mlt_properties_set_int( frame_properties, "progressive", mlt_properties_get_int( properties, "force_progressive" ) );
1090 mlt_frame_push_get_image( frame, producer_get_image );
1091 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
1095 mlt_properties_set_int( frame_properties, "test_image", 1 );
1100 mlt_properties_set_int( frame_properties, "test_image", 1 );
1104 /** Get the audio from a frame.
1107 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1109 // Get the properties from the frame
1110 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1112 // Obtain the frame number of this frame
1113 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1116 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
1118 // Get the producer properties
1119 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
1121 // Fetch the audio_context
1122 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
1124 // Get the audio_index
1125 int index = mlt_properties_get_int( properties, "audio_index" );
1127 // Get the seekable status
1128 int seekable = mlt_properties_get_int( properties, "seekable" );
1130 // Obtain the expected frame numer
1131 mlt_position expected = mlt_properties_get_position( properties, "_audio_expected" );
1133 // Obtain the resample context if it exists (not always needed)
1134 ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
1136 // Obtain the audio buffers
1137 int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
1138 int16_t *decode_buffer = mlt_properties_get_data( properties, "decode_buffer", NULL );
1140 // Get amount of audio used
1141 int audio_used = mlt_properties_get_int( properties, "_audio_used" );
1143 // Calculate the real time code
1144 double real_timecode = producer_time_of_frame( this, position );
1146 // Get the audio stream
1147 AVStream *stream = context->streams[ index ];
1149 // Get codec context
1150 AVCodecContext *codec_context = stream->codec;
1155 // Number of frames to ignore (for ffwd)
1158 // Flag for paused (silence)
1161 // Check for resample and create if necessary
1162 if ( resample == NULL && codec_context->channels <= 2 )
1164 // Create the resampler
1165 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1166 resample = av_audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate,
1167 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1169 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
1172 // And store it on properties
1173 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
1175 else if ( resample == NULL )
1177 // TODO: uncomment and remove following line when full multi-channel support is ready
1178 // *channels = codec_context->channels;
1179 codec_context->request_channels = *channels;
1181 *frequency = codec_context->sample_rate;
1184 // Check for audio buffer and create if necessary
1185 if ( audio_buffer == NULL )
1187 // Allocate the audio buffer
1188 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1190 // And store it on properties for reuse
1191 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
1194 // Check for decoder buffer and create if necessary
1195 if ( decode_buffer == NULL )
1197 // Allocate the audio buffer
1198 decode_buffer = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1200 // And store it on properties for reuse
1201 mlt_properties_set_data( properties, "decode_buffer", decode_buffer, 0, ( mlt_destructor )av_free, NULL );
1204 // Seek if necessary
1205 if ( position != expected )
1207 if ( position + 1 == expected )
1209 // We're paused - silence required
1212 else if ( !seekable && position > expected && ( position - expected ) < 250 )
1214 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1215 ignore = position - expected;
1217 else if ( position < expected || position - expected >= 12 )
1219 int64_t timestamp = ( int64_t )( real_timecode * AV_TIME_BASE + 0.5 );
1220 if ( context->start_time != AV_NOPTS_VALUE )
1221 timestamp += context->start_time;
1222 if ( timestamp < 0 )
1225 // Set to the real timecode
1226 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1229 // Clear the usage in the audio buffer
1234 // Get the audio if required
1240 av_init_packet( &pkt );
1242 while( ret >= 0 && !got_audio )
1244 // Check if the buffer already contains the samples required
1245 if ( audio_used >= *samples && ignore == 0 )
1252 ret = av_read_frame( context, &pkt );
1255 uint8_t *ptr = pkt.data;
1257 // We only deal with audio from the selected audio_index
1258 while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
1260 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1263 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1264 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1266 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1277 if ( data_size > 0 && ( audio_used * *channels + data_size < AVCODEC_MAX_AUDIO_FRAME_SIZE ) )
1281 int16_t *source = decode_buffer;
1282 int16_t *dest = &audio_buffer[ audio_used * *channels ];
1283 int convert_samples = data_size / av_get_bits_per_sample_format( codec_context->sample_fmt ) * 8 / codec_context->channels;
1285 audio_used += audio_resample( resample, dest, source, convert_samples );
1289 memcpy( &audio_buffer[ audio_used * *channels ], decode_buffer, data_size );
1290 audio_used += data_size / *channels / av_get_bits_per_sample_format( codec_context->sample_fmt ) * 8;
1294 while ( ignore && audio_used > *samples )
1297 audio_used -= *samples;
1298 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
1302 // If we're behind, ignore this packet
1305 double current_pts = av_q2d( stream->time_base ) * pkt.pts;
1306 double source_fps = mlt_properties_get_double( properties, "source_fps" );
1307 int req_position = ( int )( real_timecode * source_fps + 0.5 );
1308 int int_position = ( int )( current_pts * source_fps + 0.5 );
1310 if ( context->start_time != AV_NOPTS_VALUE )
1311 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1312 if ( seekable && !ignore && int_position < req_position )
1317 // We're finished with this packet regardless
1318 av_free_packet( &pkt );
1321 int size = *samples * *channels * sizeof( int16_t );
1322 *format = mlt_audio_s16;
1323 *buffer = mlt_pool_alloc( size );
1324 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
1326 // Now handle the audio if we have enough
1327 if ( audio_used >= *samples )
1329 memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
1330 audio_used -= *samples;
1331 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
1335 memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
1338 // Store the number of audio samples still available
1339 mlt_properties_set_int( properties, "_audio_used", audio_used );
1343 // Get silence and don't touch the context
1344 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1347 // Regardless of speed (other than paused), we expect to get the next frame
1349 mlt_properties_set_position( properties, "_audio_expected", position + 1 );
1354 /** Set up audio handling.
1357 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
1359 // Get the properties
1360 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
1362 // Fetch the audio_context
1363 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
1365 // Get the audio_index
1366 int index = mlt_properties_get_int( properties, "audio_index" );
1368 // Reopen the file if necessary
1369 if ( !context && index > -1 )
1371 mlt_events_block( properties, this );
1372 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(this) ),
1373 mlt_properties_get( properties, "resource" ) );
1374 context = mlt_properties_get_data( properties, "audio_context", NULL );
1375 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
1376 mlt_events_unblock( properties, this );
1379 // Exception handling for audio_index
1380 if ( context && index >= (int) context->nb_streams )
1382 for ( index = context->nb_streams - 1; index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO; --index );
1383 mlt_properties_set_int( properties, "audio_index", index );
1385 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1388 mlt_properties_set_int( properties, "audio_index", index );
1391 // Update the audio properties if the index changed
1392 if ( index > -1 && index != mlt_properties_get_int( properties, "_audio_index" ) )
1394 mlt_properties_set_int( properties, "_audio_index", index );
1395 mlt_properties_set_data( properties, "audio_codec", NULL, 0, NULL, NULL );
1398 // Deal with audio context
1399 if ( context != NULL && index > -1 )
1401 // Get the frame properties
1402 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1404 // Get the audio stream
1405 AVStream *stream = context->streams[ index ];
1407 // Get codec context
1408 AVCodecContext *codec_context = stream->codec;
1411 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
1413 // Initialise the codec if necessary
1414 if ( codec == NULL )
1417 codec = avcodec_find_decoder( codec_context->codec_id );
1419 // If we don't have a codec and we can't initialise it, we can't do much more...
1421 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
1423 // Now store the codec with its destructor
1424 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
1429 // Remember that we can't use this later
1430 mlt_properties_set_int( properties, "audio_index", -1 );
1435 // Process properties as AVOptions
1436 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1439 // No codec, no show...
1440 if ( codec && index > -1 )
1442 mlt_frame_push_audio( frame, producer_get_audio );
1443 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
1444 mlt_properties_set_int( frame_properties, "frequency", codec_context->sample_rate );
1445 mlt_properties_set_int( frame_properties, "channels", codec_context->channels );
1450 /** Our get frame implementation.
1453 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
1455 // Create an empty frame
1456 *frame = mlt_frame_init( MLT_PRODUCER_SERVICE( this ) );
1458 // Update timecode on the frame we're creating
1459 mlt_frame_set_position( *frame, mlt_producer_position( this ) );
1461 // Set the position of this producer
1462 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( this ) );
1465 producer_set_up_video( this, *frame );
1468 producer_set_up_audio( this, *frame );
1470 // Set the aspect_ratio
1471 mlt_properties_set_double( MLT_FRAME_PROPERTIES( *frame ), "aspect_ratio", mlt_properties_get_double( MLT_PRODUCER_PROPERTIES( this ), "aspect_ratio" ) );
1473 // Calculate the next timecode
1474 mlt_producer_prepare_next( this );