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