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