]> git.sesse.net Git - mlt/blob - src/framework/mlt_consumer.c
remove consumer_aspect_ratio property - use profile instead
[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                 // Pass along the interpolation and deinterlace options
585                 // TODO: get rid of consumer_deinterlace and use profile.progressive
586                 mlt_properties_set( frame_properties, "rescale.interp", mlt_properties_get( properties, "rescale" ) );
587                 mlt_properties_set_int( frame_properties, "consumer_deinterlace", mlt_properties_get_int( properties, "progressive" ) | mlt_properties_get_int( properties, "deinterlace" ) );
588                 mlt_properties_set( frame_properties, "deinterlace_method", mlt_properties_get( properties, "deinterlace_method" ) );
589                 mlt_properties_set_int( frame_properties, "consumer_tff", mlt_properties_get_int( properties, "top_field_first" ) );
590         }
591
592         // Return the frame
593         return frame;
594 }
595
596 /** Compute the time difference between now and a time value.
597  *
598  * \private \memberof mlt_consumer_s
599  * \param time1 a time value to be compared against now
600  * \return the difference in microseconds
601  */
602
603 static inline long time_difference( struct timeval *time1 )
604 {
605         struct timeval time2;
606         time2.tv_sec = time1->tv_sec;
607         time2.tv_usec = time1->tv_usec;
608         gettimeofday( time1, NULL );
609         return time1->tv_sec * 1000000 + time1->tv_usec - time2.tv_sec * 1000000 - time2.tv_usec;
610 }
611
612 /** The thread procedure for asynchronously pulling frames through the service
613  * network connected to a consumer.
614  *
615  * \private \memberof mlt_consumer_s
616  * \param arg a consumer
617  */
618
619 static void *consumer_read_ahead_thread( void *arg )
620 {
621         // The argument is the consumer
622         mlt_consumer self = arg;
623
624         // Get the properties of the consumer
625         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
626
627         // Get the width and height
628         int width = mlt_properties_get_int( properties, "width" );
629         int height = mlt_properties_get_int( properties, "height" );
630
631         // See if video is turned off
632         int video_off = mlt_properties_get_int( properties, "video_off" );
633         int preview_off = mlt_properties_get_int( properties, "preview_off" );
634         int preview_format = mlt_properties_get_int( properties, "preview_format" );
635
636         // Get the audio settings
637         mlt_audio_format afmt = mlt_audio_s16;
638         const char *format = mlt_properties_get( properties, "mlt_audio_format" );
639         if ( format )
640         {
641                 if ( !strcmp( format, "none" ) )
642                         afmt = mlt_audio_none;
643                 else if ( !strcmp( format, "s32" ) )
644                         afmt = mlt_audio_s32;
645                 else if ( !strcmp( format, "s32le" ) )
646                         afmt = mlt_audio_s32le;
647                 else if ( !strcmp( format, "float" ) )
648                         afmt = mlt_audio_float;
649                 else if ( !strcmp( format, "f32le" ) )
650                         afmt = mlt_audio_f32le;
651         }
652         int counter = 0;
653         double fps = mlt_properties_get_double( properties, "fps" );
654         int channels = mlt_properties_get_int( properties, "channels" );
655         int frequency = mlt_properties_get_int( properties, "frequency" );
656         int samples = 0;
657         void *audio = NULL;
658
659         // See if audio is turned off
660         int audio_off = mlt_properties_get_int( properties, "audio_off" );
661
662         // Get the maximum size of the buffer
663         int buffer = mlt_properties_get_int( properties, "buffer" ) + 1;
664
665         // General frame variable
666         mlt_frame frame = NULL;
667         uint8_t *image = NULL;
668
669         // Time structures
670         struct timeval ante;
671
672         // Average time for get_frame and get_image
673         int count = 0;
674         int skipped = 0;
675         int64_t time_process = 0;
676         int skip_next = 0;
677         mlt_position pos = 0;
678         mlt_position start_pos = 0;
679         mlt_position last_pos = 0;
680         int frame_duration = mlt_properties_get_int( properties, "frame_duration" );
681         int drop_max = mlt_properties_get_int( properties, "drop_max" );
682
683         if ( preview_off && preview_format != 0 )
684                 self->format = preview_format;
685
686         // Get the first frame
687         frame = mlt_consumer_get_frame( self );
688
689         if ( frame )
690         {
691                 // Get the image of the first frame
692                 if ( !video_off )
693                 {
694                         mlt_events_fire( MLT_CONSUMER_PROPERTIES( self ), "consumer-frame-render", frame, NULL );
695                         mlt_frame_get_image( frame, &image, &self->format, &width, &height, 0 );
696                 }
697
698                 if ( !audio_off )
699                 {
700                         samples = mlt_sample_calculator( fps, frequency, counter++ );
701                         mlt_frame_get_audio( frame, &audio, &afmt, &frequency, &channels, &samples );
702                 }
703
704                 // Mark as rendered
705                 mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 );
706                 last_pos = start_pos = pos = mlt_frame_get_position( frame );
707         }
708
709         // Get the starting time (can ignore the times above)
710         gettimeofday( &ante, NULL );
711
712         // Continue to read ahead
713         while ( self->ahead )
714         {
715                 // Put the current frame into the queue
716                 pthread_mutex_lock( &self->queue_mutex );
717                 while( self->ahead && mlt_deque_count( self->queue ) >= buffer )
718                         pthread_cond_wait( &self->queue_cond, &self->queue_mutex );
719                 mlt_deque_push_back( self->queue, frame );
720                 pthread_cond_broadcast( &self->queue_cond );
721                 pthread_mutex_unlock( &self->queue_mutex );
722
723                 // Get the next frame
724                 frame = mlt_consumer_get_frame( self );
725
726                 // If there's no frame, we're probably stopped...
727                 if ( frame == NULL )
728                         continue;
729                 pos = mlt_frame_get_position( frame );
730
731                 // Increment the counter used for averaging processing cost
732                 count ++;
733
734                 // All non-normal playback frames should be shown
735                 if ( mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "_speed" ) != 1 )
736                 {
737 #ifdef DEINTERLACE_ON_NOT_NORMAL_SPEED
738                         mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "consumer_deinterlace", 1 );
739 #endif
740                         // Indicate seeking or trick-play
741                         start_pos = pos;
742                 }
743
744                 // If skip flag not set or frame-dropping disabled
745                 if ( !skip_next || self->real_time == -1 )
746                 {
747                         if ( !video_off )
748                         {
749                                 // Reset width/height - could have been changed by previous mlt_frame_get_image
750                                 width = mlt_properties_get_int( properties, "width" );
751                                 height = mlt_properties_get_int( properties, "height" );
752
753                                 // Get the image
754                                 mlt_events_fire( MLT_CONSUMER_PROPERTIES( self ), "consumer-frame-render", frame, NULL );
755                                 mlt_frame_get_image( frame, &image, &self->format, &width, &height, 0 );
756                         }
757
758                         // Indicate the rendered image is available.
759                         mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 );
760
761                         // Reset consecutively-skipped counter
762                         skipped = 0;
763                 }
764                 else // Skip image processing
765                 {
766                         // Increment the number of consecutively-skipped frames
767                         skipped++;
768
769                         // If too many (1 sec) consecutively-skipped frames
770                         if ( skipped > drop_max )
771                         {
772                                 // Reset cost tracker
773                                 time_process = 0;
774                                 count = 1;
775                                 mlt_log_verbose( self, "too many frames dropped - forcing next frame\n" );
776                         }
777                 }
778
779                 // Always process audio
780                 if ( !audio_off )
781                 {
782                         samples = mlt_sample_calculator( fps, frequency, counter++ );
783                         mlt_frame_get_audio( frame, &audio, &afmt, &frequency, &channels, &samples );
784                 }
785
786                 // Get the time to process this frame
787                 int64_t time_current = time_difference( &ante );
788
789                 // If the current time is not suddenly some large amount
790                 if ( time_current < time_process / count * 20 || !time_process || count < 5 )
791                 {
792                         // Accumulate the cost for processing this frame
793                         time_process += time_current;
794                 }
795                 else
796                 {
797                         mlt_log_debug( self, "current %"PRId64" threshold %"PRId64" count %d\n",
798                                 time_current, (int64_t) (time_process / count * 20), count );
799                         // Ignore the cost of this frame's time
800                         count--;
801                 }
802
803                 // Determine if we started, resumed, or seeked
804                 if ( pos != last_pos + 1 )
805                         start_pos = pos;
806                 last_pos = pos;
807
808                 // Do not skip the first 20% of buffer at start, resume, or seek
809                 if ( pos - start_pos <= buffer / 5 + 1 )
810                 {
811                         // Reset cost tracker
812                         time_process = 0;
813                         count = 1;
814                 }
815
816                 // Reset skip flag
817                 skip_next = 0;
818
819                 // Only consider skipping if the buffer level is low (or really small)
820                 if ( mlt_deque_count( self->queue ) <= buffer / 5 + 1 )
821                 {
822                         // Skip next frame if average cost exceeds frame duration.
823                         if ( time_process / count > frame_duration )
824                                 skip_next = 1;
825                         if ( skip_next )
826                                 mlt_log_debug( self, "avg usec %"PRId64" (%"PRId64"/%d) duration %d\n",
827                                         time_process/count, time_process, count, frame_duration);
828                 }
829         }
830
831         // Remove the last frame
832         mlt_frame_close( frame );
833
834         return NULL;
835 }
836
837 /** Locate the first unprocessed frame in the queue.
838  *
839  * When playing with realtime behavior, we do not use the true head, but
840  * rather an adjusted process_head. The process_head is adjusted based on
841  * the rate of frame-dropping or recovery from frame-dropping. The idea is
842  * that as the level of frame-dropping increases to move the process_head
843  * closer to the tail because the frames are not completing processing prior
844  * to their playout! Then, as frames are not dropped the process_head moves
845  * back closer to the head of the queue so that worker threads can work 
846  * ahead of the playout point (queue head).
847  *
848  * \private \memberof mlt_consumer_s
849  * \param self a consumer
850  * \return an index into the queue
851  */
852
853 static inline int first_unprocessed_frame( mlt_consumer self )
854 {
855         int index = self->real_time <= 0 ? 0 : self->process_head;
856         while ( index < mlt_deque_count( self->queue ) && MLT_FRAME( mlt_deque_peek( self->queue, index ) )->is_processing )
857                 index++;
858         return index;
859 }
860
861 /** The worker thread procedure for parallel processing frames.
862  *
863  * \private \memberof mlt_consumer_s
864  * \param arg a consumer
865  */
866
867 static void *consumer_worker_thread( void *arg )
868 {
869         // The argument is the consumer
870         mlt_consumer self = arg;
871
872         // Get the properties of the consumer
873         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
874
875         // Get the width and height
876         int width = mlt_properties_get_int( properties, "width" );
877         int height = mlt_properties_get_int( properties, "height" );
878         mlt_image_format format = self->format;
879
880         // See if video is turned off
881         int video_off = mlt_properties_get_int( properties, "video_off" );
882         int preview_off = mlt_properties_get_int( properties, "preview_off" );
883         int preview_format = mlt_properties_get_int( properties, "preview_format" );
884
885         // General frame variable
886         mlt_frame frame = NULL;
887         uint8_t *image = NULL;
888
889         if ( preview_off && preview_format != 0 )
890                 format = preview_format;
891
892         // Continue to read ahead
893         while ( self->ahead )
894         {
895                 // Get the next unprocessed frame from the work queue
896                 pthread_mutex_lock( &self->queue_mutex );
897                 int index = first_unprocessed_frame( self );
898                 while ( self->ahead && index >= mlt_deque_count( self->queue ) )
899                 {
900                         mlt_log_debug( MLT_CONSUMER_SERVICE(self), "waiting in worker index = %d queue count = %d\n",
901                                 index, mlt_deque_count( self->queue ) );
902                         pthread_cond_wait( &self->queue_cond, &self->queue_mutex );
903                         index = first_unprocessed_frame( self );
904                 }
905
906                 // Mark the frame for processing
907                 frame = mlt_deque_peek( self->queue, index );
908                 if ( frame )
909                 {
910                         mlt_log_debug( MLT_CONSUMER_SERVICE(self), "worker processing index = %d frame %d queue count = %d\n",
911                                 index, mlt_frame_get_position(frame), mlt_deque_count( self->queue ) );
912                         frame->is_processing = 1;
913                         mlt_properties_inc_ref( MLT_FRAME_PROPERTIES( frame ) );
914                 }
915                 pthread_mutex_unlock( &self->queue_mutex );
916
917                 // If there's no frame, we're probably stopped...
918                 if ( frame == NULL )
919                         continue;
920
921 #ifdef DEINTERLACE_ON_NOT_NORMAL_SPEED
922                 // All non normal playback frames should be shown
923                 if ( mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "_speed" ) != 1 )
924                         mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "consumer_deinterlace", 1 );
925 #endif
926
927                 // Get the image
928                 if ( !video_off )
929                 {
930                         // Fetch width/height again
931                         width = mlt_properties_get_int( properties, "width" );
932                         height = mlt_properties_get_int( properties, "height" );
933                         mlt_events_fire( MLT_CONSUMER_PROPERTIES( self ), "consumer-frame-render", frame, NULL );
934                         mlt_frame_get_image( frame, &image, &format, &width, &height, 0 );
935                 }
936                 mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 );
937                 mlt_frame_close( frame );
938
939                 // Tell a waiting thread (non-realtime main consumer thread) that we are done.
940                 pthread_mutex_lock( &self->done_mutex );
941                 pthread_cond_broadcast( &self->done_cond );
942                 pthread_mutex_unlock( &self->done_mutex );
943         }
944
945         return NULL;
946 }
947
948 /** Start the read/render thread.
949  *
950  * \private \memberof mlt_consumer_s
951  * \param self a consumer
952  */
953
954 static void consumer_read_ahead_start( mlt_consumer self )
955 {
956         // We're running now
957         self->ahead = 1;
958
959         // Create the frame queue
960         self->queue = mlt_deque_init( );
961
962         // Create the queue mutex
963         pthread_mutex_init( &self->queue_mutex, NULL );
964
965         // Create the condition
966         pthread_cond_init( &self->queue_cond, NULL );
967
968         // Create the read ahead
969         if ( mlt_properties_get( MLT_CONSUMER_PROPERTIES( self ), "priority" ) )
970         {
971                 struct sched_param priority;
972                 priority.sched_priority = mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( self ), "priority" );
973                 pthread_attr_t thread_attributes;
974                 pthread_attr_init( &thread_attributes );
975                 pthread_attr_setschedpolicy( &thread_attributes, SCHED_OTHER );
976                 pthread_attr_setschedparam( &thread_attributes, &priority );
977                 pthread_attr_setinheritsched( &thread_attributes, PTHREAD_EXPLICIT_SCHED );
978                 pthread_attr_setscope( &thread_attributes, PTHREAD_SCOPE_SYSTEM );
979                 if ( pthread_create( &self->ahead_thread, &thread_attributes, consumer_read_ahead_thread, self ) < 0 )
980                         pthread_create( &self->ahead_thread, NULL, consumer_read_ahead_thread, self );
981                 pthread_attr_destroy( &thread_attributes );
982         }
983         else
984         {
985                 pthread_create( &self->ahead_thread, NULL, consumer_read_ahead_thread, self );
986         }
987         self->started = 1;
988 }
989
990 /** Start the worker threads.
991  *
992  * \private \memberof mlt_consumer_s
993  * \param self a consumer
994  */
995
996 static void consumer_work_start( mlt_consumer self )
997 {
998         int n = abs( self->real_time );
999         pthread_t *thread = calloc( 1, sizeof( pthread_t ) * n );
1000
1001         // We're running now
1002         self->ahead = 1;
1003         
1004         // These keep track of the accelleration of frame dropping or recovery.
1005         self->consecutive_dropped = 0;
1006         self->consecutive_rendered = 0;
1007         
1008         // This is the position in the queue from which to look for a frame to process.
1009         // If we always start from the head, then we may likely not complete processing
1010         // before the frame is played out.
1011         self->process_head = 0;
1012
1013         // Create the queues
1014         self->queue = mlt_deque_init();
1015         self->worker_threads = mlt_deque_init();
1016
1017         // Create the mutexes
1018         pthread_mutex_init( &self->queue_mutex, NULL );
1019         pthread_mutex_init( &self->done_mutex, NULL );
1020
1021         // Create the conditions
1022         pthread_cond_init( &self->queue_cond, NULL );
1023         pthread_cond_init( &self->done_cond, NULL );
1024
1025         // Create the read ahead
1026         if ( mlt_properties_get( MLT_CONSUMER_PROPERTIES( self ), "priority" ) )
1027         {
1028
1029                 struct sched_param priority;
1030                 pthread_attr_t thread_attributes;
1031
1032                 priority.sched_priority = mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( self ), "priority" );
1033                 pthread_attr_init( &thread_attributes );
1034                 pthread_attr_setschedpolicy( &thread_attributes, SCHED_OTHER );
1035                 pthread_attr_setschedparam( &thread_attributes, &priority );
1036                 pthread_attr_setinheritsched( &thread_attributes, PTHREAD_EXPLICIT_SCHED );
1037                 pthread_attr_setscope( &thread_attributes, PTHREAD_SCOPE_SYSTEM );
1038
1039                 while ( n-- )
1040                 {
1041                         if ( pthread_create( thread, &thread_attributes, consumer_worker_thread, self ) < 0 )
1042                                 if ( pthread_create( thread, NULL, consumer_worker_thread, self ) == 0 )
1043                                         mlt_deque_push_back( self->worker_threads, thread );
1044                         thread++;
1045                 }
1046                 pthread_attr_destroy( &thread_attributes );
1047         }
1048
1049         else
1050         {
1051                 while ( n-- )
1052                 {
1053                         if ( pthread_create( thread, NULL, consumer_worker_thread, self ) == 0 )
1054                                 mlt_deque_push_back( self->worker_threads, thread );
1055                         thread++;
1056                 }
1057         }
1058         self->started = 1;
1059 }
1060
1061 /** Stop the read/render thread.
1062  *
1063  * \private \memberof mlt_consumer_s
1064  * \param self a consumer
1065  */
1066
1067 static void consumer_read_ahead_stop( mlt_consumer self )
1068 {
1069         // Make sure we're running
1070         if ( self->started )
1071         {
1072                 // Inform thread to stop
1073                 self->ahead = 0;
1074
1075                 // Broadcast to the condition in case it's waiting
1076                 pthread_mutex_lock( &self->queue_mutex );
1077                 pthread_cond_broadcast( &self->queue_cond );
1078                 pthread_mutex_unlock( &self->queue_mutex );
1079
1080                 // Broadcast to the put condition in case it's waiting
1081                 pthread_mutex_lock( &self->put_mutex );
1082                 pthread_cond_broadcast( &self->put_cond );
1083                 pthread_mutex_unlock( &self->put_mutex );
1084
1085                 // Join the thread
1086                 pthread_join( self->ahead_thread, NULL );
1087                 self->started = 0;
1088
1089                 // Destroy the frame queue mutex
1090                 pthread_mutex_destroy( &self->queue_mutex );
1091
1092                 // Destroy the condition
1093                 pthread_cond_destroy( &self->queue_cond );
1094
1095                 // Wipe the queue
1096                 while ( mlt_deque_count( self->queue ) )
1097                         mlt_frame_close( mlt_deque_pop_back( self->queue ) );
1098
1099                 // Close the queue
1100                 mlt_deque_close( self->queue );
1101         }
1102 }
1103
1104 /** Stop the worker threads.
1105  *
1106  * \private \memberof mlt_consumer_s
1107  * \param self a consumer
1108  */
1109
1110 static void consumer_work_stop( mlt_consumer self )
1111 {
1112         // Make sure we're running
1113         if ( self->started )
1114         {
1115                 // Inform thread to stop
1116                 self->ahead = 0;
1117
1118                 // Broadcast to the queue condition in case it's waiting
1119                 pthread_mutex_lock( &self->queue_mutex );
1120                 pthread_cond_broadcast( &self->queue_cond );
1121                 pthread_mutex_unlock( &self->queue_mutex );
1122
1123                 // Broadcast to the put condition in case it's waiting
1124                 pthread_mutex_lock( &self->put_mutex );
1125                 pthread_cond_broadcast( &self->put_cond );
1126                 pthread_mutex_unlock( &self->put_mutex );
1127
1128                 // Broadcast to the done condition in case it's waiting
1129                 pthread_mutex_lock( &self->done_mutex );
1130                 pthread_cond_broadcast( &self->done_cond );
1131                 pthread_mutex_unlock( &self->done_mutex );
1132
1133                 // Join the threads
1134                 pthread_t *thread;
1135                 while ( ( thread = mlt_deque_pop_back( self->worker_threads ) ) )
1136                         pthread_join( *thread, NULL );
1137
1138                 // Deallocate the array of threads
1139                 if ( thread )
1140                         free( thread );
1141
1142                 // Indicate that worker threads no longer running
1143                 self->started = 0;
1144
1145                 // Destroy the mutexes
1146                 pthread_mutex_destroy( &self->queue_mutex );
1147                 pthread_mutex_destroy( &self->done_mutex );
1148
1149                 // Destroy the conditions
1150                 pthread_cond_destroy( &self->queue_cond );
1151                 pthread_cond_destroy( &self->done_cond );
1152
1153                 // Wipe the queues
1154                 while ( mlt_deque_count( self->queue ) )
1155                         mlt_frame_close( mlt_deque_pop_back( self->queue ) );
1156
1157                 // Close the queues
1158                 mlt_deque_close( self->queue );
1159                 mlt_deque_close( self->worker_threads );
1160         }
1161 }
1162
1163 /** Flush the read/render thread's buffer.
1164  *
1165  * \public \memberof mlt_consumer_s
1166  * \param self a consumer
1167  */
1168
1169 void mlt_consumer_purge( mlt_consumer self )
1170 {
1171         if ( self->ahead )
1172         {
1173                 pthread_mutex_lock( &self->queue_mutex );
1174                 while ( mlt_deque_count( self->queue ) )
1175                         mlt_frame_close( mlt_deque_pop_back( self->queue ) );
1176                 pthread_cond_broadcast( &self->queue_cond );
1177                 pthread_mutex_unlock( &self->queue_mutex );
1178         }
1179 }
1180
1181 /** Use multiple worker threads and a work queue.
1182  */
1183
1184 static mlt_frame worker_get_frame( mlt_consumer self, mlt_properties properties )
1185 {
1186         // Frame to return
1187         mlt_frame frame = NULL;
1188
1189         double fps = mlt_properties_get_double( properties, "fps" );
1190         int threads = abs( self->real_time );
1191         int buffer = mlt_properties_get_int( properties, "_buffer" );
1192         buffer = buffer > 0 ? buffer : mlt_properties_get_int( properties, "buffer" );
1193         // This is a heuristic to determine a suitable minimum buffer size for the number of threads.
1194         int headroom = 2 + threads * threads;
1195         buffer = buffer < headroom ? headroom : buffer;
1196
1197         // Start worker threads if not already started.
1198         if ( ! self->ahead )
1199         {
1200                 int prefill = mlt_properties_get_int( properties, "prefill" );
1201                 prefill = prefill > 0 && prefill < buffer ? prefill : buffer;
1202
1203                 consumer_work_start( self );
1204
1205                 // Fill the work queue.
1206                 int i = buffer;
1207                 while ( self->ahead && i-- )
1208                 {
1209                         frame = mlt_consumer_get_frame( self );
1210                         if ( frame )
1211                         {
1212                                 pthread_mutex_lock( &self->queue_mutex );
1213                                 mlt_deque_push_back( self->queue, frame );
1214                                 pthread_cond_signal( &self->queue_cond );
1215                                 pthread_mutex_unlock( &self->queue_mutex );
1216                         }
1217                 }
1218
1219                 // Wait for prefill
1220                 while ( self->ahead && first_unprocessed_frame( self ) < prefill )
1221                 {
1222                         pthread_mutex_lock( &self->done_mutex );
1223                         pthread_cond_wait( &self->done_cond, &self->done_mutex );
1224                         pthread_mutex_unlock( &self->done_mutex );
1225                 }
1226                 self->process_head = threads;
1227         }
1228
1229 //      mlt_log_verbose( MLT_CONSUMER_SERVICE(self), "size %d done count %d work count %d process_head %d\n",
1230 //              threads, first_unprocessed_frame( self ), mlt_deque_count( self->queue ), self->process_head );
1231
1232         // Feed the work queue
1233         while ( self->ahead && mlt_deque_count( self->queue ) < buffer )
1234         {
1235                 frame = mlt_consumer_get_frame( self );
1236                 if ( ! frame )
1237                         return frame;
1238                 pthread_mutex_lock( &self->queue_mutex );
1239                 mlt_deque_push_back( self->queue, frame );
1240                 pthread_cond_signal( &self->queue_cond );
1241                 pthread_mutex_unlock( &self->queue_mutex );
1242         }
1243
1244         // Wait if not realtime.
1245         mlt_frame head_frame = MLT_FRAME( mlt_deque_peek_front( self->queue ) );
1246         while ( self->ahead && self->real_time < 0 &&
1247                 !( head_frame && mlt_properties_get_int( MLT_FRAME_PROPERTIES( head_frame ), "rendered" ) ) )
1248         {
1249                 pthread_mutex_lock( &self->done_mutex );
1250                 pthread_cond_wait( &self->done_cond, &self->done_mutex );
1251                 pthread_mutex_unlock( &self->done_mutex );
1252         }
1253         
1254         // Get the frame from the queue.
1255         pthread_mutex_lock( &self->queue_mutex );
1256         frame = mlt_deque_pop_front( self->queue );
1257         pthread_mutex_unlock( &self->queue_mutex );
1258
1259         // Adapt the worker process head to the runtime conditions.
1260         if ( self->real_time > 0 )
1261         {
1262                 if ( frame && mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "rendered" ) )
1263                 {
1264                         self->consecutive_dropped = 0;
1265                         if ( self->process_head > threads && self->consecutive_rendered >= self->process_head )
1266                                 self->process_head--;
1267                         else
1268                                 self->consecutive_rendered++;
1269                 }
1270                 else
1271                 {
1272                         self->consecutive_rendered = 0;
1273                         if ( self->process_head < buffer - threads && self->consecutive_dropped > threads )
1274                                 self->process_head++;
1275                         else
1276                                 self->consecutive_dropped++;
1277                 }
1278 //              mlt_log_verbose( MLT_CONSUMER_SERVICE(self), "dropped %d rendered %d process_head %d\n",
1279 //                      self->consecutive_dropped, self->consecutive_rendered, self->process_head );
1280
1281                 // Check for too many consecutively dropped frames
1282                 if ( self->consecutive_dropped > mlt_properties_get_int( properties, "drop_max" ) )
1283                 {
1284                         int orig_buffer = mlt_properties_get_int( properties, "buffer" );
1285                         int prefill = mlt_properties_get_int( properties, "prefill" );
1286                         mlt_log_verbose( self, "too many frames dropped - " );
1287
1288                         // If using a default low-latency buffer level (SDL) and below the limit
1289                         if ( ( orig_buffer == 1 || prefill == 1 ) && buffer < (threads + 1) * 10 )
1290                         {
1291                                 // Auto-scale the buffer to compensate
1292                                 mlt_log_verbose( self, "increasing buffer to %d\n", buffer + threads );
1293                                 mlt_properties_set_int( properties, "_buffer", buffer + threads );
1294                                 self->consecutive_dropped = fps / 2;
1295                         }
1296                         else
1297                         {
1298                                 // Tell the consumer to render it
1299                                 mlt_log_verbose( self, "forcing next frame\n" );
1300                                 mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 );
1301                                 self->consecutive_dropped = 0;
1302                         }
1303                 }
1304         }
1305         
1306         return frame;
1307 }
1308
1309 /** Get the next frame from the producer connected to a consumer.
1310  *
1311  * Typically, one uses this instead of \p mlt_consumer_get_frame to make
1312  * the asynchronous/real-time behavior configurable at runtime.
1313  * You should close the frame returned from this when you are done with it.
1314  *
1315  * \public \memberof mlt_consumer_s
1316  * \param self a consumer
1317  * \return a frame
1318  */
1319
1320 mlt_frame mlt_consumer_rt_frame( mlt_consumer self )
1321 {
1322         // Frame to return
1323         mlt_frame frame = NULL;
1324
1325         // Get the properties
1326         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
1327
1328         // Check if the user has requested real time or not
1329         if ( self->real_time > 1 || self->real_time < -1 )
1330         {
1331                 // see above
1332                 return worker_get_frame( self, properties );
1333         }
1334         else if ( self->real_time == 1 || self->real_time == -1 )
1335         {
1336                 int size = 1;
1337
1338                 // Is the read ahead running?
1339                 if ( self->ahead == 0 )
1340                 {
1341                         int buffer = mlt_properties_get_int( properties, "buffer" );
1342                         int prefill = mlt_properties_get_int( properties, "prefill" );
1343                         consumer_read_ahead_start( self );
1344                         if ( buffer > 1 )
1345                                 size = prefill > 0 && prefill < buffer ? prefill : buffer;
1346                 }
1347
1348                 // Get frame from queue
1349                 pthread_mutex_lock( &self->queue_mutex );
1350                 while( self->ahead && mlt_deque_count( self->queue ) < size )
1351                         pthread_cond_wait( &self->queue_cond, &self->queue_mutex );
1352                 frame = mlt_deque_pop_front( self->queue );
1353                 pthread_cond_broadcast( &self->queue_cond );
1354                 pthread_mutex_unlock( &self->queue_mutex );
1355         }
1356         else // real_time == 0
1357         {
1358                 // Get the frame in non real time
1359                 frame = mlt_consumer_get_frame( self );
1360
1361                 // This isn't true, but from the consumers perspective it is
1362                 if ( frame != NULL )
1363                         mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 );
1364         }
1365
1366         return frame;
1367 }
1368
1369 /** Callback for the implementation to indicate a stopped condition.
1370  *
1371  * \public \memberof mlt_consumer_s
1372  * \param self a consumer
1373  */
1374
1375 void mlt_consumer_stopped( mlt_consumer self )
1376 {
1377         mlt_properties_set_int( MLT_CONSUMER_PROPERTIES( self ), "running", 0 );
1378         mlt_events_fire( MLT_CONSUMER_PROPERTIES( self ), "consumer-stopped", NULL );
1379         mlt_event_unblock( self->event_listener );
1380 }
1381
1382 /** Stop the consumer.
1383  *
1384  * \public \memberof mlt_consumer_s
1385  * \param self a consumer
1386  * \return true if there was an error
1387  */
1388
1389 int mlt_consumer_stop( mlt_consumer self )
1390 {
1391         // Get the properies
1392         mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
1393
1394         // Just in case...
1395         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_DEBUG, "stopping put waiting\n" );
1396         pthread_mutex_lock( &self->put_mutex );
1397         self->put_active = 0;
1398         pthread_cond_broadcast( &self->put_cond );
1399         pthread_mutex_unlock( &self->put_mutex );
1400
1401         // Stop the consumer
1402         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_DEBUG, "stopping consumer\n" );
1403         
1404         // Cancel the read ahead threads
1405         self->ahead = 0;
1406         if ( self->started )
1407         {
1408                 // Unblock the consumer calling mlt_consumer_rt_frame
1409                 pthread_mutex_lock( &self->queue_mutex );
1410                 pthread_cond_broadcast( &self->queue_cond );
1411                 pthread_mutex_unlock( &self->queue_mutex );             
1412         }
1413         
1414         // Invoke the child callback
1415         if ( self->stop != NULL )
1416                 self->stop( self );
1417
1418         // Check if the user has requested real time or not and stop if necessary
1419         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_DEBUG, "stopping read_ahead\n" );
1420         if ( abs( self->real_time ) == 1 )
1421                 consumer_read_ahead_stop( self );
1422         else if ( abs( self->real_time ) > 1 )
1423                 consumer_work_stop( self );
1424
1425         // Kill the test card
1426         mlt_properties_set_data( properties, "test_card_producer", NULL, 0, NULL, NULL );
1427
1428         // Check and run a post command
1429         if ( mlt_properties_get( properties, "post" ) )
1430                 if (system( mlt_properties_get( properties, "post" ) ) == -1 )
1431                         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_ERROR, "system(%s) failed!\n", mlt_properties_get( properties, "post" ) );
1432
1433         mlt_log( MLT_CONSUMER_SERVICE( self ), MLT_LOG_DEBUG, "stopped\n" );
1434
1435         return 0;
1436 }
1437
1438 /** Determine if the consumer is stopped.
1439  *
1440  * \public \memberof mlt_consumer_s
1441  * \param self a consumer
1442  * \return true if the consumer is stopped
1443  */
1444
1445 int mlt_consumer_is_stopped( mlt_consumer self )
1446 {
1447         // Check if the consumer is stopped
1448         if ( self->is_stopped != NULL )
1449                 return self->is_stopped( self );
1450
1451         return 0;
1452 }
1453
1454 /** Close and destroy the consumer.
1455  *
1456  * \public \memberof mlt_consumer_s
1457  * \param self a consumer
1458  */
1459
1460 void mlt_consumer_close( mlt_consumer self )
1461 {
1462         if ( self != NULL && mlt_properties_dec_ref( MLT_CONSUMER_PROPERTIES( self ) ) <= 0 )
1463         {
1464                 // Get the childs close function
1465                 void ( *consumer_close )( ) = self->close;
1466
1467                 if ( consumer_close )
1468                 {
1469                         // Just in case...
1470                         //mlt_consumer_stop( self );
1471
1472                         self->close = NULL;
1473                         consumer_close( self );
1474                 }
1475                 else
1476                 {
1477                         // Make sure it only gets called once
1478                         self->parent.close = NULL;
1479
1480                         // Destroy the push mutex and condition
1481                         pthread_mutex_destroy( &self->put_mutex );
1482                         pthread_cond_destroy( &self->put_cond );
1483
1484                         mlt_service_close( &self->parent );
1485                 }
1486         }
1487 }
1488
1489 /** Get the position of the last frame shown.
1490  *
1491  * \public \memberof mlt_consumer_s
1492  * \param consumer a consumer
1493  * \return the position
1494  */
1495
1496 mlt_position mlt_consumer_position( mlt_consumer consumer )
1497 {
1498         return consumer->position;
1499 }
1500