]> git.sesse.net Git - mlt/blob - src/modules/sdl/consumer_sdl.c
35015008c17b9151d1ff1ea0fa3b1ef94f35195a
[mlt] / src / modules / sdl / consumer_sdl.c
1 /*
2  * consumer_sdl.c -- A Simple DirectMedia Layer consumer
3  * Copyright (C) 2003-2004, 2010 Ushodaya Enterprises Limited
4  * Author: Dan Dennedy <dan@dennedy.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include <framework/mlt_consumer.h>
22 #include <framework/mlt_frame.h>
23 #include <framework/mlt_deque.h>
24 #include <framework/mlt_factory.h>
25 #include <framework/mlt_filter.h>
26 #include <framework/mlt_log.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <pthread.h>
31 #include <SDL.h>
32 #include <SDL_syswm.h>
33 #include <sys/time.h>
34 #include "consumer_sdl_osx.h"
35
36 extern pthread_mutex_t mlt_sdl_mutex;
37
38 /** This classes definition.
39 */
40
41 typedef struct consumer_sdl_s *consumer_sdl;
42
43 struct consumer_sdl_s
44 {
45         struct mlt_consumer_s parent;
46         mlt_properties properties;
47         mlt_deque queue;
48         pthread_t thread;
49         int joined;
50         int running;
51         uint8_t audio_buffer[ 4096 * 10 ];
52         int audio_avail;
53         pthread_mutex_t audio_mutex;
54         pthread_cond_t audio_cond;
55         pthread_mutex_t video_mutex;
56         pthread_cond_t video_cond;
57         int window_width;
58         int window_height;
59         int previous_width;
60         int previous_height;
61         int width;
62         int height;
63         int playing;
64         int sdl_flags;
65         SDL_Overlay *sdl_overlay;
66         SDL_Rect rect;
67         uint8_t *buffer;
68         int bpp;
69         int is_purge;
70 };
71
72 /** Forward references to static functions.
73 */
74
75 static int consumer_start( mlt_consumer parent );
76 static int consumer_stop( mlt_consumer parent );
77 static int consumer_is_stopped( mlt_consumer parent );
78 static void consumer_purge( mlt_consumer parent );
79 static void consumer_close( mlt_consumer parent );
80 static void *consumer_thread( void * );
81 static int consumer_get_dimensions( int *width, int *height );
82 static void consumer_sdl_event( mlt_listener listener, mlt_properties owner, mlt_service self, void **args );
83
84 /** This is what will be called by the factory - anything can be passed in
85         via the argument, but keep it simple.
86 */
87
88 mlt_consumer consumer_sdl_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
89 {
90         // Create the consumer object
91         consumer_sdl self = calloc( 1, sizeof( struct consumer_sdl_s ) );
92
93         // If no malloc'd and consumer init ok
94         if ( self != NULL && mlt_consumer_init( &self->parent, self, profile ) == 0 )
95         {
96                 // Create the queue
97                 self->queue = mlt_deque_init( );
98
99                 // Get the parent consumer object
100                 mlt_consumer parent = &self->parent;
101
102                 // We have stuff to clean up, so override the close method
103                 parent->close = consumer_close;
104
105                 // get a handle on properties
106                 mlt_service service = MLT_CONSUMER_SERVICE( parent );
107                 self->properties = MLT_SERVICE_PROPERTIES( service );
108
109                 // Set the default volume
110                 mlt_properties_set_double( self->properties, "volume", 1.0 );
111
112                 // This is the initialisation of the consumer
113                 pthread_mutex_init( &self->audio_mutex, NULL );
114                 pthread_cond_init( &self->audio_cond, NULL);
115                 pthread_mutex_init( &self->video_mutex, NULL );
116                 pthread_cond_init( &self->video_cond, NULL);
117                 
118                 // Default scaler (for now we'll use nearest)
119                 mlt_properties_set( self->properties, "rescale", "nearest" );
120                 mlt_properties_set( self->properties, "deinterlace_method", "onefield" );
121                 mlt_properties_set_int( self->properties, "top_field_first", -1 );
122
123                 // Default buffer for low latency
124                 mlt_properties_set_int( self->properties, "buffer", 1 );
125
126                 // Default audio buffer
127                 mlt_properties_set_int( self->properties, "audio_buffer", 2048 );
128
129                 // Ensure we don't join on a non-running object
130                 self->joined = 1;
131                 
132                 // process actual param
133                 if ( arg && sscanf( arg, "%dx%d", &self->width, &self->height ) )
134                 {
135                         mlt_properties_set_int( self->properties, "_arg_size", 1 );
136                 }
137                 else
138                 {
139                         self->width = mlt_properties_get_int( self->properties, "width" );
140                         self->height = mlt_properties_get_int( self->properties, "height" );
141                 }
142         
143                 // Set the sdl flags
144                 self->sdl_flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL | SDL_DOUBLEBUF;
145 #if !defined(__DARWIN__)
146                 self->sdl_flags |= SDL_RESIZABLE;
147 #endif          
148                 // Allow thread to be started/stopped
149                 parent->start = consumer_start;
150                 parent->stop = consumer_stop;
151                 parent->is_stopped = consumer_is_stopped;
152                 parent->purge = consumer_purge;
153
154                 // Register specific events
155                 mlt_events_register( self->properties, "consumer-sdl-event", ( mlt_transmitter )consumer_sdl_event );
156
157                 // Return the consumer produced
158                 return parent;
159         }
160
161         // malloc or consumer init failed
162         free( self );
163
164         // Indicate failure
165         return NULL;
166 }
167
168 static void consumer_sdl_event( mlt_listener listener, mlt_properties owner, mlt_service self, void **args )
169 {
170         if ( listener != NULL )
171                 listener( owner, self, ( SDL_Event * )args[ 0 ] );
172 }
173
174 int consumer_start( mlt_consumer parent )
175 {
176         consumer_sdl self = parent->child;
177
178         if ( !self->running )
179         {
180                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( parent );
181                 int video_off = mlt_properties_get_int( properties, "video_off" );
182                 int preview_off = mlt_properties_get_int( properties, "preview_off" );
183                 int display_off = video_off | preview_off;
184                 int audio_off = mlt_properties_get_int( properties, "audio_off" );
185                 int sdl_started = mlt_properties_get_int( properties, "sdl_started" );
186                 char *output_display = mlt_properties_get( properties, "output_display" );
187                 char *window_id = mlt_properties_get( properties, "window_id" );
188                 char *audio_driver = mlt_properties_get( properties, "audio_driver" );
189                 char *video_driver = mlt_properties_get( properties, "video_driver" );
190                 char *audio_device = mlt_properties_get( properties, "audio_device" );
191
192                 consumer_stop( parent );
193
194                 self->running = 1;
195                 self->joined = 0;
196
197                 if ( output_display != NULL )
198                         setenv( "DISPLAY", output_display, 1 );
199
200                 if ( window_id != NULL )
201                         setenv( "SDL_WINDOWID", window_id, 1 );
202
203                 if ( video_driver != NULL )
204                         setenv( "SDL_VIDEODRIVER", video_driver, 1 );
205
206                 if ( audio_driver != NULL )
207                         setenv( "SDL_AUDIODRIVER", audio_driver, 1 );
208
209                 if ( audio_device != NULL )
210                         setenv( "AUDIODEV", audio_device, 1 );
211
212                 if ( ! mlt_properties_get_int( self->properties, "_arg_size" ) )
213                 {
214                         if ( mlt_properties_get_int( self->properties, "width" ) > 0 )
215                                 self->width = mlt_properties_get_int( self->properties, "width" );
216                         if ( mlt_properties_get_int( self->properties, "height" ) > 0 )
217                                 self->height = mlt_properties_get_int( self->properties, "height" );
218                 }
219
220                 self->bpp = mlt_properties_get_int( self->properties, "bpp" );
221
222                 if ( sdl_started == 0 && display_off == 0 )
223                 {
224                         pthread_mutex_lock( &mlt_sdl_mutex );
225                         int ret = SDL_Init( SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE );
226                         pthread_mutex_unlock( &mlt_sdl_mutex );
227                         if ( ret < 0 )
228                         {
229                                 mlt_log_error( MLT_CONSUMER_SERVICE(parent), "Failed to initialize SDL: %s\n", SDL_GetError() );
230                                 return -1;
231                         }
232
233                         SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL );
234                         SDL_EnableUNICODE( 1 );
235                 }
236
237                 if ( audio_off == 0 )
238                         SDL_InitSubSystem( SDL_INIT_AUDIO );
239
240                 // Default window size
241                 if ( mlt_properties_get_int( self->properties, "_arg_size" ) )
242                 {
243                         self->window_width = self->width;
244                         self->window_height = self->height;
245                 }
246                 else
247                 {
248                         double display_ratio = mlt_properties_get_double( self->properties, "display_ratio" );
249                         self->window_width = ( double )self->height * display_ratio + 0.5;
250                         self->window_height = self->height;
251                 }
252
253                 pthread_mutex_lock( &mlt_sdl_mutex );
254                 if ( !SDL_GetVideoSurface() && display_off == 0 )
255                 {
256                         if ( mlt_properties_get_int( self->properties, "fullscreen" ) )
257                         {
258                                 const SDL_VideoInfo *vi;
259                                 pthread_mutex_lock( &mlt_sdl_mutex );
260                                 vi = SDL_GetVideoInfo();
261                                 pthread_mutex_unlock( &mlt_sdl_mutex );
262                                 self->window_width = vi->current_w;
263                                 self->window_height = vi->current_h;
264                                 self->sdl_flags |= SDL_FULLSCREEN;
265                                 SDL_ShowCursor( SDL_DISABLE );
266                         }
267                         SDL_SetVideoMode( self->window_width, self->window_height, 0, self->sdl_flags );
268                 }
269                 pthread_mutex_unlock( &mlt_sdl_mutex );
270
271                 pthread_create( &self->thread, NULL, consumer_thread, self );
272         }
273
274         return 0;
275 }
276
277 int consumer_stop( mlt_consumer parent )
278 {
279         // Get the actual object
280         consumer_sdl self = parent->child;
281
282         if ( self->joined == 0 )
283         {
284                 // Kill the thread and clean up
285                 self->joined = 1;
286                 self->running = 0;
287 #ifndef WIN32
288                 if ( self->thread )
289 #endif
290                         pthread_join( self->thread, NULL );
291
292                 // internal cleanup
293                 if ( self->sdl_overlay != NULL )
294                         SDL_FreeYUVOverlay( self->sdl_overlay );
295                 self->sdl_overlay = NULL;
296
297                 if ( !mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( parent ), "audio_off" ) )
298                 {
299                         pthread_mutex_lock( &self->audio_mutex );
300                         pthread_cond_broadcast( &self->audio_cond );
301                         pthread_mutex_unlock( &self->audio_mutex );
302                         SDL_QuitSubSystem( SDL_INIT_AUDIO );
303                 }
304
305                 if ( mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( parent ), "sdl_started" ) == 0 )
306                 {
307                         pthread_mutex_lock( &mlt_sdl_mutex );
308                         SDL_Quit( );
309                         pthread_mutex_unlock( &mlt_sdl_mutex );
310                 }
311         }
312
313         return 0;
314 }
315
316 int consumer_is_stopped( mlt_consumer parent )
317 {
318         consumer_sdl self = parent->child;
319         return !self->running;
320 }
321
322 void consumer_purge( mlt_consumer parent )
323 {
324         consumer_sdl self = parent->child;
325         if ( self->running )
326         {
327                 pthread_mutex_lock( &self->video_mutex );
328                 while ( mlt_deque_count( self->queue ) )
329                         mlt_frame_close( mlt_deque_pop_back( self->queue ) );
330                 self->is_purge = 1;
331                 pthread_cond_broadcast( &self->video_cond );
332                 pthread_mutex_unlock( &self->video_mutex );
333         }
334 }
335
336 static int sdl_lock_display( )
337 {
338         pthread_mutex_lock( &mlt_sdl_mutex );
339         SDL_Surface *screen = SDL_GetVideoSurface( );
340         int result = screen != NULL && ( !SDL_MUSTLOCK( screen ) || SDL_LockSurface( screen ) >= 0 );
341         pthread_mutex_unlock( &mlt_sdl_mutex );
342         return result;
343 }
344
345 static void sdl_unlock_display( )
346 {
347         pthread_mutex_lock( &mlt_sdl_mutex );
348         SDL_Surface *screen = SDL_GetVideoSurface( );
349         if ( screen != NULL && SDL_MUSTLOCK( screen ) )
350                 SDL_UnlockSurface( screen );
351         pthread_mutex_unlock( &mlt_sdl_mutex );
352 }
353
354 static void sdl_fill_audio( void *udata, uint8_t *stream, int len )
355 {
356         consumer_sdl self = udata;
357
358         // Get the volume
359         double volume = mlt_properties_get_double( self->properties, "volume" );
360
361         pthread_mutex_lock( &self->audio_mutex );
362
363         // Block until audio received
364         while ( self->running && len > self->audio_avail )
365                 pthread_cond_wait( &self->audio_cond, &self->audio_mutex );
366
367         if ( self->audio_avail >= len )
368         {
369                 // Place in the audio buffer
370                 if ( volume != 1.0 )
371                         SDL_MixAudio( stream, self->audio_buffer, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
372                 else
373                         memcpy( stream, self->audio_buffer, len );
374
375                 // Remove len from the audio available
376                 self->audio_avail -= len;
377
378                 // Remove the samples
379                 memmove( self->audio_buffer, self->audio_buffer + len, self->audio_avail );
380         }
381         else
382         {
383                 // Just to be safe, wipe the stream first
384                 memset( stream, 0, len );
385
386                 // Mix the audio 
387                 SDL_MixAudio( stream, self->audio_buffer, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
388
389                 // No audio left
390                 self->audio_avail = 0;
391         }
392
393         // We're definitely playing now
394         self->playing = 1;
395
396         pthread_cond_broadcast( &self->audio_cond );
397         pthread_mutex_unlock( &self->audio_mutex );
398 }
399
400 static int consumer_play_audio( consumer_sdl self, mlt_frame frame, int init_audio, int *duration )
401 {
402         // Get the properties of self consumer
403         mlt_properties properties = self->properties;
404         mlt_audio_format afmt = mlt_audio_s16;
405
406         // Set the preferred params of the test card signal
407         int channels = mlt_properties_get_int( properties, "channels" );
408         int dest_channels = channels;
409         int frequency = mlt_properties_get_int( properties, "frequency" );
410         static int counter = 0;
411
412         int samples = mlt_sample_calculator( mlt_properties_get_double( self->properties, "fps" ), frequency, counter++ );
413         
414         int16_t *pcm;
415         int bytes;
416
417         mlt_frame_get_audio( frame, (void**) &pcm, &afmt, &frequency, &channels, &samples );
418         *duration = ( ( samples * 1000 ) / frequency );
419         pcm += mlt_properties_get_int( properties, "audio_offset" );
420
421         if ( mlt_properties_get_int( properties, "audio_off" ) )
422         {
423                 self->playing = 1;
424                 init_audio = 1;
425                 return init_audio;
426         }
427
428         if ( init_audio == 1 )
429         {
430                 SDL_AudioSpec request;
431                 SDL_AudioSpec got;
432
433                 int audio_buffer = mlt_properties_get_int( properties, "audio_buffer" );
434
435                 // specify audio format
436                 memset( &request, 0, sizeof( SDL_AudioSpec ) );
437                 self->playing = 0;
438                 request.freq = frequency;
439                 request.format = AUDIO_S16SYS;
440                 request.channels = dest_channels;
441                 request.samples = audio_buffer;
442                 request.callback = sdl_fill_audio;
443                 request.userdata = (void *)self;
444                 if ( SDL_OpenAudio( &request, &got ) != 0 )
445                 {
446                         mlt_log_error( MLT_CONSUMER_SERVICE( self ), "SDL failed to open audio: %s\n", SDL_GetError() );
447                         init_audio = 2;
448                 }
449                 else if ( got.size != 0 )
450                 {
451                         SDL_PauseAudio( 0 );
452                         init_audio = 0;
453                 }
454         }
455
456         if ( init_audio == 0 )
457         {
458                 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
459                 
460                 bytes = samples * dest_channels * sizeof(*pcm);
461                 pthread_mutex_lock( &self->audio_mutex );
462                 while ( self->running && bytes > ( sizeof( self->audio_buffer) - self->audio_avail ) )
463                         pthread_cond_wait( &self->audio_cond, &self->audio_mutex );
464                 if ( self->running )
465                 {
466                         if ( mlt_properties_get_double( properties, "_speed" ) == 1 )
467                         {
468                                 if ( channels == dest_channels )
469                                 {
470                                         memcpy( &self->audio_buffer[ self->audio_avail ], pcm, bytes );
471                                 }
472                                 else
473                                 {
474                                         int16_t *dest = (int16_t*) &self->audio_buffer[ self->audio_avail ];
475                                         int i = samples + 1;
476                                         
477                                         while ( --i )
478                                         {
479                                                 memcpy( dest, pcm, dest_channels * sizeof(*pcm) );
480                                                 pcm += channels;
481                                                 dest += dest_channels;
482                                         }
483                                 }
484                         }
485                         else
486                         {
487                                 memset( &self->audio_buffer[ self->audio_avail ], 0, bytes );
488                         }
489                         self->audio_avail += bytes;
490                 }
491                 pthread_cond_broadcast( &self->audio_cond );
492                 pthread_mutex_unlock( &self->audio_mutex );
493         }
494         else
495         {
496                 self->playing = 1;
497         }
498
499         return init_audio;
500 }
501
502 static int consumer_play_video( consumer_sdl self, mlt_frame frame )
503 {
504         // Get the properties of this consumer
505         mlt_properties properties = self->properties;
506
507         mlt_image_format vfmt = mlt_image_yuv422;
508         int width = self->width, height = self->height;
509         uint8_t *image;
510         int changed = 0;
511
512         int video_off = mlt_properties_get_int( properties, "video_off" );
513         int preview_off = mlt_properties_get_int( properties, "preview_off" );
514         mlt_image_format preview_format = mlt_properties_get_int( properties, "preview_format" );
515         int display_off = video_off | preview_off;
516
517         if ( self->running && display_off == 0 )
518         {
519                 // Get the image, width and height
520                 mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
521                 
522                 void *pool = mlt_cocoa_autorelease_init();
523
524                 // Handle events
525                 if ( SDL_GetVideoSurface() )
526                 {
527                         SDL_Event event;
528         
529                         sdl_lock_display( );
530                         pthread_mutex_lock( &mlt_sdl_mutex );
531                         changed = consumer_get_dimensions( &self->window_width, &self->window_height );
532                         pthread_mutex_unlock( &mlt_sdl_mutex );
533                         sdl_unlock_display( );
534
535                         while ( SDL_PollEvent( &event ) )
536                         {
537                                 mlt_events_fire( self->properties, "consumer-sdl-event", &event, NULL );
538
539                                 switch( event.type )
540                                 {
541                                         case SDL_VIDEORESIZE:
542                                                 self->window_width = event.resize.w;
543                                                 self->window_height = event.resize.h;
544                                                 changed = 1;
545                                                 break;
546                                         case SDL_QUIT:
547                                                 self->running = 0;
548                                                 break;
549                                         case SDL_KEYDOWN:
550                                                 {
551                                                         mlt_producer producer = mlt_properties_get_data( properties, "transport_producer", NULL );
552                                                         char keyboard[ 2 ] = " ";
553                                                         void (*callback)( mlt_producer, char * ) = mlt_properties_get_data( properties, "transport_callback", NULL );
554                                                         if ( callback != NULL && producer != NULL && event.key.keysym.unicode < 0x80 && event.key.keysym.unicode > 0 )
555                                                         {
556                                                                 keyboard[ 0 ] = ( char )event.key.keysym.unicode;
557                                                                 callback( producer, keyboard );
558                                                         }
559                                                 }
560                                                 break;
561                                 }
562                         }
563                 }
564         
565                 sdl_lock_display();
566
567                 if ( width != self->width || height != self->height )
568                 {
569                         if ( self->sdl_overlay != NULL )
570                                 SDL_FreeYUVOverlay( self->sdl_overlay );
571                         self->sdl_overlay = NULL;
572                 }
573
574                 if ( self->running && ( !SDL_GetVideoSurface() || changed ) )
575                 {
576                         // Force an overlay recreation
577                         if ( self->sdl_overlay != NULL )
578                                 SDL_FreeYUVOverlay( self->sdl_overlay );
579                         self->sdl_overlay = NULL;
580
581                         // open SDL window with video overlay, if possible
582                         pthread_mutex_lock( &mlt_sdl_mutex );
583                         SDL_Surface *screen = SDL_SetVideoMode( self->window_width, self->window_height, self->bpp, self->sdl_flags );
584                         if ( consumer_get_dimensions( &self->window_width, &self->window_height ) )
585                                 screen = SDL_SetVideoMode( self->window_width, self->window_height, self->bpp, self->sdl_flags );
586                         pthread_mutex_unlock( &mlt_sdl_mutex );
587
588                         if ( screen )
589                         {
590                                 uint32_t color = mlt_properties_get_int( self->properties, "window_background" );
591                                 SDL_FillRect( screen, NULL, color >> 8 );
592                                 SDL_Flip( screen );
593                         }
594                 }
595
596                 if ( self->running )
597                 {
598                         // Determine window's new display aspect ratio
599                         double this_aspect = ( double )self->window_width / self->window_height;
600
601                         // Get the display aspect ratio
602                         double display_ratio = mlt_properties_get_double( properties, "display_ratio" );
603
604                         // Determine frame's display aspect ratio
605                         double frame_aspect = mlt_frame_get_aspect_ratio( frame ) * width / height;
606
607                         // Store the width and height received
608                         self->width = width;
609                         self->height = height;
610
611                         // If using hardware scaler
612                         if ( mlt_properties_get( properties, "rescale" ) != NULL &&
613                                 !strcmp( mlt_properties_get( properties, "rescale" ), "none" ) )
614                         {
615                                 // Use hardware scaler to normalise display aspect ratio
616                                 self->rect.w = frame_aspect / this_aspect * self->window_width;
617                                 self->rect.h = self->window_height;
618                                 if ( self->rect.w > self->window_width )
619                                 {
620                                         self->rect.w = self->window_width;
621                                         self->rect.h = this_aspect / frame_aspect * self->window_height;
622                                 }
623                         }
624                         // Special case optimisation to negate odd effect of sample aspect ratio
625                         // not corresponding exactly with image resolution.
626                         else if ( (int)( this_aspect * 1000 ) == (int)( display_ratio * 1000 ) ) 
627                         {
628                                 self->rect.w = self->window_width;
629                                 self->rect.h = self->window_height;
630                         }
631                         // Use hardware scaler to normalise sample aspect ratio
632                         else if ( self->window_height * display_ratio > self->window_width )
633                         {
634                                 self->rect.w = self->window_width;
635                                 self->rect.h = self->window_width / display_ratio;
636                         }
637                         else
638                         {
639                                 self->rect.w = self->window_height * display_ratio;
640                                 self->rect.h = self->window_height;
641                         }
642                         
643                         self->rect.x = ( self->window_width - self->rect.w ) / 2;
644                         self->rect.y = ( self->window_height - self->rect.h ) / 2;
645                         self->rect.x -= self->rect.x % 2;
646
647                         mlt_properties_set_int( self->properties, "rect_x", self->rect.x );
648                         mlt_properties_set_int( self->properties, "rect_y", self->rect.y );
649                         mlt_properties_set_int( self->properties, "rect_w", self->rect.w );
650                         mlt_properties_set_int( self->properties, "rect_h", self->rect.h );
651
652                         SDL_SetClipRect( SDL_GetVideoSurface(), &self->rect );
653                 }
654
655                 if ( self->running && SDL_GetVideoSurface() && self->sdl_overlay == NULL )
656                 {
657                         SDL_SetClipRect( SDL_GetVideoSurface(), &self->rect );
658                         self->sdl_overlay = SDL_CreateYUVOverlay( width, height, SDL_YUY2_OVERLAY, SDL_GetVideoSurface() );
659                 }
660
661                 if ( self->running && SDL_GetVideoSurface() && self->sdl_overlay != NULL )
662                 {
663                         self->buffer = self->sdl_overlay->pixels[ 0 ];
664                         if ( SDL_LockYUVOverlay( self->sdl_overlay ) >= 0 )
665                         {
666                                 if ( image != NULL )
667                                         memcpy( self->buffer, image, width * height * 2 );
668                                 SDL_UnlockYUVOverlay( self->sdl_overlay );
669                                 SDL_DisplayYUVOverlay( self->sdl_overlay, &SDL_GetVideoSurface()->clip_rect );
670                         }
671                 }
672
673                 sdl_unlock_display();
674                 mlt_cocoa_autorelease_close( pool );
675                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
676         }
677         else if ( self->running )
678         {
679                 vfmt = preview_format == mlt_image_none ? mlt_image_rgb24a : preview_format;
680                 if ( !video_off )
681                         mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
682                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
683         }
684
685         return 0;
686 }
687
688 static void *video_thread( void *arg )
689 {
690         // Identify the arg
691         consumer_sdl self = arg;
692
693         // Obtain time of thread start
694         struct timeval now;
695         int64_t start = 0;
696         int64_t elapsed = 0;
697         struct timespec tm;
698         mlt_frame next = NULL;
699         mlt_properties properties = NULL;
700         double speed = 0;
701
702         // Get real time flag
703         int real_time = mlt_properties_get_int( self->properties, "real_time" );
704
705         // Get the current time
706         gettimeofday( &now, NULL );
707
708         // Determine start time
709         start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec;
710
711         while ( self->running )
712         {
713                 // Pop the next frame
714                 pthread_mutex_lock( &self->video_mutex );
715                 next = mlt_deque_pop_front( self->queue );
716                 while ( next == NULL && self->running )
717                 {
718                         pthread_cond_wait( &self->video_cond, &self->video_mutex );
719                         next = mlt_deque_pop_front( self->queue );
720                 }
721                 pthread_mutex_unlock( &self->video_mutex );
722
723                 if ( !self->running || next == NULL ) break;
724
725                 // Get the properties
726                 properties =  MLT_FRAME_PROPERTIES( next );
727
728                 // Get the speed of the frame
729                 speed = mlt_properties_get_double( properties, "_speed" );
730
731                 // Get the current time
732                 gettimeofday( &now, NULL );
733
734                 // Get the elapsed time
735                 elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - start;
736
737                 // See if we have to delay the display of the current frame
738                 if ( mlt_properties_get_int( properties, "rendered" ) == 1 && self->running )
739                 {
740                         // Obtain the scheduled playout time
741                         int64_t scheduled = mlt_properties_get_int( properties, "playtime" );
742
743                         // Determine the difference between the elapsed time and the scheduled playout time
744                         int64_t difference = scheduled - elapsed;
745
746                         // Smooth playback a bit
747                         if ( real_time && ( difference > 20000 && speed == 1.0 ) )
748                         {
749                                 tm.tv_sec = difference / 1000000;
750                                 tm.tv_nsec = ( difference % 1000000 ) * 500;
751                                 nanosleep( &tm, NULL );
752                         }
753
754                         // Show current frame if not too old
755                         if ( !real_time || ( difference > -10000 || speed != 1.0 || mlt_deque_count( self->queue ) < 2 ) )
756                                 consumer_play_video( self, next );
757
758                         // If the queue is empty, recalculate start to allow build up again
759                         if ( real_time && ( mlt_deque_count( self->queue ) == 0 && speed == 1.0 ) )
760                         {
761                                 gettimeofday( &now, NULL );
762                                 start = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - scheduled + 20000;
763                         }
764                 }
765                 else
766                 {
767                         static int dropped = 0;
768                         mlt_log_info( MLT_CONSUMER_SERVICE(&self->parent), "dropped video frame %d\n", ++dropped );
769                 }
770
771                 // This frame can now be closed
772                 mlt_frame_close( next );
773                 next = NULL;
774         }
775
776         if ( next != NULL )
777                 mlt_frame_close( next );
778
779         mlt_consumer_stopped( &self->parent );
780
781         return NULL;
782 }
783
784 /** Threaded wrapper for pipe.
785 */
786
787 static void *consumer_thread( void *arg )
788 {
789         // Identify the arg
790         consumer_sdl self = arg;
791
792         // Get the consumer
793         mlt_consumer consumer = &self->parent;
794
795         // Convenience functionality
796         int terminate_on_pause = mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( consumer ), "terminate_on_pause" );
797         int terminated = 0;
798
799         // Video thread
800         pthread_t thread;
801
802         // internal intialization
803         int init_audio = 1;
804         int init_video = 1;
805         mlt_frame frame = NULL;
806         int duration = 0;
807         int64_t playtime = 0;
808         struct timespec tm = { 0, 100000 };
809
810         // Loop until told not to
811         while( self->running )
812         {
813                 // Get a frame from the attached producer
814                 frame = !terminated? mlt_consumer_rt_frame( consumer ) : NULL;
815
816                 // Check for termination
817                 if ( terminate_on_pause && frame )
818                         terminated = mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0;
819
820                 // Ensure that we have a frame
821                 if ( frame )
822                 {
823                         // Play audio
824                         init_audio = consumer_play_audio( self, frame, init_audio, &duration );
825
826                         // Determine the start time now
827                         if ( self->playing && init_video )
828                         {
829                                 // Create the video thread
830                                 pthread_create( &thread, NULL, video_thread, self );
831
832                                 // Video doesn't need to be initialised any more
833                                 init_video = 0;
834                         }
835
836                         // Set playtime for this frame
837                         mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "playtime", playtime );
838
839                         while ( self->running && mlt_deque_count( self->queue ) > 15 )
840                                 nanosleep( &tm, NULL );
841
842                         // Push this frame to the back of the queue
843                         pthread_mutex_lock( &self->video_mutex );
844                         if ( self->is_purge )
845                         {
846                                 mlt_frame_close( frame );
847                                 frame = NULL;
848                                 self->is_purge = 0;
849                         }
850                         else
851                         {
852                                 mlt_deque_push_back( self->queue, frame );
853                                 pthread_cond_broadcast( &self->video_cond );
854                         }
855                         pthread_mutex_unlock( &self->video_mutex );
856
857                         // Calculate the next playtime
858                         playtime += ( duration * 1000 );
859                 }
860                 else if ( terminated )
861                 {
862                         if ( init_video || mlt_deque_count( self->queue ) == 0 )
863                                 break;
864                         else
865                                 nanosleep( &tm, NULL );
866                 }
867         }
868
869         self->running = 0;
870         
871         // Unblock sdl_preview
872         if ( mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( consumer ), "put_mode" ) == 1 )
873         {
874                 frame = mlt_consumer_get_frame( consumer );
875                 if ( frame )
876                         mlt_frame_close( frame );
877                 frame = NULL;
878         }
879
880         // Kill the video thread
881         if ( init_video == 0 )
882         {
883                 pthread_mutex_lock( &self->video_mutex );
884                 pthread_cond_broadcast( &self->video_cond );
885                 pthread_mutex_unlock( &self->video_mutex );
886                 pthread_join( thread, NULL );
887         }
888
889         while( mlt_deque_count( self->queue ) )
890                 mlt_frame_close( mlt_deque_pop_back( self->queue ) );
891
892         self->audio_avail = 0;
893
894         return NULL;
895 }
896
897 static int consumer_get_dimensions( int *width, int *height )
898 {
899         int changed = 0;
900
901         // SDL windows manager structure
902         SDL_SysWMinfo wm;
903
904         // Specify the SDL Version
905         SDL_VERSION( &wm.version );
906
907         // Lock the display
908         //sdl_lock_display();
909
910 #ifndef __DARWIN__
911         // Get the wm structure
912         if ( SDL_GetWMInfo( &wm ) == 1 )
913         {
914 #ifndef WIN32
915                 // Check that we have the X11 wm
916                 if ( wm.subsystem == SDL_SYSWM_X11 ) 
917                 {
918                         // Get the SDL window
919                         Window window = wm.info.x11.window;
920
921                         // Get the display session
922                         Display *display = wm.info.x11.display;
923
924                         // Get the window attributes
925                         XWindowAttributes attr;
926                         XGetWindowAttributes( display, window, &attr );
927
928                         // Determine whether window has changed
929                         changed = *width != attr.width || *height != attr.height;
930
931                         // Return width and height
932                         *width = attr.width;
933                         *height = attr.height;
934                 }
935 #endif
936         }
937 #endif
938
939         // Unlock the display
940         //sdl_unlock_display();
941
942         return changed;
943 }
944
945 /** Callback to allow override of the close method.
946 */
947
948 static void consumer_close( mlt_consumer parent )
949 {
950         // Get the actual object
951         consumer_sdl self = parent->child;
952
953         // Stop the consumer
954         ///mlt_consumer_stop( parent );
955
956         // Now clean up the rest
957         mlt_consumer_close( parent );
958
959         // Close the queue
960         mlt_deque_close( self->queue );
961
962         // Destroy mutexes
963         pthread_mutex_destroy( &self->audio_mutex );
964         pthread_cond_destroy( &self->audio_cond );
965                 
966         // Finally clean up this
967         free( self );
968 }