]> git.sesse.net Git - mlt/blob - src/modules/avformat/producer_avformat.c
Fix over- and under-linking.
[mlt] / src / modules / avformat / producer_avformat.c
1 /*
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
6  *
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.
11  *
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.
16  *
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
20  */
21
22 // MLT Header files
23 #include <framework/mlt_producer.h>
24 #include <framework/mlt_frame.h>
25 #include <framework/mlt_profile.h>
26
27 // ffmpeg Header files
28 #include <avformat.h>
29 #include <opt.h>
30 #ifdef SWSCALE
31 #  include <swscale.h>
32 #endif
33 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
34 #  include "audioconvert.h"
35 #endif
36
37 // System header files
38 #include <stdlib.h>
39 #include <string.h>
40 #include <pthread.h>
41
42 #if LIBAVUTIL_VERSION_INT < (50<<16)
43 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
44 #endif
45
46 void avformat_lock( );
47 void avformat_unlock( );
48
49 // Forward references.
50 static int producer_open( mlt_producer this, mlt_profile profile, char *file );
51 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
52
53 /** Constructor for libavformat.
54 */
55
56 mlt_producer producer_avformat_init( mlt_profile profile, char *file )
57 {
58         int error = 0;
59
60         // Report information about available demuxers and codecs as YAML Tiny
61         if ( file && strstr( file, "f-list" ) )
62         {
63                 fprintf( stderr, "---\nformats:\n" );
64                 AVInputFormat *format = NULL;
65                 while ( ( format = av_iformat_next( format ) ) )
66                         fprintf( stderr, "  - %s\n", format->name );
67                 fprintf( stderr, "...\n" );
68                 error = 1;
69         }
70         if ( file && strstr( file, "acodec-list" ) )
71         {
72                 fprintf( stderr, "---\naudio_codecs:\n" );
73                 AVCodec *codec = NULL;
74                 while ( ( codec = av_codec_next( codec ) ) )
75                         if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
76                                 fprintf( stderr, "  - %s\n", codec->name );
77                 fprintf( stderr, "...\n" );
78                 error = 1;
79         }
80         if ( file && strstr( file, "vcodec-list" ) )
81         {
82                 fprintf( stderr, "---\nvideo_codecs:\n" );
83                 AVCodec *codec = NULL;
84                 while ( ( codec = av_codec_next( codec ) ) )
85                         if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
86                                 fprintf( stderr, "  - %s\n", codec->name );
87                 fprintf( stderr, "...\n" );
88                 error = 1;
89         }
90         if ( error )
91                 return NULL;
92
93         mlt_producer this = NULL;
94
95         // Check that we have a non-NULL argument
96         if ( file != NULL )
97         {
98                 // Construct the producer
99                 this = calloc( 1, sizeof( struct mlt_producer_s ) );
100
101                 // Initialise it
102                 if ( mlt_producer_init( this, NULL ) == 0 )
103                 {
104                         // Get the properties
105                         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
106
107                         // Set the resource property (required for all producers)
108                         mlt_properties_set( properties, "resource", file );
109
110                         // Register our get_frame implementation
111                         this->get_frame = producer_get_frame;
112
113                         // Open the file
114                         if ( producer_open( this, profile, file ) != 0 )
115                         {
116                                 // Clean up
117                                 mlt_producer_close( this );
118                                 this = NULL;
119                         }
120                         else
121                         {
122                                 // Close the file to release resources for large playlists - reopen later as needed
123                                 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
124                                 mlt_properties_set_data( properties, "audio_context", NULL, 0, NULL, NULL );
125                                 mlt_properties_set_data( properties, "video_context", NULL, 0, NULL, NULL );
126
127                                 // Default the user-selectable indices from the auto-detected indices
128                                 mlt_properties_set_int( properties, "audio_index",  mlt_properties_get_int( properties, "_audio_index" ) );
129                                 mlt_properties_set_int( properties, "video_index",  mlt_properties_get_int( properties, "_video_index" ) );
130                         }
131                 }
132         }
133
134         return this;
135 }
136
137 /** Find the default streams.
138 */
139
140 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
141 {
142         int i;
143         char key[200];
144
145         mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
146
147         // Allow for multiple audio and video streams in the file and select first of each (if available)
148         for( i = 0; i < context->nb_streams; i++ )
149         {
150                 // Get the codec context
151                 AVStream *stream = context->streams[ i ];
152                 if ( ! stream ) continue;
153                 AVCodecContext *codec_context = stream->codec;
154                 if ( ! codec_context ) continue;
155                 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
156                 if ( ! codec ) continue;
157
158                 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
159
160                 // Determine the type and obtain the first index of each type
161                 switch( codec_context->codec_type )
162                 {
163                         case CODEC_TYPE_VIDEO:
164                                 if ( *video_index < 0 )
165                                         *video_index = i;
166                                 mlt_properties_set( meta_media, key, "video" );
167                                 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
168                                 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
169 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
170                                 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
171                                 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
172 #endif
173                                 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
174                                 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
175                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
176                                 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
177                                 break;
178                         case CODEC_TYPE_AUDIO:
179                                 if ( *audio_index < 0 )
180                                         *audio_index = i;
181                                 mlt_properties_set( meta_media, key, "audio" );
182 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
183                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
184                                 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
185 #endif
186                                 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
187                                 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
188                                 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
189                                 mlt_properties_set_int( meta_media, key, codec_context->channels );
190                                 break;
191                         default:
192                                 break;
193                 }
194 //              snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
195 //              mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
196                 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
197                 mlt_properties_set( meta_media, key, codec->name );
198 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
199                 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
200                 mlt_properties_set( meta_media, key, codec->long_name );
201 #endif
202                 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
203                 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
204 //              snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
205 //              mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
206                 snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
207                 mlt_properties_set_int( meta_media, key, codec_context->profile );
208                 snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
209                 mlt_properties_set_int( meta_media, key, codec_context->level );
210         }
211
212         return meta_media;
213 }
214
215 /** Producer file destructor.
216 */
217
218 static void producer_file_close( void *context )
219 {
220         if ( context != NULL )
221         {
222                 // Lock the mutex now
223                 avformat_lock( );
224
225                 // Close the file
226                 av_close_input_file( context );
227
228                 // Unlock the mutex now
229                 avformat_unlock( );
230         }
231 }
232
233 /** Producer file destructor.
234 */
235
236 static void producer_codec_close( void *codec )
237 {
238         if ( codec != NULL )
239         {
240                 // Lock the mutex now
241                 avformat_lock( );
242
243                 // Close the file
244                 avcodec_close( codec );
245
246                 // Unlock the mutex now
247                 avformat_unlock( );
248         }
249 }
250
251 static inline int dv_is_pal( AVPacket *pkt )
252 {
253         return pkt->data[3] & 0x80;
254 }
255
256 static int dv_is_wide( AVPacket *pkt )
257 {
258         int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
259
260         for ( ; i < pkt->size; i += 5 /* packet size */ )
261         {
262                 if ( pkt->data[ i ] == 0x61 )
263                 {
264                         uint8_t x = pkt->data[ i + 2 ] & 0x7;
265                         return ( x == 2 ) || ( x == 7 );
266                 }
267         }
268         return 0;
269 }
270
271 static double get_aspect_ratio( AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
272 {
273         double aspect_ratio = 1.0;
274
275         if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
276         {
277                 if ( pkt )
278                 {
279                         if ( dv_is_pal( pkt ) )
280                         {
281                                 aspect_ratio = dv_is_wide( pkt )
282                                         ? 64.0/45.0 // 16:9 PAL
283                                         : 16.0/15.0; // 4:3 PAL
284                         }
285                         else
286                         {
287                                 aspect_ratio = dv_is_wide( pkt )
288                                         ? 32.0/27.0 // 16:9 NTSC
289                                         : 8.0/9.0; // 4:3 NTSC
290                         }
291                 }
292                 else
293                 {
294                         AVRational ar =
295 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
296                                 stream->sample_aspect_ratio;
297 #else
298                                 codec_context->sample_aspect_ratio;
299 #endif
300                         // Override FFmpeg's notion of DV aspect ratios, which are
301                         // based upon a width of 704. Since we do not have a normaliser
302                         // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
303                         // we just coerce the values to facilitate a passive behaviour through
304                         // the rescale normaliser when using equivalent producers and consumers.
305                         // = display_aspect / (width * height)
306                         if ( ar.num == 10 && ar.den == 11 )
307                                 aspect_ratio = 8.0/9.0; // 4:3 NTSC
308                         else if ( ar.num == 59 && ar.den == 54 )
309                                 aspect_ratio = 16.0/15.0; // 4:3 PAL
310                         else if ( ar.num == 40 && ar.den == 33 )
311                                 aspect_ratio = 32.0/27.0; // 16:9 NTSC
312                         else if ( ar.num == 118 && ar.den == 81 )
313                                 aspect_ratio = 64.0/45.0; // 16:9 PAL
314                 }
315         }
316         else
317         {
318                 AVRational codec_sar = codec_context->sample_aspect_ratio;
319                 AVRational stream_sar =
320 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
321                         stream->sample_aspect_ratio;
322 #else
323                         { 0, 1 };
324 #endif
325                 if ( codec_sar.num > 0 )
326                         aspect_ratio = av_q2d( codec_sar );
327                 else if ( stream_sar.num > 0 )
328                         aspect_ratio = av_q2d( stream_sar );
329         }
330         return aspect_ratio;
331 }
332
333 /** Open the file.
334 */
335
336 static int producer_open( mlt_producer this, mlt_profile profile, char *file )
337 {
338         // Return an error code (0 == no error)
339         int error = 0;
340
341         // Context for avformat
342         AVFormatContext *context = NULL;
343
344         // Get the properties
345         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
346
347         // We will treat everything with the producer fps
348         double fps = mlt_profile_fps( profile );
349
350         // Lock the mutex now
351         avformat_lock( );
352
353         // If "MRL", then create AVInputFormat
354         AVInputFormat *format = NULL;
355         AVFormatParameters *params = NULL;
356         char *standard = NULL;
357         char *mrl = strchr( file, ':' );
358
359         // AV option (0 = both, 1 = video, 2 = audio)
360         int av = 0;
361
362         // Setting lowest log level
363         av_log_set_level( -1 );
364
365         // Only if there is not a protocol specification that avformat can handle
366         if ( mrl && !url_exist( file ) )
367         {
368                 // 'file' becomes format abbreviation
369                 mrl[0] = 0;
370
371                 // Lookup the format
372                 format = av_find_input_format( file );
373
374                 // Eat the format designator
375                 file = ++mrl;
376
377                 if ( format )
378                 {
379                         // Allocate params
380                         params = calloc( sizeof( AVFormatParameters ), 1 );
381
382                         // These are required by video4linux (defaults)
383                         params->width = 640;
384                         params->height = 480;
385                         params->time_base= (AVRational){1,25};
386                         // params->device = file;
387                         params->channels = 2;
388                         params->sample_rate = 48000;
389                 }
390
391                 // XXX: this does not work anymore since avdevice
392                 // TODO: make producer_avddevice?
393                 // Parse out params
394                 mrl = strchr( file, '?' );
395                 while ( mrl )
396                 {
397                         mrl[0] = 0;
398                         char *name = strdup( ++mrl );
399                         char *value = strchr( name, ':' );
400                         if ( value )
401                         {
402                                 value[0] = 0;
403                                 value++;
404                                 char *t = strchr( value, '&' );
405                                 if ( t )
406                                         t[0] = 0;
407                                 if ( !strcmp( name, "frame_rate" ) )
408                                         params->time_base.den = atoi( value );
409                                 else if ( !strcmp( name, "frame_rate_base" ) )
410                                         params->time_base.num = atoi( value );
411                                 else if ( !strcmp( name, "sample_rate" ) )
412                                         params->sample_rate = atoi( value );
413                                 else if ( !strcmp( name, "channels" ) )
414                                         params->channels = atoi( value );
415                                 else if ( !strcmp( name, "width" ) )
416                                         params->width = atoi( value );
417                                 else if ( !strcmp( name, "height" ) )
418                                         params->height = atoi( value );
419                                 else if ( !strcmp( name, "standard" ) )
420                                 {
421                                         standard = strdup( value );
422                                         params->standard = standard;
423                                 }
424                                 else if ( !strcmp( name, "av" ) )
425                                         av = atoi( value );
426                         }
427                         free( name );
428                         mrl = strchr( mrl, '&' );
429                 }
430         }
431
432         // Now attempt to open the file
433         error = av_open_input_file( &context, file, format, 0, params ) < 0;
434
435         // Cleanup AVFormatParameters
436         free( standard );
437         free( params );
438
439         // If successful, then try to get additional info
440         if ( error == 0 )
441         {
442                 // Get the stream info
443                 error = av_find_stream_info( context ) < 0;
444
445                 // Continue if no error
446                 if ( error == 0 )
447                 {
448                         // We will default to the first audio and video streams found
449                         int audio_index = -1;
450                         int video_index = -1;
451                         int av_bypass = 0;
452
453                         // Now set properties where we can (use default unknowns if required)
454                         if ( context->duration != AV_NOPTS_VALUE )
455                         {
456                                 // This isn't going to be accurate for all formats
457                                 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + 0.5 );
458                                 mlt_properties_set_position( properties, "out", frames - 1 );
459                                 mlt_properties_set_position( properties, "length", frames );
460                         }
461
462                         // Find default audio and video streams
463                         find_default_streams( properties, context, &audio_index, &video_index );
464
465                         if ( context->start_time != AV_NOPTS_VALUE )
466                                 mlt_properties_set_double( properties, "_start_time", context->start_time );
467
468                         // Check if we're seekable (something funny about mpeg here :-/)
469                         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                         {
471                                 mlt_properties_set_int( properties, "seekable", av_seek_frame( context, -1, mlt_properties_get_double( properties, "_start_time" ), AVSEEK_FLAG_BACKWARD ) >= 0 );
472                                 mlt_properties_set_data( properties, "dummy_context", context, 0, producer_file_close, NULL );
473                                 av_open_input_file( &context, file, NULL, 0, NULL );
474                                 av_find_stream_info( context );
475                         }
476                         else
477                                 av_bypass = 1;
478
479                         // Store selected audio and video indexes on properties
480                         mlt_properties_set_int( properties, "_audio_index", audio_index );
481                         mlt_properties_set_int( properties, "_video_index", video_index );
482                         mlt_properties_set_int( properties, "_last_position", -1 );
483
484                         // Fetch the width, height and aspect ratio
485                         if ( video_index != -1 )
486                         {
487                                 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
488                                 mlt_properties_set_int( properties, "width", codec_context->width );
489                                 mlt_properties_set_int( properties, "height", codec_context->height );
490
491                                 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
492                                 {
493                                         // Fetch the first frame of DV so we can read it directly
494                                         AVPacket pkt;
495                                         int ret = 0;
496                                         while ( ret >= 0 )
497                                         {
498                                                 ret = av_read_frame( context, &pkt );
499                                                 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
500                                                 {
501                                                         mlt_properties_set_double( properties, "aspect_ratio",
502                                                                 get_aspect_ratio( context->streams[ video_index ], codec_context, &pkt ) );
503                                                         break;
504                                                 }
505                                         }
506                                 }
507                                 else
508                                 {
509                                         mlt_properties_set_double( properties, "aspect_ratio",
510                                                 get_aspect_ratio( context->streams[ video_index ], codec_context, NULL ) );
511                                 }
512                         }
513
514                         // Read Metadata
515                         if (context->title != NULL)
516                                 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
517                         if (context->author != NULL)
518                                 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
519                         if (context->copyright != NULL)
520                                 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
521                         if (context->comment != NULL)
522                                 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
523                         if (context->album != NULL)
524                                 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
525                         if (context->year != 0)
526                                 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
527                         if (context->track != 0)
528                                 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
529
530                         // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
531                         if ( av == 0 && audio_index != -1 && video_index != -1 )
532                         {
533                                 // We'll use the open one as our video_context
534                                 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
535
536                                 // And open again for our audio context
537                                 av_open_input_file( &context, file, NULL, 0, NULL );
538                                 av_find_stream_info( context );
539
540                                 // Audio context
541                                 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
542                         }
543                         else if ( av != 2 && video_index != -1 )
544                         {
545                                 // We only have a video context
546                                 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
547                         }
548                         else if ( audio_index != -1 )
549                         {
550                                 // We only have an audio context
551                                 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
552                         }
553                         else
554                         {
555                                 // Something has gone wrong
556                                 error = -1;
557                         }
558
559                         mlt_properties_set_int( properties, "av_bypass", av_bypass );
560                 }
561         }
562
563         // Unlock the mutex now
564         avformat_unlock( );
565
566         return error;
567 }
568
569 /** Convert a frame position to a time code.
570 */
571
572 static double producer_time_of_frame( mlt_producer this, mlt_position position )
573 {
574         return ( double )position / mlt_producer_get_fps( this );
575 }
576
577 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format format, int width, int height )
578 {
579 #ifdef SWSCALE
580         if ( format == mlt_image_yuv420p )
581         {
582                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
583                         width, height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);
584                 AVPicture output;
585                 output.data[0] = buffer;
586                 output.data[1] = buffer + width * height;
587                 output.data[2] = buffer + ( 3 * width * height ) / 2;
588                 output.linesize[0] = width;
589                 output.linesize[1] = width >> 1;
590                 output.linesize[2] = width >> 1;
591                 sws_scale( context, frame->data, frame->linesize, 0, height,
592                         output.data, output.linesize);
593                 sws_freeContext( context );
594         }
595         else if ( format == mlt_image_rgb24 )
596         {
597                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
598                         width, height, PIX_FMT_RGB24, SWS_FAST_BILINEAR, NULL, NULL, NULL);
599                 AVPicture output;
600                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
601                 sws_scale( context, frame->data, frame->linesize, 0, height,
602                         output.data, output.linesize);
603                 sws_freeContext( context );
604         }
605         else
606         {
607                 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
608                         width, height, PIX_FMT_YUYV422, SWS_FAST_BILINEAR, NULL, NULL, NULL);
609                 AVPicture output;
610                 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
611                 sws_scale( context, frame->data, frame->linesize, 0, height,
612                         output.data, output.linesize);
613                 sws_freeContext( context );
614         }
615 #else
616         if ( format == mlt_image_yuv420p )
617         {
618                 AVPicture pict;
619                 pict.data[0] = buffer;
620                 pict.data[1] = buffer + width * height;
621                 pict.data[2] = buffer + ( 3 * width * height ) / 2;
622                 pict.linesize[0] = width;
623                 pict.linesize[1] = width >> 1;
624                 pict.linesize[2] = width >> 1;
625                 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
626         }
627         else if ( format == mlt_image_rgb24 )
628         {
629                 AVPicture output;
630                 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
631                 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
632         }
633         else
634         {
635                 AVPicture output;
636                 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
637                 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
638         }
639 #endif
640 }
641
642 /** Allocate the image buffer and set it on the frame.
643 */
644
645 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
646 {
647         int size = 0;
648
649         if ( codec_context->width == 0 || codec_context->height == 0 )
650                 return size;
651
652         *width = codec_context->width;
653         *height = codec_context->height;
654         mlt_properties_set_int( frame_properties, "width", *width );
655         mlt_properties_set_int( frame_properties, "height", *height );
656
657         switch ( *format )
658         {
659                 case mlt_image_yuv420p:
660                         size = *width * 3 * ( *height + 1 ) / 2;
661                         break;
662                 case mlt_image_rgb24:
663                         size = *width * ( *height + 1 ) * 3;
664                         break;
665                 default:
666                         *format = mlt_image_yuv422;
667                         size = *width * ( *height + 1 ) * 2;
668                         break;
669         }
670
671         // Construct the output image
672         *buffer = mlt_pool_alloc( size );
673         if ( *buffer )
674                 mlt_properties_set_data( frame_properties, "image", *buffer, size, (mlt_destructor)mlt_pool_release, NULL );
675         else
676                 size = 0;
677
678         return size;
679 }
680
681 /** Get an image from a frame.
682 */
683
684 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
685 {
686         // Get the properties from the frame
687         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
688
689         // Obtain the frame number of this frame
690         mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
691
692         // Get the producer
693         mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
694
695         // Get the producer properties
696         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
697
698         // Fetch the video_context
699         AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
700
701         // Get the video_index
702         int index = mlt_properties_get_int( properties, "video_index" );
703
704         // Obtain the expected frame numer
705         mlt_position expected = mlt_properties_get_position( properties, "_video_expected" );
706
707         // Get the video stream
708         AVStream *stream = context->streams[ index ];
709
710         // Get codec context
711         AVCodecContext *codec_context = stream->codec;
712
713         // Packet
714         AVPacket pkt;
715
716         // Get the conversion frame
717         AVFrame *av_frame = mlt_properties_get_data( properties, "av_frame", NULL );
718
719         // Special case pause handling flag
720         int paused = 0;
721
722         // Special case ffwd handling
723         int ignore = 0;
724
725         // We may want to use the source fps if available
726         double source_fps = mlt_properties_get_double( properties, "source_fps" );
727         double fps = mlt_producer_get_fps( this );
728
729         // This is the physical frame position in the source
730         int req_position = ( int )( position / fps * source_fps + 0.5 );
731
732         // Get the seekable status
733         int seekable = mlt_properties_get_int( properties, "seekable" );
734
735         // Hopefully provide better support for streams...
736         int av_bypass = mlt_properties_get_int( properties, "av_bypass" );
737
738         // Determines if we have to decode all frames in a sequence
739         int must_decode = 1;
740
741         // Temporary hack to improve intra frame only
742         must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
743                                   strcmp( codec_context->codec->name, "dvvideo" ) &&
744                                   strcmp( codec_context->codec->name, "huffyuv" ) &&
745                                   strcmp( codec_context->codec->name, "mjpeg" ) &&
746                                   strcmp( codec_context->codec->name, "rawvideo" );
747
748         // Seek if necessary
749         if ( position != expected )
750         {
751                 if ( av_frame != NULL && position + 1 == expected )
752                 {
753                         // We're paused - use last image
754                         paused = 1;
755                 }
756                 else if ( !seekable && position > expected && ( position - expected ) < 250 )
757                 {
758                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
759                         ignore = ( int )( ( position - expected ) / fps * source_fps );
760                 }
761                 else if ( seekable && ( position < expected || position - expected >= 12 ) )
762                 {
763                         // Calculate the timestamp for the requested frame
764                         int64_t timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
765                         if ( ( uint64_t )context->start_time != AV_NOPTS_VALUE )
766                                 timestamp += context->start_time;
767                         if ( must_decode )
768                                 timestamp -= AV_TIME_BASE;
769                         if ( timestamp < 0 )
770                                 timestamp = 0;
771
772                         // Set to the timestamp
773                         av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
774
775                         // Remove the cached info relating to the previous position
776                         mlt_properties_set_int( properties, "_current_position", -1 );
777                         mlt_properties_set_int( properties, "_last_position", -1 );
778                         mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
779                         av_frame = NULL;
780                 }
781         }
782
783         // Duplicate the last image if necessary (see comment on rawvideo below)
784         int current_position = mlt_properties_get_int( properties, "_current_position" );
785         int got_picture = mlt_properties_get_int( properties, "_got_picture" );
786         if ( av_frame != NULL && got_picture && ( paused || current_position >= req_position ) && av_bypass == 0 )
787         {
788                 // Duplicate it
789                 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
790                         convert_image( av_frame, *buffer, codec_context->pix_fmt, *format, *width, *height );
791                 else
792                         mlt_frame_get_image( frame, buffer, format, width, height, writable );
793         }
794         else
795         {
796                 int ret = 0;
797                 int int_position = 0;
798                 got_picture = 0;
799
800                 av_init_packet( &pkt );
801
802                 // Construct an AVFrame for YUV422 conversion
803                 if ( av_frame == NULL )
804                         av_frame = avcodec_alloc_frame( );
805
806                 while( ret >= 0 && !got_picture )
807                 {
808                         // Read a packet
809                         ret = av_read_frame( context, &pkt );
810
811                         // We only deal with video from the selected video_index
812                         if ( ret >= 0 && pkt.stream_index == index && pkt.size > 0 )
813                         {
814                                 // Determine time code of the packet
815                                 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
816                                 if ( context->start_time != AV_NOPTS_VALUE )
817                                         int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
818                                 int last_position = mlt_properties_get_int( properties, "_last_position" );
819                                 if ( int_position == last_position )
820                                         int_position = last_position + 1;
821                                 mlt_properties_set_int( properties, "_last_position", int_position );
822
823                                 // Decode the image
824                                 if ( must_decode || int_position >= req_position )
825                                         ret = avcodec_decode_video( codec_context, av_frame, &got_picture, pkt.data, pkt.size );
826
827                                 if ( got_picture )
828                                 {
829                                         // Handle ignore
830                                         if ( int_position < req_position )
831                                         {
832                                                 ignore = 0;
833                                                 got_picture = 0;
834                                         }
835                                         else if ( int_position >= req_position )
836                                         {
837                                                 ignore = 0;
838                                         }
839                                         else if ( ignore -- )
840                                         {
841                                                 got_picture = 0;
842                                         }
843                                 }
844                                 av_free_packet( &pkt );
845                         }
846                         else if ( ret >= 0 )
847                         {
848                                 av_free_packet( &pkt );
849                         }
850
851                         // Now handle the picture if we have one
852                         if ( got_picture )
853                         {
854                                 if ( allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) )
855                                 {
856                                         convert_image( av_frame, *buffer, codec_context->pix_fmt, *format, *width, *height );
857                                         mlt_properties_set_int( frame_properties, "progressive", !av_frame->interlaced_frame );
858                                         mlt_properties_set_int( properties, "top_field_first", av_frame->top_field_first );
859                                         mlt_properties_set_int( properties, "_current_position", int_position );
860                                         mlt_properties_set_int( properties, "_got_picture", 1 );
861                                         mlt_properties_set_data( properties, "av_frame", av_frame, 0, av_free, NULL );
862                                 }
863                                 else
864                                 {
865                                         got_picture = 0;
866                                 }
867                         }
868                 }
869                 if ( !got_picture )
870                         mlt_frame_get_image( frame, buffer, format, width, height, writable );
871         }
872
873         // Very untidy - for rawvideo, the packet contains the frame, hence the free packet
874         // above will break the pause behaviour - so we wipe the frame now
875         if ( !strcmp( codec_context->codec->name, "rawvideo" ) )
876                 mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
877
878         // Set the field order property for this frame
879         mlt_properties_set_int( frame_properties, "top_field_first", mlt_properties_get_int( properties, "top_field_first" ) );
880
881         // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
882         mlt_properties_set_position( properties, "_video_expected", position + 1 );
883
884         return 0;
885 }
886
887 /** Process properties as AVOptions and apply to AV context obj
888 */
889
890 static void apply_properties( void *obj, mlt_properties properties, int flags )
891 {
892         int i;
893         int count = mlt_properties_count( properties );
894         for ( i = 0; i < count; i++ )
895         {
896                 const char *opt_name = mlt_properties_get_name( properties, i );
897                 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
898                 if ( opt != NULL )
899 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
900                         av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
901 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
902                         av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
903 #else
904                         av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
905 #endif
906         }
907 }
908
909 /** Set up video handling.
910 */
911
912 static void producer_set_up_video( mlt_producer this, mlt_frame frame )
913 {
914         // Get the properties
915         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
916
917         // Fetch the video_context
918         AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
919
920         // Get the video_index
921         int index = mlt_properties_get_int( properties, "video_index" );
922
923         // Reopen the file if necessary
924         if ( !context && index > -1 )
925         {
926                 mlt_events_block( properties, this );
927                 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(this) ),
928                         mlt_properties_get( properties, "resource" ) );
929                 context = mlt_properties_get_data( properties, "video_context", NULL );
930                 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
931                 mlt_events_unblock( properties, this );
932
933                 // Process properties as AVOptions
934                 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
935         }
936
937         // Exception handling for video_index
938         if ( context && index >= (int) context->nb_streams )
939         {
940                 // Get the last video stream
941                 for ( index = context->nb_streams - 1; index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO; --index );
942                 mlt_properties_set_int( properties, "video_index", index );
943         }
944         if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
945         {
946                 // Invalidate the video stream
947                 index = -1;
948                 mlt_properties_set_int( properties, "video_index", index );
949         }
950
951         // Get the frame properties
952         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
953
954         if ( context && index > -1 )
955         {
956                 // Get the video stream
957                 AVStream *stream = context->streams[ index ];
958
959                 // Get codec context
960                 AVCodecContext *codec_context = stream->codec;
961
962                 // Get the codec
963                 AVCodec *codec = mlt_properties_get_data( properties, "video_codec", NULL );
964
965                 // Update the video properties if the index changed
966                 if ( index != mlt_properties_get_int( properties, "_video_index" ) )
967                 {
968                         // Reset the video properties if the index changed
969                         mlt_properties_set_int( properties, "_video_index", index );
970                         mlt_properties_set_data( properties, "video_codec", NULL, 0, NULL, NULL );
971                         mlt_properties_set_int( properties, "width", codec_context->width );
972                         mlt_properties_set_int( properties, "height", codec_context->height );
973                         // TODO: get the first usable AVPacket and reset the stream position
974                         mlt_properties_set_double( properties, "aspect_ratio",
975                                 get_aspect_ratio( context->streams[ index ], codec_context, NULL ) );
976                         codec = NULL;
977                 }
978
979                 // Initialise the codec if necessary
980                 if ( codec == NULL )
981                 {
982                         // Initialise multi-threading
983                         int thread_count = mlt_properties_get_int( properties, "threads" );
984                         if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
985                                 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
986                         if ( thread_count > 1 )
987                         {
988                                 avcodec_thread_init( codec_context, thread_count );
989                                 codec_context->thread_count = thread_count;
990                         }
991
992                         // Find the codec
993                         codec = avcodec_find_decoder( codec_context->codec_id );
994
995                         // If we don't have a codec and we can't initialise it, we can't do much more...
996                         avformat_lock( );
997                         if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
998                         {
999                                 // Now store the codec with its destructor
1000                                 mlt_properties_set_data( properties, "video_codec", codec_context, 0, producer_codec_close, NULL );
1001                         }
1002                         else
1003                         {
1004                                 // Remember that we can't use this later
1005                                 mlt_properties_set_int( properties, "video_index", -1 );
1006                                 index = -1;
1007                         }
1008                         avformat_unlock( );
1009
1010                         // Process properties as AVOptions
1011                         apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1012                 }
1013
1014                 // No codec, no show...
1015                 if ( codec && index > -1 )
1016                 {
1017                         double source_fps = 0;
1018                         double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1019                         double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1020                                 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1021
1022                         // Determine the fps
1023                         source_fps = ( double )codec_context->time_base.den / ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num );
1024
1025                         // We'll use fps if it's available
1026                         if ( source_fps > 0 )
1027                                 mlt_properties_set_double( properties, "source_fps", source_fps );
1028                         else
1029                                 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( this ) );
1030                         mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
1031
1032                         // Set the width and height
1033                         mlt_properties_set_int( frame_properties, "width", codec_context->width );
1034                         mlt_properties_set_int( frame_properties, "height", codec_context->height );
1035                         mlt_properties_set_int( frame_properties, "real_width", codec_context->width );
1036                         mlt_properties_set_int( frame_properties, "real_height", codec_context->height );
1037                         mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1038
1039                         mlt_frame_push_get_image( frame, producer_get_image );
1040                         mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
1041                 }
1042                 else
1043                 {
1044                         mlt_properties_set_int( frame_properties, "test_image", 1 );
1045                 }
1046         }
1047         else
1048         {
1049                 mlt_properties_set_int( frame_properties, "test_image", 1 );
1050         }
1051 }
1052
1053 /** Get the audio from a frame.
1054 */
1055
1056 static int producer_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1057 {
1058         // Get the properties from the frame
1059         mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1060
1061         // Obtain the frame number of this frame
1062         mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1063
1064         // Get the producer
1065         mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
1066
1067         // Get the producer properties
1068         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
1069
1070         // Fetch the audio_context
1071         AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
1072
1073         // Get the audio_index
1074         int index = mlt_properties_get_int( properties, "audio_index" );
1075
1076         // Get the seekable status
1077         int seekable = mlt_properties_get_int( properties, "seekable" );
1078
1079         // Obtain the expected frame numer
1080         mlt_position expected = mlt_properties_get_position( properties, "_audio_expected" );
1081
1082         // Obtain the resample context if it exists (not always needed)
1083         ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
1084
1085 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
1086         // Get the format converter context if it exists
1087         AVAudioConvert *convert = mlt_properties_get_data( properties, "audio_convert", NULL );
1088 #endif
1089
1090         // Obtain the audio buffers
1091         int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
1092         int16_t *decode_buffer = mlt_properties_get_data( properties, "decode_buffer", NULL );
1093         int16_t *convert_buffer = mlt_properties_get_data( properties, "convert_buffer", NULL );
1094
1095         // Get amount of audio used
1096         int audio_used =  mlt_properties_get_int( properties, "_audio_used" );
1097
1098         // Calculate the real time code
1099         double real_timecode = producer_time_of_frame( this, position );
1100
1101         // Get the audio stream
1102         AVStream *stream = context->streams[ index ];
1103
1104         // Get codec context
1105         AVCodecContext *codec_context = stream->codec;
1106
1107         // Packet
1108         AVPacket pkt;
1109
1110         // Number of frames to ignore (for ffwd)
1111         int ignore = 0;
1112
1113         // Flag for paused (silence)
1114         int paused = 0;
1115
1116         // Check for resample and create if necessary
1117         if ( resample == NULL && codec_context->channels <= 2 )
1118         {
1119                 // Create the resampler
1120                 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
1121
1122                 // And store it on properties
1123                 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
1124         }
1125         else if ( resample == NULL )
1126         {
1127                 *channels = codec_context->channels;
1128                 *frequency = codec_context->sample_rate;
1129         }
1130
1131 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
1132         // Check for audio format converter and create if necessary
1133         // TODO: support higher resolutions than 16-bit.
1134         if ( convert == NULL && codec_context->sample_fmt != SAMPLE_FMT_S16 )
1135         {
1136                 // Create single channel converter for interleaved with no mixing matrix
1137                 convert = av_audio_convert_alloc( SAMPLE_FMT_S16, 1, codec_context->sample_fmt, 1, NULL, 0 );
1138                 mlt_properties_set_data( properties, "audio_convert", convert, 0, ( mlt_destructor )av_audio_convert_free, NULL );
1139         }
1140 #endif
1141
1142         // Check for audio buffer and create if necessary
1143         if ( audio_buffer == NULL )
1144         {
1145                 // Allocate the audio buffer
1146                 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1147
1148                 // And store it on properties for reuse
1149                 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
1150         }
1151
1152         // Check for decoder buffer and create if necessary
1153         if ( decode_buffer == NULL )
1154         {
1155                 // Allocate the audio buffer
1156                 decode_buffer = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1157
1158                 // And store it on properties for reuse
1159                 mlt_properties_set_data( properties, "decode_buffer", decode_buffer, 0, ( mlt_destructor )av_free, NULL );
1160         }
1161
1162 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
1163         // Check for format converter buffer and create if necessary
1164         if ( resample && convert && convert_buffer == NULL )
1165         {
1166                 // Allocate the audio buffer
1167                 convert_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1168
1169                 // And store it on properties for reuse
1170                 mlt_properties_set_data( properties, "convert_buffer", convert_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
1171         }
1172 #endif
1173
1174         // Seek if necessary
1175         if ( position != expected )
1176         {
1177                 if ( position + 1 == expected )
1178                 {
1179                         // We're paused - silence required
1180                         paused = 1;
1181                 }
1182                 else if ( !seekable && position > expected && ( position - expected ) < 250 )
1183                 {
1184                         // Fast forward - seeking is inefficient for small distances - just ignore following frames
1185                         ignore = position - expected;
1186                 }
1187                 else if ( position < expected || position - expected >= 12 )
1188                 {
1189                         int64_t timestamp = ( int64_t )( real_timecode * AV_TIME_BASE + 0.5 );
1190                         if ( context->start_time != AV_NOPTS_VALUE )
1191                                 timestamp += context->start_time;
1192                         if ( timestamp < 0 )
1193                                 timestamp = 0;
1194
1195                         // Set to the real timecode
1196                         if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1197                                 paused = 1;
1198
1199                         // Clear the usage in the audio buffer
1200                         audio_used = 0;
1201                 }
1202         }
1203
1204         // Get the audio if required
1205         if ( !paused )
1206         {
1207                 int ret = 0;
1208                 int got_audio = 0;
1209
1210                 av_init_packet( &pkt );
1211
1212                 while( ret >= 0 && !got_audio )
1213                 {
1214                         // Check if the buffer already contains the samples required
1215                         if ( audio_used >= *samples && ignore == 0 )
1216                         {
1217                                 got_audio = 1;
1218                                 break;
1219                         }
1220
1221                         // Read a packet
1222                         ret = av_read_frame( context, &pkt );
1223
1224                         int len = pkt.size;
1225                         uint8_t *ptr = pkt.data;
1226
1227                         // We only deal with audio from the selected audio_index
1228                         while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
1229                         {
1230                                 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1231
1232                                 // Decode the audio
1233 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1234                                 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1235 #else
1236                                 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1237 #endif
1238                                 if ( ret < 0 )
1239                                 {
1240                                         ret = 0;
1241                                         break;
1242                                 }
1243
1244                                 len -= ret;
1245                                 ptr += ret;
1246
1247                                 if ( data_size > 0 )
1248                                 {
1249                                         int src_stride[6]= { av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 };
1250                                         int dst_stride[6]= { av_get_bits_per_sample_format( SAMPLE_FMT_S16 ) / 8 };
1251
1252                                         if ( resample )
1253                                         {
1254                                                 int16_t *source = decode_buffer;
1255                                                 int16_t *dest = &audio_buffer[ audio_used * *channels ];
1256                                                 int convert_samples = data_size / src_stride[0];
1257
1258 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
1259                                                 if ( convert )
1260                                                 {
1261                                                         const void *src_buf[6] = { decode_buffer };
1262                                                         void *dst_buf[6] = { convert_buffer };
1263                                                         av_audio_convert( convert, dst_buf, dst_stride, src_buf, src_stride, convert_samples );
1264                                                         source = convert_buffer;
1265                                                 }
1266 #endif
1267                                                 audio_used += audio_resample( resample, dest, source, convert_samples / codec_context->channels );
1268                                         }
1269                                         else
1270                                         {
1271 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
1272                                                 if ( convert )
1273                                                 {
1274                                                         const void *src_buf[6] = { decode_buffer };
1275                                                         void *dst_buf[6] = { &audio_buffer[ audio_used * *channels ] };
1276                                                         av_audio_convert( convert, dst_buf, dst_stride, src_buf, src_stride, data_size / src_stride[0] );
1277                                                 }
1278                                                 else
1279 #endif
1280                                                 {
1281                                                         memcpy( &audio_buffer[ audio_used * *channels ], decode_buffer, data_size );
1282                                                 }
1283                                                 audio_used += data_size / *channels / src_stride[0];
1284                                         }
1285
1286                                         // Handle ignore
1287                                         while ( ignore && audio_used > *samples )
1288                                         {
1289                                                 ignore --;
1290                                                 audio_used -= *samples;
1291                                                 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
1292                                         }
1293                                 }
1294
1295                                 // If we're behind, ignore this packet
1296                                 if ( pkt.pts >= 0 )
1297                                 {
1298                                         double current_pts = av_q2d( stream->time_base ) * pkt.pts;
1299                                         double source_fps = mlt_properties_get_double( properties, "source_fps" );
1300                                         int req_position = ( int )( real_timecode * source_fps + 0.5 );
1301                                         int int_position = ( int )( current_pts * source_fps + 0.5 );
1302
1303                                         if ( context->start_time != AV_NOPTS_VALUE )
1304                                                 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1305                                         if ( seekable && !ignore && int_position < req_position )
1306                                                 ignore = 1;
1307                                 }
1308                         }
1309
1310                         // We're finished with this packet regardless
1311                         av_free_packet( &pkt );
1312                 }
1313
1314                 *buffer = mlt_pool_alloc( *samples * *channels * sizeof( int16_t ) );
1315                 mlt_properties_set_data( frame_properties, "audio", *buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
1316
1317                 // Now handle the audio if we have enough
1318                 if ( audio_used >= *samples )
1319                 {
1320                         memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
1321                         audio_used -= *samples;
1322                         memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
1323                 }
1324                 else
1325                 {
1326                         memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
1327                 }
1328
1329                 // Store the number of audio samples still available
1330                 mlt_properties_set_int( properties, "_audio_used", audio_used );
1331         }
1332         else
1333         {
1334                 // Get silence and don't touch the context
1335                 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
1336         }
1337
1338         // Regardless of speed (other than paused), we expect to get the next frame
1339         if ( !paused )
1340                 mlt_properties_set_position( properties, "_audio_expected", position + 1 );
1341
1342         return 0;
1343 }
1344
1345 /** Set up audio handling.
1346 */
1347
1348 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
1349 {
1350         // Get the properties
1351         mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
1352
1353         // Fetch the audio_context
1354         AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
1355
1356         // Get the audio_index
1357         int index = mlt_properties_get_int( properties, "audio_index" );
1358
1359         // Reopen the file if necessary
1360         if ( !context && index > -1 )
1361         {
1362                 mlt_events_block( properties, this );
1363                 producer_open( this, mlt_service_profile( MLT_PRODUCER_SERVICE(this) ),
1364                         mlt_properties_get( properties, "resource" ) );
1365                 context = mlt_properties_get_data( properties, "audio_context", NULL );
1366                 mlt_properties_set_data( properties, "dummy_context", NULL, 0, NULL, NULL );
1367                 mlt_events_unblock( properties, this );
1368         }
1369
1370         // Exception handling for audio_index
1371         if ( context && index >= (int) context->nb_streams )
1372         {
1373                 for ( index = context->nb_streams - 1; index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO; --index );
1374                 mlt_properties_set_int( properties, "audio_index", index );
1375         }
1376         if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
1377         {
1378                 index = -1;
1379                 mlt_properties_set_int( properties, "audio_index", index );
1380         }
1381
1382         // Update the audio properties if the index changed
1383         if ( index > -1 && index != mlt_properties_get_int( properties, "_audio_index" ) )
1384         {
1385                 mlt_properties_set_int( properties, "_audio_index", index );
1386                 mlt_properties_set_data( properties, "audio_codec", NULL, 0, NULL, NULL );
1387         }
1388
1389         // Deal with audio context
1390         if ( context != NULL && index > -1 )
1391         {
1392                 // Get the frame properties
1393                 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1394
1395                 // Get the audio stream
1396                 AVStream *stream = context->streams[ index ];
1397
1398                 // Get codec context
1399                 AVCodecContext *codec_context = stream->codec;
1400
1401                 // Get the codec
1402                 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
1403
1404                 // Initialise the codec if necessary
1405                 if ( codec == NULL )
1406                 {
1407                         // Find the codec
1408                         codec = avcodec_find_decoder( codec_context->codec_id );
1409
1410                         // If we don't have a codec and we can't initialise it, we can't do much more...
1411                         avformat_lock( );
1412                         if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
1413                         {
1414                                 // Now store the codec with its destructor
1415                                 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
1416
1417                         }
1418                         else
1419                         {
1420                                 // Remember that we can't use this later
1421                                 mlt_properties_set_int( properties, "audio_index", -1 );
1422                                 index = -1;
1423                         }
1424                         avformat_unlock( );
1425
1426                         // Process properties as AVOptions
1427                         apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1428                 }
1429
1430                 // No codec, no show...
1431                 if ( codec && index > -1 )
1432                 {
1433                         mlt_frame_push_audio( frame, producer_get_audio );
1434                         mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
1435                         mlt_properties_set_int( frame_properties, "frequency", codec_context->sample_rate );
1436                         mlt_properties_set_int( frame_properties, "channels", codec_context->channels );
1437                 }
1438         }
1439 }
1440
1441 /** Our get frame implementation.
1442 */
1443
1444 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
1445 {
1446         // Create an empty frame
1447         *frame = mlt_frame_init( MLT_PRODUCER_SERVICE( this ) );
1448
1449         // Update timecode on the frame we're creating
1450         mlt_frame_set_position( *frame, mlt_producer_position( this ) );
1451
1452         // Set the position of this producer
1453         mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( this ) );
1454
1455         // Set up the video
1456         producer_set_up_video( this, *frame );
1457
1458         // Set up the audio
1459         producer_set_up_audio( this, *frame );
1460
1461         // Set the aspect_ratio
1462         mlt_properties_set_double( MLT_FRAME_PROPERTIES( *frame ), "aspect_ratio", mlt_properties_get_double( MLT_PRODUCER_PROPERTIES( this ), "aspect_ratio" ) );
1463
1464         // Calculate the next timecode
1465         mlt_producer_prepare_next( this );
1466
1467         return 0;
1468 }