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