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