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