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