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