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