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