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