]> git.sesse.net Git - mlt/blob - src/framework/mlt_consumer.c
Add check for null frame.
[mlt] / src / framework / mlt_consumer.c
1 /**
2  * \file mlt_consumer.c
3  * \brief abstraction for all consumer services
4  * \see mlt_consumer_s
5  *
6  * Copyright (C) 2003-2010 Ushodaya Enterprises Limited
7  * \author Charles Yates <charles.yates@pandora.be>
8  * \author Dan Dennedy <dan@dennedy.org>
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 #include "mlt_consumer.h"
26 #include "mlt_factory.h"
27 #include "mlt_producer.h"
28 #include "mlt_frame.h"
29 #include "mlt_profile.h"
30 #include "mlt_log.h"
31
32 #include <stdio.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #include <sys/time.h>
36
37 /** Define this if you want an automatic deinterlace (if necessary) when the
38  * consumer's producer is not running at normal speed.
39  */
40 #undef DEINTERLACE_ON_NOT_NORMAL_SPEED
41
42 /** This is not the ideal place for this, but it is needed by VDPAU as well.
43  */
44 pthread_mutex_t mlt_sdl_mutex = PTHREAD_MUTEX_INITIALIZER;
45
46 static void mlt_consumer_frame_render( mlt_listener listener, mlt_properties owner, mlt_service self, void **args );
47 static void mlt_consumer_frame_show( mlt_listener listener, mlt_properties owner, mlt_service self, void **args );
48 static void mlt_consumer_property_changed( mlt_properties owner, mlt_consumer self, char *name );
49 static void apply_profile_properties( mlt_consumer self, mlt_profile profile, mlt_properties properties );
50 static void on_consumer_frame_show( mlt_properties owner, mlt_consumer self, mlt_frame frame );
51
52 /** Initialize a consumer service.
53  *
54  * \public \memberof mlt_consumer_s
55  * \param self the consumer to initialize
56  * \param child a pointer to the object for the subclass
57  * \param profile the \p mlt_profile_s to use (optional but recommended,
58  * uses the environment variable MLT if self is NULL)
59  * \return true if there was an error
60  */
61
62 int mlt_consumer_init( mlt_consumer self, void *child, mlt_profile profile )
63 {
64         int error = 0;
65         memset( self, 0, sizeof( struct mlt_consumer_s ) );
66         self->child = child;
67         error = mlt_service_init( &self->parent, self );
68         if ( error == 0 )
69         {
70                 // Get the properties from the service
71                 mlt_properties properties = MLT_SERVICE_PROPERTIES( &self->parent );
72
73                 // Apply profile to properties
74                 if ( profile == NULL )
75                 {
76                         // Normally the application creates the profile and controls its lifetime
77                         // This is the fallback exception handling
78                         profile = mlt_profile_init( NULL );
79                         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
80                         mlt_properties_set_data( properties, "_profile", profile, 0, (mlt_destructor)mlt_profile_close, NULL );
81                 }
82                 apply_profile_properties( self, profile, properties );
83
84                 // Default rescaler for all consumers
85                 mlt_properties_set( properties, "rescale", "bilinear" );
86
87                 // Default read ahead buffer size
88                 mlt_properties_set_int( properties, "buffer", 25 );
89
90                 // Default audio frequency and channels
91                 mlt_properties_set_int( properties, "frequency", 48000 );
92                 mlt_properties_set_int( properties, "channels", 2 );
93
94                 // Default of all consumers is real time
95                 mlt_properties_set_int( properties, "real_time", 1 );
96
97                 // Default to environment test card
98                 mlt_properties_set( properties, "test_card", mlt_environment( "MLT_TEST_CARD" ) );
99
100                 // Hmm - default all consumers to yuv422 :-/
101                 self->format = mlt_image_yuv422;
102
103                 mlt_events_register( properties, "consumer-frame-show", ( mlt_transmitter )mlt_consumer_frame_show );
104                 mlt_events_register( properties, "consumer-frame-render", ( mlt_transmitter )mlt_consumer_frame_render );
105                 mlt_events_register( properties, "consumer-stopped", NULL );
106                 mlt_events_listen( properties, self, "consumer-frame-show", ( mlt_listener )on_consumer_frame_show );
107
108                 // Register a property-changed listener to handle the profile property -
109                 // subsequent properties can override the profile
110                 self->event_listener = mlt_events_listen( properties, self, "property-changed", ( mlt_listener )mlt_consumer_property_changed );
111
112                 // Create the push mutex and condition
113                 pthread_mutex_init( &self->put_mutex, NULL );
114                 pthread_cond_init( &self->put_cond, NULL );
115
116         }
117         return error;
118 }
119
120 /** Convert the profile into properties on the consumer.
121  *
122  * \private \memberof mlt_consumer_s
123  * \param self a consumer
124  * \param profile a profile
125  * \param properties a properties list (typically, the consumer's)
126  */
127
128 static void apply_profile_properties( mlt_consumer self, mlt_profile profile, mlt_properties properties )
129 {
130         mlt_event_block( self->event_listener );
131         mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
132         mlt_properties_set_int( properties, "frame_rate_num", profile->frame_rate_num );
133         mlt_properties_set_int( properties, "frame_rate_den", profile->frame_rate_den );
134         mlt_properties_set_int( properties, "width", profile->width );
135         mlt_properties_set_int( properties, "height", profile->height );
136         mlt_properties_set_int( properties, "progressive", profile->progressive );
137         mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile )  );
138         mlt_properties_set_int( properties, "sample_aspect_num", profile->sample_aspect_num );
139         mlt_properties_set_int( properties, "sample_aspect_den", profile->sample_aspect_den );
140         mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile )  );
141         mlt_properties_set_int( properties, "display_aspect_num", profile->display_aspect_num );
142         mlt_properties_set_int( properties, "display_aspect_num", profile->display_aspect_num );
143         mlt_properties_set_int( properties, "colorspace", profile->colorspace );
144         mlt_event_unblock( self->event_listener );
145 }
146
147 /** The property-changed event listener
148  *
149  * \private \memberof mlt_consumer_s
150  * \param owner the events object
151  * \param self the consumer
152  * \param name the name of the property that changed
153  */
154
155 static void mlt_consumer_property_changed( mlt_properties owner, mlt_consumer self, char *name )
156 {
157         if ( !strcmp( name, "mlt_profile" ) )
158         {
159                 // Get the properies
160                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
161
162                 // Get the current profile
163                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
164
165                 // Load the new profile
166                 mlt_profile new_profile = mlt_profile_init( mlt_properties_get( properties, name ) );
167
168                 if ( new_profile )
169                 {
170                         // Copy the profile
171                         if ( profile != NULL )
172                         {
173                                 free( profile->description );
174                                 memcpy( profile, new_profile, sizeof( struct mlt_profile_s ) );
175                                 profile->description = strdup( new_profile->description );
176                                 mlt_profile_close( new_profile );
177                         }
178                         else
179                         {
180                                 profile = new_profile;
181                         }
182
183                         // Apply to properties
184                         apply_profile_properties( self, profile, properties );
185                 }
186         }
187         else if ( !strcmp( name, "frame_rate_num" ) )
188         {
189                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
190                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
191                 if ( profile )
192                 {
193                         profile->frame_rate_num = mlt_properties_get_int( properties, "frame_rate_num" );
194                         mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
195                 }
196         }
197         else if ( !strcmp( name, "frame_rate_den" ) )
198         {
199                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
200                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
201                 if ( profile )
202                 {
203                         profile->frame_rate_den = mlt_properties_get_int( properties, "frame_rate_den" );
204                         mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
205                 }
206         }
207         else if ( !strcmp( name, "width" ) )
208         {
209                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
210                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
211                 if ( profile )
212                         profile->width = mlt_properties_get_int( properties, "width" );
213         }
214         else if ( !strcmp( name, "height" ) )
215         {
216                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
217                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
218                 if ( profile )
219                         profile->height = mlt_properties_get_int( properties, "height" );
220         }
221         else if ( !strcmp( name, "progressive" ) )
222         {
223                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
224                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
225                 if ( profile )
226                         profile->progressive = mlt_properties_get_int( properties, "progressive" );
227         }
228         else if ( !strcmp( name, "sample_aspect_num" ) )
229         {
230                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
231                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
232                 profile->sample_aspect_num = mlt_properties_get_int( properties, "sample_aspect_num" );
233                 if ( profile )
234                         mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile )  );
235         }
236         else if ( !strcmp( name, "sample_aspect_den" ) )
237         {
238                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
239                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
240                 profile->sample_aspect_den = mlt_properties_get_int( properties, "sample_aspect_den" );
241                 if ( profile )
242                         mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile )  );
243         }
244         else if ( !strcmp( name, "display_aspect_num" ) )
245         {
246                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
247                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
248                 if ( profile )
249                 {
250                         profile->display_aspect_num = mlt_properties_get_int( properties, "display_aspect_num" );
251                         mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile )  );
252                 }
253         }
254         else if ( !strcmp( name, "display_aspect_den" ) )
255         {
256                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
257                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
258                 if ( profile )
259                 {
260                         profile->display_aspect_den = mlt_properties_get_int( properties, "display_aspect_den" );
261                         mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile )  );
262                 }
263         }
264         else if ( !strcmp( name, "colorspace" ) )
265         {
266                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
267                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
268                 if ( profile )
269                         profile->colorspace = mlt_properties_get_int( properties, "colorspace" );
270         }
271 }
272
273 /** The transmitter for the consumer-frame-show event
274  *
275  * Invokes the listener.
276  *
277  * \private \memberof mlt_consumer_s
278  * \param listener a function pointer that will be invoked
279  * \param owner the events object that will be passed to \p listener
280  * \param self  a service that will be passed to \p listener
281  * \param args an array of pointers - the first entry is passed as a string to \p listener
282  */
283
284 static void mlt_consumer_frame_show( mlt_listener listener, mlt_properties owner, mlt_service self, void **args )
285 {
286         if ( listener != NULL )
287                 listener( owner, self, ( mlt_frame )args[ 0 ] );
288 }
289
290 /** The transmitter for the consumer-frame-render event
291  *
292  * Invokes the listener.
293  *
294  * \private \memberof mlt_consumer_s
295  * \param listener a function pointer that will be invoked
296  * \param owner the events object that will be passed to \p listener
297  * \param self  a service that will be passed to \p listener
298  * \param args an array of pointers - the first entry is passed as a string to \p listener
299  */
300
301 static void mlt_consumer_frame_render( mlt_listener listener, mlt_properties owner, mlt_service self, void **args )
302 {
303         if ( listener != NULL )
304                 listener( owner, self, ( mlt_frame )args[ 0 ] );
305 }
306
307 /** A listener on the consumer-frame-show event
308  *
309  * Saves the position of the frame shown.
310  *
311  * \private \memberof mlt_consumer_s
312  * \param owner the events object
313  * \param consumer the consumer on which this event occurred
314  * \param frame the frame that was shown
315  */
316
317 static void on_consumer_frame_show( mlt_properties owner, mlt_consumer consumer, mlt_frame frame )
318 {
319         if ( frame )
320                 consumer->position = mlt_frame_get_position( frame );
321 }
322
323 /** Create a new consumer.
324  *
325  * \public \memberof mlt_consumer_s
326  * \param profile a profile (optional, but recommended)
327  * \return a new consumer
328  */
329
330 mlt_consumer mlt_consumer_new( mlt_profile profile )
331 {
332         // Create the memory for the structure
333         mlt_consumer self = malloc( sizeof( struct mlt_consumer_s ) );
334
335         // Initialise it
336         if ( self != NULL )
337                 mlt_consumer_init( self, NULL, profile );
338
339         // Return it
340         return self;
341 }
342
343 /** Get the parent service object.
344  *
345  * \public \memberof mlt_consumer_s
346  * \param self a consumer
347  * \return the parent service class
348  * \see MLT_CONSUMER_SERVICE
349  */
350
351 mlt_service mlt_consumer_service( mlt_consumer self )
352 {
353         return self != NULL ? &self->parent : NULL;
354 }
355
356 /** Get the consumer properties.
357  *
358  * \public \memberof mlt_consumer_s
359  * \param self a consumer
360  * \return the consumer's properties list
361  * \see MLT_CONSUMER_PROPERTIES
362  */
363
364 mlt_properties mlt_consumer_properties( mlt_consumer self )
365 {
366         return self != NULL ? MLT_SERVICE_PROPERTIES( &self->parent ) : NULL;
367 }
368
369 /** Connect the consumer to the producer.
370  *
371  * \public \memberof mlt_consumer_s
372  * \param self a consumer
373  * \param producer a producer
374  * \return > 0 warning, == 0 success, < 0 serious error,
375  *         1 = this service does not accept input,
376  *         2 = the producer is invalid,
377  *         3 = the producer is already registered with this consumer
378  */
379
380 int mlt_consumer_connect( mlt_consumer self, mlt_service producer )
381 {
382         return mlt_service_connect_producer( &self->parent, producer, 0 );
383 }
384
385 /** Start the consumer.
386  *
387  * \public \memberof mlt_consumer_s
388  * \param self a consumer
389  * \return true if there was an error
390  */
391
392 int mlt_consumer_start( mlt_consumer self )
393 {
394         if ( !mlt_consumer_is_stopped( self ) )
395                 return 0;
396
397         // Stop listening to the property-changed event
398         mlt_event_block( self->event_listener );
399
400         // Get the properies
401         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
402
403         // Determine if there's a test card producer
404         char *test_card = mlt_properties_get( properties, "test_card" );
405
406         // Just to make sure nothing is hanging around...
407         self->put = NULL;
408         self->put_active = 1;
409
410         // Deal with it now.
411         if ( test_card != NULL )
412         {
413                 if ( mlt_properties_get_data( properties, "test_card_producer", NULL ) == NULL )
414                 {
415                         // Create a test card producer
416                         mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( self ) );
417                         mlt_producer producer = mlt_factory_producer( profile, NULL, test_card );
418
419                         // Do we have a producer
420                         if ( producer != NULL )
421                         {
422                                 // Test card should loop I guess...
423                                 mlt_properties_set( MLT_PRODUCER_PROPERTIES( producer ), "eof", "loop" );
424                                 //mlt_producer_set_speed( producer, 0 );
425                                 //mlt_producer_set_in_and_out( producer, 0, 0 );
426
427                                 // Set the test card on the consumer
428                                 mlt_properties_set_data( properties, "test_card_producer", producer, 0, ( mlt_destructor )mlt_producer_close, NULL );
429                         }
430                 }
431         }
432         else
433         {
434                 // Allow the hash table to speed things up
435                 mlt_properties_set_data( properties, "test_card_producer", NULL, 0, NULL, NULL );
436         }
437
438         // Set the frame duration in microseconds for the frame-dropping heuristic
439         int frame_duration = 1000000 / mlt_properties_get_int( properties, "frame_rate_num" ) *
440                         mlt_properties_get_int( properties, "frame_rate_den" );
441         mlt_properties_set_int( properties, "frame_duration", frame_duration );
442
443         // Check and run an ante command
444         if ( mlt_properties_get( properties, "ante" ) )
445                 if ( system( mlt_properties_get( properties, "ante" ) ) == -1 )
446                         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_ERROR, "system(%s) failed!\n", mlt_properties_get( properties, "ante" ) );
447
448         // Set the real_time preference
449         self->real_time = mlt_properties_get_int( properties, "real_time" );
450
451         // For worker threads implementation, buffer must be at least # threads
452         if ( abs( self->real_time ) > 1 && mlt_properties_get_int( properties, "buffer" ) <= abs( self->real_time ) )
453                 mlt_properties_set_int( properties, "_buffer", abs( self->real_time ) + 1 );
454
455         // Start the service
456         if ( self->start != NULL )
457                 return self->start( self );
458
459         return 0;
460 }
461
462 /** An alternative method to feed frames into the consumer.
463  *
464  * Only valid if the consumer itself is not connected.
465  *
466  * \public \memberof mlt_consumer_s
467  * \param self a consumer
468  * \param frame a frame
469  * \return true (ignore self for now)
470  */
471
472 int mlt_consumer_put_frame( mlt_consumer self, mlt_frame frame )
473 {
474         int error = 1;
475
476         // Get the service assoicated to the consumer
477         mlt_service service = MLT_CONSUMER_SERVICE( self );
478
479         if ( mlt_service_producer( service ) == NULL )
480         {
481                 struct timeval now;
482                 struct timespec tm;
483                 pthread_mutex_lock( &self->put_mutex );
484                 while ( self->put_active && self->put != NULL )
485                 {
486                         gettimeofday( &now, NULL );
487                         tm.tv_sec = now.tv_sec + 1;
488                         tm.tv_nsec = now.tv_usec * 1000;
489                         pthread_cond_timedwait( &self->put_cond, &self->put_mutex, &tm );
490                 }
491                 if ( self->put_active && self->put == NULL )
492                         self->put = frame;
493                 else
494                         mlt_frame_close( frame );
495                 pthread_cond_broadcast( &self->put_cond );
496                 pthread_mutex_unlock( &self->put_mutex );
497         }
498         else
499         {
500                 mlt_frame_close( frame );
501         }
502
503         return error;
504 }
505
506 /** Protected method for consumer to get frames from connected service
507  *
508  * \public \memberof mlt_consumer_s
509  * \param self a consumer
510  * \return a frame
511  */
512
513 mlt_frame mlt_consumer_get_frame( mlt_consumer self )
514 {
515         // Frame to return
516         mlt_frame frame = NULL;
517
518         // Get the service assoicated to the consumer
519         mlt_service service = MLT_CONSUMER_SERVICE( self );
520
521         // Get the consumer properties
522         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
523
524         // Get the frame
525         if ( mlt_service_producer( service ) == NULL && mlt_properties_get_int( properties, "put_mode" ) )
526         {
527                 struct timeval now;
528                 struct timespec tm;
529                 pthread_mutex_lock( &self->put_mutex );
530                 while ( self->put_active && self->put == NULL )
531                 {
532                         gettimeofday( &now, NULL );
533                         tm.tv_sec = now.tv_sec + 1;
534                         tm.tv_nsec = now.tv_usec * 1000;
535                         pthread_cond_timedwait( &self->put_cond, &self->put_mutex, &tm );
536                 }
537                 frame = self->put;
538                 self->put = NULL;
539                 pthread_cond_broadcast( &self->put_cond );
540                 pthread_mutex_unlock( &self->put_mutex );
541                 if ( frame != NULL )
542                         mlt_service_apply_filters( service, frame, 0 );
543         }
544         else if ( mlt_service_producer( service ) != NULL )
545         {
546                 mlt_service_get_frame( service, &frame, 0 );
547         }
548         else
549         {
550                 frame = mlt_frame_init( service );
551         }
552
553         if ( frame != NULL )
554         {
555                 // Get the frame properties
556                 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
557
558                 // Get the test card producer
559                 mlt_producer test_card = mlt_properties_get_data( properties, "test_card_producer", NULL );
560
561                 // Attach the test frame producer to it.
562                 if ( test_card != NULL )
563                         mlt_properties_set_data( frame_properties, "test_card_producer", test_card, 0, NULL, NULL );
564
565                 // Attach the rescale property
566                 mlt_properties_set( frame_properties, "rescale.interp", mlt_properties_get( properties, "rescale" ) );
567
568                 // Aspect ratio and other jiggery pokery
569                 mlt_properties_set_double( frame_properties, "consumer_aspect_ratio", mlt_properties_get_double( properties, "aspect_ratio" ) );
570                 mlt_properties_set_int( frame_properties, "consumer_deinterlace", mlt_properties_get_int( properties, "progressive" ) | mlt_properties_get_int( properties, "deinterlace" ) );
571                 mlt_properties_set( frame_properties, "deinterlace_method", mlt_properties_get( properties, "deinterlace_method" ) );
572         }
573
574         // Return the frame
575         return frame;
576 }
577
578 /** Compute the time difference between now and a time value.
579  *
580  * \private \memberof mlt_consumer_s
581  * \param time1 a time value to be compared against now
582  * \return the difference in microseconds
583  */
584
585 static inline long time_difference( struct timeval *time1 )
586 {
587         struct timeval time2;
588         time2.tv_sec = time1->tv_sec;
589         time2.tv_usec = time1->tv_usec;
590         gettimeofday( time1, NULL );
591         return time1->tv_sec * 1000000 + time1->tv_usec - time2.tv_sec * 1000000 - time2.tv_usec;
592 }
593
594 /** The thread procedure for asynchronously pulling frames through the service
595  * network connected to a consumer.
596  *
597  * \private \memberof mlt_consumer_s
598  * \param arg a consumer
599  */
600
601 static void *consumer_read_ahead_thread( void *arg )
602 {
603         // The argument is the consumer
604         mlt_consumer self = arg;
605
606         // Get the properties of the consumer
607         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
608
609         // Get the width and height
610         int width = mlt_properties_get_int( properties, "width" );
611         int height = mlt_properties_get_int( properties, "height" );
612
613         // See if video is turned off
614         int video_off = mlt_properties_get_int( properties, "video_off" );
615         int preview_off = mlt_properties_get_int( properties, "preview_off" );
616         int preview_format = mlt_properties_get_int( properties, "preview_format" );
617
618         // Get the audio settings
619         mlt_audio_format afmt = mlt_audio_s16;
620         int counter = 0;
621         double fps = mlt_properties_get_double( properties, "fps" );
622         int channels = mlt_properties_get_int( properties, "channels" );
623         int frequency = mlt_properties_get_int( properties, "frequency" );
624         int samples = 0;
625         void *audio = NULL;
626
627         // See if audio is turned off
628         int audio_off = mlt_properties_get_int( properties, "audio_off" );
629
630         // Get the maximum size of the buffer
631         int buffer = mlt_properties_get_int( properties, "buffer" ) + 1;
632
633         // General frame variable
634         mlt_frame frame = NULL;
635         uint8_t *image = NULL;
636
637         // Time structures
638         struct timeval ante;
639
640         // Average time for get_frame and get_image
641         int count = 0;
642         int skipped = 0;
643         int64_t time_process = 0;
644         int skip_next = 0;
645         mlt_position pos = 0;
646         mlt_position start_pos = 0;
647         mlt_position last_pos = 0;
648         int frame_duration = mlt_properties_get_int( properties, "frame_duration" );
649
650         if ( preview_off && preview_format != 0 )
651                 self->format = preview_format;
652
653         // Get the first frame
654         frame = mlt_consumer_get_frame( self );
655
656         if ( frame )
657         {
658                 // Get the image of the first frame
659                 if ( !video_off )
660                 {
661                         mlt_events_fire( MLT_CONSUMER_PROPERTIES( self ), "consumer-frame-render", frame, NULL );
662                         mlt_frame_get_image( frame, &image, &self->format, &width, &height, 0 );
663                 }
664
665                 if ( !audio_off )
666                 {
667                         samples = mlt_sample_calculator( fps, frequency, counter++ );
668                         mlt_frame_get_audio( frame, &audio, &afmt, &frequency, &channels, &samples );
669                 }
670
671                 // Mark as rendered
672                 mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 );
673                 last_pos = start_pos = pos = mlt_frame_get_position( frame );
674         }
675
676         // Get the starting time (can ignore the times above)
677         gettimeofday( &ante, NULL );
678
679         // Continue to read ahead
680         while ( self->ahead )
681         {
682                 // Put the current frame into the queue
683                 pthread_mutex_lock( &self->queue_mutex );
684                 while( self->ahead && mlt_deque_count( self->queue ) >= buffer )
685                         pthread_cond_wait( &self->queue_cond, &self->queue_mutex );
686                 mlt_deque_push_back( self->queue, frame );
687                 pthread_cond_broadcast( &self->queue_cond );
688                 pthread_mutex_unlock( &self->queue_mutex );
689
690                 // Get the next frame
691                 frame = mlt_consumer_get_frame( self );
692
693                 // If there's no frame, we're probably stopped...
694                 if ( frame == NULL )
695                         continue;
696                 pos = mlt_frame_get_position( frame );
697
698                 // Increment the counter used for averaging processing cost
699                 count ++;
700
701                 // All non-normal playback frames should be shown
702                 if ( mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "_speed" ) != 1 )
703                 {
704 #ifdef DEINTERLACE_ON_NOT_NORMAL_SPEED
705                         mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "consumer_deinterlace", 1 );
706 #endif
707                         // Indicate seeking or trick-play
708                         start_pos = pos;
709                 }
710
711                 // If skip flag not set or frame-dropping disabled
712                 if ( !skip_next || self->real_time == -1 )
713                 {
714                         if ( !video_off )
715                         {
716                                 // Reset width/height - could have been changed by previous mlt_frame_get_image
717                                 width = mlt_properties_get_int( properties, "width" );
718                                 height = mlt_properties_get_int( properties, "height" );
719
720                                 // Get the image
721                                 mlt_events_fire( MLT_CONSUMER_PROPERTIES( self ), "consumer-frame-render", frame, NULL );
722                                 mlt_frame_get_image( frame, &image, &self->format, &width, &height, 0 );
723                         }
724
725                         // Indicate the rendered image is available.
726                         mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 );
727
728                         // Reset consecutively-skipped counter
729                         skipped = 0;
730                 }
731                 else // Skip image processing
732                 {
733                         // Increment the number of consecutively-skipped frames
734                         skipped++;
735
736                         // If too many (1 sec) consecutively-skipped frames
737                         if ( skipped > fps )
738                         {
739                                 // Reset cost tracker
740                                 time_process = 0;
741                                 count = 1;
742                                 mlt_log_verbose( self, "too many frames dropped - forcing next frame\n" );
743                         }
744                 }
745
746                 // Always process audio
747                 if ( !audio_off )
748                 {
749                         samples = mlt_sample_calculator( fps, frequency, counter++ );
750                         mlt_frame_get_audio( frame, &audio, &afmt, &frequency, &channels, &samples );
751                 }
752
753                 // Get the time to process this frame
754                 int64_t time_current = time_difference( &ante );
755
756                 // If the current time is not suddenly some large amount
757                 if ( time_current < time_process / count * 20 || !time_process || count < 5 )
758                 {
759                         // Accumulate the cost for processing this frame
760                         time_process += time_current;
761                 }
762                 else
763                 {
764                         mlt_log_debug( self, "current %"PRId64" threshold %"PRId64" count %d\n",
765                                 time_current, (int64_t) (time_process / count * 20), count );
766                         // Ignore the cost of this frame's time
767                         count--;
768                 }
769
770                 // Determine if we started, resumed, or seeked
771                 if ( pos != last_pos + 1 )
772                         start_pos = pos;
773                 last_pos = pos;
774
775                 // Do not skip the first 20% of buffer at start, resume, or seek
776                 if ( pos - start_pos <= buffer / 5 + 1 )
777                 {
778                         // Reset cost tracker
779                         time_process = 0;
780                         count = 1;
781                 }
782
783                 // Reset skip flag
784                 skip_next = 0;
785
786                 // Only consider skipping if the buffer level is low (or really small)
787                 if ( mlt_deque_count( self->queue ) <= buffer / 5 + 1 )
788                 {
789                         // Skip next frame if average cost exceeds frame duration.
790                         if ( time_process / count > frame_duration )
791                                 skip_next = 1;
792                         if ( skip_next )
793                                 mlt_log_debug( self, "avg usec %"PRId64" (%"PRId64"/%d) duration %d\n",
794                                         time_process/count, time_process, count, frame_duration);
795                 }
796         }
797
798         // Remove the last frame
799         mlt_frame_close( frame );
800
801         return NULL;
802 }
803
804 /** Locate the first unprocessed frame in the queue.
805  *
806  * When playing with realtime behavior, we do not use the true head, but
807  * rather an adjusted process_head. The process_head is adjusted based on
808  * the rate of frame-dropping or recovery from frame-dropping. The idea is
809  * that as the level of frame-dropping increases to move the process_head
810  * closer to the tail because the frames are not completing processing prior
811  * to their playout! Then, as frames are not dropped the process_head moves
812  * back closer to the head of the queue so that worker threads can work 
813  * ahead of the playout point (queue head).
814  *
815  * \private \memberof mlt_consumer_s
816  * \param self a consumer
817  * \return an index into the queue
818  */
819
820 static inline int first_unprocessed_frame( mlt_consumer self )
821 {
822         int index = self->real_time <= 0 ? 0 : self->process_head;
823         while ( index < mlt_deque_count( self->queue ) && MLT_FRAME( mlt_deque_peek( self->queue, index ) )->is_processing )
824                 index++;
825         return index;
826 }
827
828 /** The worker thread procedure for parallel processing frames.
829  *
830  * \private \memberof mlt_consumer_s
831  * \param arg a consumer
832  */
833
834 static void *consumer_worker_thread( void *arg )
835 {
836         // The argument is the consumer
837         mlt_consumer self = arg;
838
839         // Get the properties of the consumer
840         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
841
842         // Get the width and height
843         int width = mlt_properties_get_int( properties, "width" );
844         int height = mlt_properties_get_int( properties, "height" );
845         mlt_image_format format = self->format;
846
847         // See if video is turned off
848         int video_off = mlt_properties_get_int( properties, "video_off" );
849         int preview_off = mlt_properties_get_int( properties, "preview_off" );
850         int preview_format = mlt_properties_get_int( properties, "preview_format" );
851
852         // General frame variable
853         mlt_frame frame = NULL;
854         uint8_t *image = NULL;
855
856         if ( preview_off && preview_format != 0 )
857                 format = preview_format;
858
859         // Continue to read ahead
860         while ( self->ahead )
861         {
862                 // Get the next unprocessed frame from the work queue
863                 pthread_mutex_lock( &self->queue_mutex );
864                 int index = first_unprocessed_frame( self );
865                 while ( self->ahead && index >= mlt_deque_count( self->queue ) )
866                 {
867                         mlt_log_debug( MLT_CONSUMER_SERVICE(self), "waiting in worker index = %d queue count = %d\n",
868                                 index, mlt_deque_count( self->queue ) );
869                         pthread_cond_wait( &self->queue_cond, &self->queue_mutex );
870                         index = first_unprocessed_frame( self );
871                 }
872
873                 // Mark the frame for processing
874                 frame = mlt_deque_peek( self->queue, index );
875                 if ( frame )
876                 {
877                         mlt_log_debug( MLT_CONSUMER_SERVICE(self), "worker processing index = %d frame %d queue count = %d\n",
878                                 index, mlt_frame_get_position(frame), mlt_deque_count( self->queue ) );
879                         frame->is_processing = 1;
880                         mlt_properties_inc_ref( MLT_FRAME_PROPERTIES( frame ) );
881                 }
882                 pthread_mutex_unlock( &self->queue_mutex );
883
884                 // If there's no frame, we're probably stopped...
885                 if ( frame == NULL )
886                         continue;
887
888 #ifdef DEINTERLACE_ON_NOT_NORMAL_SPEED
889                 // All non normal playback frames should be shown
890                 if ( mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "_speed" ) != 1 )
891                         mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "consumer_deinterlace", 1 );
892 #endif
893
894                 // Get the image
895                 if ( !video_off )
896                 {
897                         // Fetch width/height again
898                         width = mlt_properties_get_int( properties, "width" );
899                         height = mlt_properties_get_int( properties, "height" );
900                         mlt_events_fire( MLT_CONSUMER_PROPERTIES( self ), "consumer-frame-render", frame, NULL );
901                         mlt_frame_get_image( frame, &image, &format, &width, &height, 0 );
902                 }
903                 mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 );
904                 mlt_frame_close( frame );
905
906                 // Tell a waiting thread (non-realtime main consumer thread) that we are done.
907                 pthread_mutex_lock( &self->done_mutex );
908                 pthread_cond_broadcast( &self->done_cond );
909                 pthread_mutex_unlock( &self->done_mutex );
910         }
911
912         return NULL;
913 }
914
915 /** Start the read/render thread.
916  *
917  * \private \memberof mlt_consumer_s
918  * \param self a consumer
919  */
920
921 static void consumer_read_ahead_start( mlt_consumer self )
922 {
923         // We're running now
924         self->ahead = 1;
925
926         // Create the frame queue
927         self->queue = mlt_deque_init( );
928
929         // Create the queue mutex
930         pthread_mutex_init( &self->queue_mutex, NULL );
931
932         // Create the condition
933         pthread_cond_init( &self->queue_cond, NULL );
934
935         // Create the read ahead
936         if ( mlt_properties_get( MLT_CONSUMER_PROPERTIES( self ), "priority" ) )
937         {
938                 struct sched_param priority;
939                 priority.sched_priority = mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( self ), "priority" );
940                 pthread_attr_t thread_attributes;
941                 pthread_attr_init( &thread_attributes );
942                 pthread_attr_setschedpolicy( &thread_attributes, SCHED_OTHER );
943                 pthread_attr_setschedparam( &thread_attributes, &priority );
944                 pthread_attr_setinheritsched( &thread_attributes, PTHREAD_EXPLICIT_SCHED );
945                 pthread_attr_setscope( &thread_attributes, PTHREAD_SCOPE_SYSTEM );
946                 if ( pthread_create( &self->ahead_thread, &thread_attributes, consumer_read_ahead_thread, self ) < 0 )
947                         pthread_create( &self->ahead_thread, NULL, consumer_read_ahead_thread, self );
948                 pthread_attr_destroy( &thread_attributes );
949         }
950         else
951         {
952                 pthread_create( &self->ahead_thread, NULL, consumer_read_ahead_thread, self );
953         }
954         self->started = 1;
955 }
956
957 /** Start the worker threads.
958  *
959  * \private \memberof mlt_consumer_s
960  * \param self a consumer
961  */
962
963 static void consumer_work_start( mlt_consumer self )
964 {
965         int n = abs( self->real_time );
966         pthread_t *thread = calloc( 1, sizeof( pthread_t ) * n );
967
968         // We're running now
969         self->ahead = 1;
970         
971         // These keep track of the accelleration of frame dropping or recovery.
972         self->consecutive_dropped = 0;
973         self->consecutive_rendered = 0;
974         
975         // This is the position in the queue from which to look for a frame to process.
976         // If we always start from the head, then we may likely not complete processing
977         // before the frame is played out.
978         self->process_head = 0;
979
980         // Create the queues
981         self->queue = mlt_deque_init();
982         self->worker_threads = mlt_deque_init();
983
984         // Create the mutexes
985         pthread_mutex_init( &self->queue_mutex, NULL );
986         pthread_mutex_init( &self->done_mutex, NULL );
987
988         // Create the conditions
989         pthread_cond_init( &self->queue_cond, NULL );
990         pthread_cond_init( &self->done_cond, NULL );
991
992         // Create the read ahead
993         if ( mlt_properties_get( MLT_CONSUMER_PROPERTIES( self ), "priority" ) )
994         {
995
996                 struct sched_param priority;
997                 pthread_attr_t thread_attributes;
998
999                 priority.sched_priority = mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( self ), "priority" );
1000                 pthread_attr_init( &thread_attributes );
1001                 pthread_attr_setschedpolicy( &thread_attributes, SCHED_OTHER );
1002                 pthread_attr_setschedparam( &thread_attributes, &priority );
1003                 pthread_attr_setinheritsched( &thread_attributes, PTHREAD_EXPLICIT_SCHED );
1004                 pthread_attr_setscope( &thread_attributes, PTHREAD_SCOPE_SYSTEM );
1005
1006                 while ( n-- )
1007                 {
1008                         if ( pthread_create( thread, &thread_attributes, consumer_worker_thread, self ) < 0 )
1009                                 if ( pthread_create( thread, NULL, consumer_worker_thread, self ) == 0 )
1010                                         mlt_deque_push_back( self->worker_threads, thread );
1011                         thread++;
1012                 }
1013                 pthread_attr_destroy( &thread_attributes );
1014         }
1015
1016         else
1017         {
1018                 while ( n-- )
1019                 {
1020                         if ( pthread_create( thread, NULL, consumer_worker_thread, self ) == 0 )
1021                                 mlt_deque_push_back( self->worker_threads, thread );
1022                         thread++;
1023                 }
1024         }
1025         self->started = 1;
1026 }
1027
1028 /** Stop the read/render thread.
1029  *
1030  * \private \memberof mlt_consumer_s
1031  * \param self a consumer
1032  */
1033
1034 static void consumer_read_ahead_stop( mlt_consumer self )
1035 {
1036         // Make sure we're running
1037         if ( self->started )
1038         {
1039                 // Inform thread to stop
1040                 self->ahead = 0;
1041
1042                 // Broadcast to the condition in case it's waiting
1043                 pthread_mutex_lock( &self->queue_mutex );
1044                 pthread_cond_broadcast( &self->queue_cond );
1045                 pthread_mutex_unlock( &self->queue_mutex );
1046
1047                 // Broadcast to the put condition in case it's waiting
1048                 pthread_mutex_lock( &self->put_mutex );
1049                 pthread_cond_broadcast( &self->put_cond );
1050                 pthread_mutex_unlock( &self->put_mutex );
1051
1052                 // Join the thread
1053                 pthread_join( self->ahead_thread, NULL );
1054                 self->started = 0;
1055
1056                 // Destroy the frame queue mutex
1057                 pthread_mutex_destroy( &self->queue_mutex );
1058
1059                 // Destroy the condition
1060                 pthread_cond_destroy( &self->queue_cond );
1061
1062                 // Wipe the queue
1063                 while ( mlt_deque_count( self->queue ) )
1064                         mlt_frame_close( mlt_deque_pop_back( self->queue ) );
1065
1066                 // Close the queue
1067                 mlt_deque_close( self->queue );
1068         }
1069 }
1070
1071 /** Stop the worker threads.
1072  *
1073  * \private \memberof mlt_consumer_s
1074  * \param self a consumer
1075  */
1076
1077 static void consumer_work_stop( mlt_consumer self )
1078 {
1079         // Make sure we're running
1080         if ( self->started )
1081         {
1082                 // Inform thread to stop
1083                 self->ahead = 0;
1084
1085                 // Broadcast to the queue condition in case it's waiting
1086                 pthread_mutex_lock( &self->queue_mutex );
1087                 pthread_cond_broadcast( &self->queue_cond );
1088                 pthread_mutex_unlock( &self->queue_mutex );
1089
1090                 // Broadcast to the put condition in case it's waiting
1091                 pthread_mutex_lock( &self->put_mutex );
1092                 pthread_cond_broadcast( &self->put_cond );
1093                 pthread_mutex_unlock( &self->put_mutex );
1094
1095                 // Broadcast to the done condition in case it's waiting
1096                 pthread_mutex_lock( &self->done_mutex );
1097                 pthread_cond_broadcast( &self->done_cond );
1098                 pthread_mutex_unlock( &self->done_mutex );
1099
1100                 // Join the threads
1101                 pthread_t *thread;
1102                 while ( ( thread = mlt_deque_pop_back( self->worker_threads ) ) )
1103                         pthread_join( *thread, NULL );
1104
1105                 // Deallocate the array of threads
1106                 if ( thread )
1107                         free( thread );
1108
1109                 // Indicate that worker threads no longer running
1110                 self->started = 0;
1111
1112                 // Destroy the mutexes
1113                 pthread_mutex_destroy( &self->queue_mutex );
1114                 pthread_mutex_destroy( &self->done_mutex );
1115
1116                 // Destroy the conditions
1117                 pthread_cond_destroy( &self->queue_cond );
1118                 pthread_cond_destroy( &self->done_cond );
1119
1120                 // Wipe the queues
1121                 while ( mlt_deque_count( self->queue ) )
1122                         mlt_frame_close( mlt_deque_pop_back( self->queue ) );
1123
1124                 // Close the queues
1125                 mlt_deque_close( self->queue );
1126                 mlt_deque_close( self->worker_threads );
1127         }
1128 }
1129
1130 /** Flush the read/render thread's buffer.
1131  *
1132  * \public \memberof mlt_consumer_s
1133  * \param self a consumer
1134  */
1135
1136 void mlt_consumer_purge( mlt_consumer self )
1137 {
1138         if ( self->ahead )
1139         {
1140                 pthread_mutex_lock( &self->queue_mutex );
1141                 while ( mlt_deque_count( self->queue ) )
1142                         mlt_frame_close( mlt_deque_pop_back( self->queue ) );
1143                 pthread_cond_broadcast( &self->queue_cond );
1144                 pthread_mutex_unlock( &self->queue_mutex );
1145         }
1146 }
1147
1148 /** Use multiple worker threads and a work queue.
1149  */
1150
1151 static mlt_frame worker_get_frame( mlt_consumer self, mlt_properties properties )
1152 {
1153         // Frame to return
1154         mlt_frame frame = NULL;
1155
1156         double fps = mlt_properties_get_double( properties, "fps" );
1157         int threads = abs( self->real_time );
1158         int buffer = mlt_properties_get_int( properties, "_buffer" );
1159         buffer = buffer > 0 ? buffer : mlt_properties_get_int( properties, "buffer" );
1160         // This is a heuristic to determine a suitable minimum buffer size for the number of threads.
1161         int headroom = 2 + threads * threads;
1162         buffer = buffer < headroom ? headroom : buffer;
1163
1164         // Start worker threads if not already started.
1165         if ( ! self->ahead )
1166         {
1167                 int prefill = mlt_properties_get_int( properties, "prefill" );
1168                 prefill = prefill > 0 && prefill < buffer ? prefill : buffer;
1169
1170                 consumer_work_start( self );
1171
1172                 // Fill the work queue.
1173                 int i = buffer;
1174                 while ( self->ahead && i-- )
1175                 {
1176                         frame = mlt_consumer_get_frame( self );
1177                         if ( frame )
1178                         {
1179                                 pthread_mutex_lock( &self->queue_mutex );
1180                                 mlt_deque_push_back( self->queue, frame );
1181                                 pthread_cond_signal( &self->queue_cond );
1182                                 pthread_mutex_unlock( &self->queue_mutex );
1183                         }
1184                 }
1185
1186                 // Wait for prefill
1187                 while ( self->ahead && first_unprocessed_frame( self ) < prefill )
1188                 {
1189                         pthread_mutex_lock( &self->done_mutex );
1190                         pthread_cond_wait( &self->done_cond, &self->done_mutex );
1191                         pthread_mutex_unlock( &self->done_mutex );
1192                 }
1193                 self->process_head = threads;
1194         }
1195
1196 //      mlt_log_verbose( MLT_CONSUMER_SERVICE(self), "size %d done count %d work count %d process_head %d\n",
1197 //              threads, first_unprocessed_frame( self ), mlt_deque_count( self->queue ), self->process_head );
1198
1199         // Feed the work queue
1200         while ( self->ahead && mlt_deque_count( self->queue ) < buffer )
1201         {
1202                 frame = mlt_consumer_get_frame( self );
1203                 if ( ! frame )
1204                         return frame;
1205                 pthread_mutex_lock( &self->queue_mutex );
1206                 mlt_deque_push_back( self->queue, frame );
1207                 pthread_cond_signal( &self->queue_cond );
1208                 pthread_mutex_unlock( &self->queue_mutex );
1209         }
1210
1211         // Wait if not realtime.
1212         mlt_frame head_frame = MLT_FRAME( mlt_deque_peek_front( self->queue ) );
1213         while ( self->ahead && self->real_time < 0 &&
1214                 !( head_frame && mlt_properties_get_int( MLT_FRAME_PROPERTIES( head_frame ), "rendered" ) ) )
1215         {
1216                 pthread_mutex_lock( &self->done_mutex );
1217                 pthread_cond_wait( &self->done_cond, &self->done_mutex );
1218                 pthread_mutex_unlock( &self->done_mutex );
1219         }
1220         
1221         // Get the frame from the queue.
1222         pthread_mutex_lock( &self->queue_mutex );
1223         frame = mlt_deque_pop_front( self->queue );
1224         pthread_mutex_unlock( &self->queue_mutex );
1225
1226         // Adapt the worker process head to the runtime conditions.
1227         if ( self->real_time > 0 )
1228         {
1229                 if ( frame && mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "rendered" ) )
1230                 {
1231                         self->consecutive_dropped = 0;
1232                         if ( self->process_head > threads && self->consecutive_rendered >= self->process_head )
1233                                 self->process_head--;
1234                         else
1235                                 self->consecutive_rendered++;
1236                 }
1237                 else
1238                 {
1239                         self->consecutive_rendered = 0;
1240                         if ( self->process_head < buffer - threads && self->consecutive_dropped > threads )
1241                                 self->process_head++;
1242                         else
1243                                 self->consecutive_dropped++;
1244                 }
1245 //              mlt_log_verbose( MLT_CONSUMER_SERVICE(self), "dropped %d rendered %d process_head %d\n",
1246 //                      self->consecutive_dropped, self->consecutive_rendered, self->process_head );
1247
1248                 // Check for too many consecutively dropped frames
1249                 if ( self->consecutive_dropped > fps )
1250                 {
1251                         int orig_buffer = mlt_properties_get_int( properties, "buffer" );
1252                         int prefill = mlt_properties_get_int( properties, "prefill" );
1253                         mlt_log_verbose( self, "too many frames dropped - " );
1254
1255                         // If using a default low-latency buffer level (SDL) and below the limit
1256                         if ( ( orig_buffer == 1 || prefill == 1 ) && buffer < (threads + 1) * 10 )
1257                         {
1258                                 // Auto-scale the buffer to compensate
1259                                 mlt_log_verbose( self, "increasing buffer to %d\n", buffer + threads );
1260                                 mlt_properties_set_int( properties, "_buffer", buffer + threads );
1261                                 self->consecutive_dropped = fps / 2;
1262                         }
1263                         else
1264                         {
1265                                 // Tell the consumer to render it
1266                                 mlt_log_verbose( self, "forcing next frame\n" );
1267                                 mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 );
1268                                 self->consecutive_dropped = 0;
1269                         }
1270                 }
1271         }
1272         
1273         return frame;
1274 }
1275
1276 /** Get the next frame from the producer connected to a consumer.
1277  *
1278  * Typically, one uses this instead of \p mlt_consumer_get_frame to make
1279  * the asynchronous/real-time behavior configurable at runtime.
1280  * You should close the frame returned from this when you are done with it.
1281  *
1282  * \public \memberof mlt_consumer_s
1283  * \param self a consumer
1284  * \return a frame
1285  */
1286
1287 mlt_frame mlt_consumer_rt_frame( mlt_consumer self )
1288 {
1289         // Frame to return
1290         mlt_frame frame = NULL;
1291
1292         // Get the properties
1293         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
1294
1295         // Check if the user has requested real time or not
1296         if ( self->real_time > 1 || self->real_time < -1 )
1297         {
1298                 // see above
1299                 return worker_get_frame( self, properties );
1300         }
1301         else if ( self->real_time == 1 || self->real_time == -1 )
1302         {
1303                 int size = 1;
1304
1305                 // Is the read ahead running?
1306                 if ( self->ahead == 0 )
1307                 {
1308                         int buffer = mlt_properties_get_int( properties, "buffer" );
1309                         int prefill = mlt_properties_get_int( properties, "prefill" );
1310                         consumer_read_ahead_start( self );
1311                         if ( buffer > 1 )
1312                                 size = prefill > 0 && prefill < buffer ? prefill : buffer;
1313                 }
1314
1315                 // Get frame from queue
1316                 pthread_mutex_lock( &self->queue_mutex );
1317                 while( self->ahead && mlt_deque_count( self->queue ) < size )
1318                         pthread_cond_wait( &self->queue_cond, &self->queue_mutex );
1319                 frame = mlt_deque_pop_front( self->queue );
1320                 pthread_cond_broadcast( &self->queue_cond );
1321                 pthread_mutex_unlock( &self->queue_mutex );
1322         }
1323         else // real_time == 0
1324         {
1325                 // Get the frame in non real time
1326                 frame = mlt_consumer_get_frame( self );
1327
1328                 // This isn't true, but from the consumers perspective it is
1329                 if ( frame != NULL )
1330                         mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 );
1331         }
1332
1333         return frame;
1334 }
1335
1336 /** Callback for the implementation to indicate a stopped condition.
1337  *
1338  * \public \memberof mlt_consumer_s
1339  * \param self a consumer
1340  */
1341
1342 void mlt_consumer_stopped( mlt_consumer self )
1343 {
1344         mlt_properties_set_int( MLT_CONSUMER_PROPERTIES( self ), "running", 0 );
1345         mlt_events_fire( MLT_CONSUMER_PROPERTIES( self ), "consumer-stopped", NULL );
1346         mlt_event_unblock( self->event_listener );
1347 }
1348
1349 /** Stop the consumer.
1350  *
1351  * \public \memberof mlt_consumer_s
1352  * \param self a consumer
1353  * \return true if there was an error
1354  */
1355
1356 int mlt_consumer_stop( mlt_consumer self )
1357 {
1358         // Get the properies
1359         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
1360
1361         // Just in case...
1362         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_DEBUG, "stopping put waiting\n" );
1363         pthread_mutex_lock( &self->put_mutex );
1364         self->put_active = 0;
1365         pthread_cond_broadcast( &self->put_cond );
1366         pthread_mutex_unlock( &self->put_mutex );
1367
1368         // Stop the consumer
1369         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_DEBUG, "stopping consumer\n" );
1370         
1371         // Cancel the read ahead threads
1372         self->ahead = 0;
1373         if ( self->started )
1374         {
1375                 // Unblock the consumer calling mlt_consumer_rt_frame
1376                 pthread_mutex_lock( &self->queue_mutex );
1377                 pthread_cond_broadcast( &self->queue_cond );
1378                 pthread_mutex_unlock( &self->queue_mutex );             
1379         }
1380         
1381         // Invoke the child callback
1382         if ( self->stop != NULL )
1383                 self->stop( self );
1384
1385         // Check if the user has requested real time or not and stop if necessary
1386         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_DEBUG, "stopping read_ahead\n" );
1387         if ( abs( self->real_time ) == 1 )
1388                 consumer_read_ahead_stop( self );
1389         else if ( abs( self->real_time ) > 1 )
1390                 consumer_work_stop( self );
1391
1392         // Kill the test card
1393         mlt_properties_set_data( properties, "test_card_producer", NULL, 0, NULL, NULL );
1394
1395         // Check and run a post command
1396         if ( mlt_properties_get( properties, "post" ) )
1397                 if (system( mlt_properties_get( properties, "post" ) ) == -1 )
1398                         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_ERROR, "system(%s) failed!\n", mlt_properties_get( properties, "post" ) );
1399
1400         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_DEBUG, "stopped\n" );
1401
1402         return 0;
1403 }
1404
1405 /** Determine if the consumer is stopped.
1406  *
1407  * \public \memberof mlt_consumer_s
1408  * \param self a consumer
1409  * \return true if the consumer is stopped
1410  */
1411
1412 int mlt_consumer_is_stopped( mlt_consumer self )
1413 {
1414         // Check if the consumer is stopped
1415         if ( self->is_stopped != NULL )
1416                 return self->is_stopped( self );
1417
1418         return 0;
1419 }
1420
1421 /** Close and destroy the consumer.
1422  *
1423  * \public \memberof mlt_consumer_s
1424  * \param self a consumer
1425  */
1426
1427 void mlt_consumer_close( mlt_consumer self )
1428 {
1429         if ( self != NULL && mlt_properties_dec_ref( MLT_CONSUMER_PROPERTIES( self ) ) <= 0 )
1430         {
1431                 // Get the childs close function
1432                 void ( *consumer_close )( ) = self->close;
1433
1434                 if ( consumer_close )
1435                 {
1436                         // Just in case...
1437                         //mlt_consumer_stop( self );
1438
1439                         self->close = NULL;
1440                         consumer_close( self );
1441                 }
1442                 else
1443                 {
1444                         // Make sure it only gets called once
1445                         self->parent.close = NULL;
1446
1447                         // Destroy the push mutex and condition
1448                         pthread_mutex_destroy( &self->put_mutex );
1449                         pthread_cond_destroy( &self->put_cond );
1450
1451                         mlt_service_close( &self->parent );
1452                 }
1453         }
1454 }
1455
1456 /** Get the position of the last frame shown.
1457  *
1458  * \public \memberof mlt_consumer_s
1459  * \param consumer a consumer
1460  * \return the position
1461  */
1462
1463 mlt_position mlt_consumer_position( mlt_consumer consumer )
1464 {
1465         return consumer->position;
1466 }
1467