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