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