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