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