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