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