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