]> git.sesse.net Git - mlt/blob - src/modules/sdl/consumer_sdl.c
Fix compile error on Windows.
[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                                 vi = SDL_GetVideoInfo();
260                                 self->window_width = vi->current_w;
261                                 self->window_height = vi->current_h;
262                                 self->sdl_flags |= SDL_FULLSCREEN;
263                                 SDL_ShowCursor( SDL_DISABLE );
264                         }
265                         SDL_SetVideoMode( self->window_width, self->window_height, 0, self->sdl_flags );
266                 }
267                 pthread_mutex_unlock( &mlt_sdl_mutex );
268
269                 pthread_create( &self->thread, NULL, consumer_thread, self );
270         }
271
272         return 0;
273 }
274
275 int consumer_stop( mlt_consumer parent )
276 {
277         // Get the actual object
278         consumer_sdl self = parent->child;
279
280         if ( self->joined == 0 )
281         {
282                 // Kill the thread and clean up
283                 self->joined = 1;
284                 self->running = 0;
285 #ifndef WIN32
286                 if ( self->thread )
287 #endif
288                         pthread_join( self->thread, NULL );
289
290                 // internal cleanup
291                 if ( self->sdl_overlay != NULL )
292                         SDL_FreeYUVOverlay( self->sdl_overlay );
293                 self->sdl_overlay = NULL;
294
295                 if ( !mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( parent ), "audio_off" ) )
296                 {
297                         pthread_mutex_lock( &self->audio_mutex );
298                         pthread_cond_broadcast( &self->audio_cond );
299                         pthread_mutex_unlock( &self->audio_mutex );
300                         SDL_QuitSubSystem( SDL_INIT_AUDIO );
301                 }
302
303                 if ( mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( parent ), "sdl_started" ) == 0 )
304                 {
305                         pthread_mutex_lock( &mlt_sdl_mutex );
306                         SDL_Quit( );
307                         pthread_mutex_unlock( &mlt_sdl_mutex );
308                 }
309         }
310
311         return 0;
312 }
313
314 int consumer_is_stopped( mlt_consumer parent )
315 {
316         consumer_sdl self = parent->child;
317         return !self->running;
318 }
319
320 void consumer_purge( mlt_consumer parent )
321 {
322         consumer_sdl self = parent->child;
323         if ( self->running )
324         {
325                 pthread_mutex_lock( &self->video_mutex );
326                 while ( mlt_deque_count( self->queue ) )
327                         mlt_frame_close( mlt_deque_pop_back( self->queue ) );
328                 self->is_purge = 1;
329                 pthread_cond_broadcast( &self->video_cond );
330                 pthread_mutex_unlock( &self->video_mutex );
331         }
332 }
333
334 static int sdl_lock_display( )
335 {
336         pthread_mutex_lock( &mlt_sdl_mutex );
337         SDL_Surface *screen = SDL_GetVideoSurface( );
338         int result = screen != NULL && ( !SDL_MUSTLOCK( screen ) || SDL_LockSurface( screen ) >= 0 );
339         pthread_mutex_unlock( &mlt_sdl_mutex );
340         return result;
341 }
342
343 static void sdl_unlock_display( )
344 {
345         pthread_mutex_lock( &mlt_sdl_mutex );
346         SDL_Surface *screen = SDL_GetVideoSurface( );
347         if ( screen != NULL && SDL_MUSTLOCK( screen ) )
348                 SDL_UnlockSurface( screen );
349         pthread_mutex_unlock( &mlt_sdl_mutex );
350 }
351
352 static void sdl_fill_audio( void *udata, uint8_t *stream, int len )
353 {
354         consumer_sdl self = udata;
355
356         // Get the volume
357         double volume = mlt_properties_get_double( self->properties, "volume" );
358
359         pthread_mutex_lock( &self->audio_mutex );
360
361         // Block until audio received
362         while ( self->running && len > self->audio_avail )
363                 pthread_cond_wait( &self->audio_cond, &self->audio_mutex );
364
365         if ( self->audio_avail >= len )
366         {
367                 // Place in the audio buffer
368                 if ( volume != 1.0 )
369                         SDL_MixAudio( stream, self->audio_buffer, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
370                 else
371                         memcpy( stream, self->audio_buffer, len );
372
373                 // Remove len from the audio available
374                 self->audio_avail -= len;
375
376                 // Remove the samples
377                 memmove( self->audio_buffer, self->audio_buffer + len, self->audio_avail );
378         }
379         else
380         {
381                 // Just to be safe, wipe the stream first
382                 memset( stream, 0, len );
383
384                 // Mix the audio 
385                 SDL_MixAudio( stream, self->audio_buffer, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
386
387                 // No audio left
388                 self->audio_avail = 0;
389         }
390
391         // We're definitely playing now
392         self->playing = 1;
393
394         pthread_cond_broadcast( &self->audio_cond );
395         pthread_mutex_unlock( &self->audio_mutex );
396 }
397
398 static int consumer_play_audio( consumer_sdl self, mlt_frame frame, int init_audio, int *duration )
399 {
400         // Get the properties of self consumer
401         mlt_properties properties = self->properties;
402         mlt_audio_format afmt = mlt_audio_s16;
403
404         // Set the preferred params of the test card signal
405         int channels = mlt_properties_get_int( properties, "channels" );
406         int dest_channels = channels;
407         int frequency = mlt_properties_get_int( properties, "frequency" );
408         static int counter = 0;
409
410         int samples = mlt_sample_calculator( mlt_properties_get_double( self->properties, "fps" ), frequency, counter++ );
411         
412         int16_t *pcm;
413         int bytes;
414
415         mlt_frame_get_audio( frame, (void**) &pcm, &afmt, &frequency, &channels, &samples );
416         *duration = ( ( samples * 1000 ) / frequency );
417         pcm += mlt_properties_get_int( properties, "audio_offset" );
418
419         if ( mlt_properties_get_int( properties, "audio_off" ) )
420         {
421                 self->playing = 1;
422                 init_audio = 1;
423                 return init_audio;
424         }
425
426         if ( init_audio == 1 )
427         {
428                 SDL_AudioSpec request;
429                 SDL_AudioSpec got;
430
431                 int audio_buffer = mlt_properties_get_int( properties, "audio_buffer" );
432
433                 // specify audio format
434                 memset( &request, 0, sizeof( SDL_AudioSpec ) );
435                 self->playing = 0;
436                 request.freq = frequency;
437                 request.format = AUDIO_S16SYS;
438                 request.channels = dest_channels;
439                 request.samples = audio_buffer;
440                 request.callback = sdl_fill_audio;
441                 request.userdata = (void *)self;
442                 if ( SDL_OpenAudio( &request, &got ) != 0 )
443                 {
444                         mlt_log_error( MLT_CONSUMER_SERVICE( self ), "SDL failed to open audio: %s\n", SDL_GetError() );
445                         init_audio = 2;
446                 }
447                 else if ( got.size != 0 )
448                 {
449                         SDL_PauseAudio( 0 );
450                         init_audio = 0;
451                 }
452         }
453
454         if ( init_audio == 0 )
455         {
456                 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
457                 
458                 bytes = samples * dest_channels * sizeof(*pcm);
459                 pthread_mutex_lock( &self->audio_mutex );
460                 while ( self->running && bytes > ( sizeof( self->audio_buffer) - self->audio_avail ) )
461                         pthread_cond_wait( &self->audio_cond, &self->audio_mutex );
462                 if ( self->running )
463                 {
464                         if ( mlt_properties_get_double( properties, "_speed" ) == 1 )
465                         {
466                                 if ( channels == dest_channels )
467                                 {
468                                         memcpy( &self->audio_buffer[ self->audio_avail ], pcm, bytes );
469                                 }
470                                 else
471                                 {
472                                         int16_t *dest = (int16_t*) &self->audio_buffer[ self->audio_avail ];
473                                         int i = samples + 1;
474                                         
475                                         while ( --i )
476                                         {
477                                                 memcpy( dest, pcm, dest_channels * sizeof(*pcm) );
478                                                 pcm += channels;
479                                                 dest += dest_channels;
480                                         }
481                                 }
482                         }
483                         else
484                         {
485                                 memset( &self->audio_buffer[ self->audio_avail ], 0, bytes );
486                         }
487                         self->audio_avail += bytes;
488                 }
489                 pthread_cond_broadcast( &self->audio_cond );
490                 pthread_mutex_unlock( &self->audio_mutex );
491         }
492         else
493         {
494                 self->playing = 1;
495         }
496
497         return init_audio;
498 }
499
500 static int consumer_play_video( consumer_sdl self, mlt_frame frame )
501 {
502         // Get the properties of this consumer
503         mlt_properties properties = self->properties;
504
505         mlt_image_format vfmt = mlt_image_yuv422;
506         int width = self->width, height = self->height;
507         uint8_t *image;
508         int changed = 0;
509
510         int video_off = mlt_properties_get_int( properties, "video_off" );
511         int preview_off = mlt_properties_get_int( properties, "preview_off" );
512         mlt_image_format preview_format = mlt_properties_get_int( properties, "preview_format" );
513         int display_off = video_off | preview_off;
514
515         if ( self->running && display_off == 0 )
516         {
517                 // Get the image, width and height
518                 mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
519                 
520                 void *pool = mlt_cocoa_autorelease_init();
521
522                 // Handle events
523                 if ( SDL_GetVideoSurface() )
524                 {
525                         SDL_Event event;
526         
527                         sdl_lock_display( );
528                         pthread_mutex_lock( &mlt_sdl_mutex );
529                         changed = consumer_get_dimensions( &self->window_width, &self->window_height );
530                         pthread_mutex_unlock( &mlt_sdl_mutex );
531                         sdl_unlock_display( );
532
533                         while ( SDL_PollEvent( &event ) )
534                         {
535                                 mlt_events_fire( self->properties, "consumer-sdl-event", &event, NULL );
536
537                                 switch( event.type )
538                                 {
539                                         case SDL_VIDEORESIZE:
540                                                 self->window_width = event.resize.w;
541                                                 self->window_height = event.resize.h;
542                                                 changed = 1;
543                                                 break;
544                                         case SDL_QUIT:
545                                                 self->running = 0;
546                                                 break;
547                                         case SDL_KEYDOWN:
548                                                 {
549                                                         mlt_producer producer = mlt_properties_get_data( properties, "transport_producer", NULL );
550                                                         char keyboard[ 2 ] = " ";
551                                                         void (*callback)( mlt_producer, char * ) = mlt_properties_get_data( properties, "transport_callback", NULL );
552                                                         if ( callback != NULL && producer != NULL && event.key.keysym.unicode < 0x80 && event.key.keysym.unicode > 0 )
553                                                         {
554                                                                 keyboard[ 0 ] = ( char )event.key.keysym.unicode;
555                                                                 callback( producer, keyboard );
556                                                         }
557                                                 }
558                                                 break;
559                                 }
560                         }
561                 }
562         
563                 sdl_lock_display();
564
565                 if ( width != self->width || height != self->height )
566                 {
567                         if ( self->sdl_overlay != NULL )
568                                 SDL_FreeYUVOverlay( self->sdl_overlay );
569                         self->sdl_overlay = NULL;
570                 }
571
572                 if ( self->running && ( !SDL_GetVideoSurface() || changed ) )
573                 {
574                         // Force an overlay recreation
575                         if ( self->sdl_overlay != NULL )
576                                 SDL_FreeYUVOverlay( self->sdl_overlay );
577                         self->sdl_overlay = NULL;
578
579                         // open SDL window with video overlay, if possible
580                         pthread_mutex_lock( &mlt_sdl_mutex );
581                         SDL_Surface *screen = SDL_SetVideoMode( self->window_width, self->window_height, self->bpp, self->sdl_flags );
582                         if ( consumer_get_dimensions( &self->window_width, &self->window_height ) )
583                                 screen = SDL_SetVideoMode( self->window_width, self->window_height, self->bpp, self->sdl_flags );
584                         pthread_mutex_unlock( &mlt_sdl_mutex );
585
586                         if ( screen )
587                         {
588                                 uint32_t color = mlt_properties_get_int( self->properties, "window_background" );
589                                 SDL_FillRect( screen, NULL, color >> 8 );
590                                 SDL_Flip( screen );
591                         }
592                 }
593
594                 if ( self->running )
595                 {
596                         // Determine window's new display aspect ratio
597                         double this_aspect = ( double )self->window_width / self->window_height;
598
599                         // Get the display aspect ratio
600                         double display_ratio = mlt_properties_get_double( properties, "display_ratio" );
601
602                         // Determine frame's display aspect ratio
603                         double frame_aspect = mlt_frame_get_aspect_ratio( frame ) * width / height;
604
605                         // Store the width and height received
606                         self->width = width;
607                         self->height = height;
608
609                         // If using hardware scaler
610                         if ( mlt_properties_get( properties, "rescale" ) != NULL &&
611                                 !strcmp( mlt_properties_get( properties, "rescale" ), "none" ) )
612                         {
613                                 // Use hardware scaler to normalise display aspect ratio
614                                 self->rect.w = frame_aspect / this_aspect * self->window_width;
615                                 self->rect.h = self->window_height;
616                                 if ( self->rect.w > self->window_width )
617                                 {
618                                         self->rect.w = self->window_width;
619                                         self->rect.h = this_aspect / frame_aspect * self->window_height;
620                                 }
621                         }
622                         // Special case optimisation to negate odd effect of sample aspect ratio
623                         // not corresponding exactly with image resolution.
624                         else if ( (int)( this_aspect * 1000 ) == (int)( display_ratio * 1000 ) ) 
625                         {
626                                 self->rect.w = self->window_width;
627                                 self->rect.h = self->window_height;
628                         }
629                         // Use hardware scaler to normalise sample aspect ratio
630                         else if ( self->window_height * display_ratio > self->window_width )
631                         {
632                                 self->rect.w = self->window_width;
633                                 self->rect.h = self->window_width / display_ratio;
634                         }
635                         else
636                         {
637                                 self->rect.w = self->window_height * display_ratio;
638                                 self->rect.h = self->window_height;
639                         }
640                         
641                         self->rect.x = ( self->window_width - self->rect.w ) / 2;
642                         self->rect.y = ( self->window_height - self->rect.h ) / 2;
643                         self->rect.x -= self->rect.x % 2;
644
645                         mlt_properties_set_int( self->properties, "rect_x", self->rect.x );
646                         mlt_properties_set_int( self->properties, "rect_y", self->rect.y );
647                         mlt_properties_set_int( self->properties, "rect_w", self->rect.w );
648                         mlt_properties_set_int( self->properties, "rect_h", self->rect.h );
649
650                         SDL_SetClipRect( SDL_GetVideoSurface(), &self->rect );
651                 }
652
653                 if ( self->running && SDL_GetVideoSurface() && self->sdl_overlay == NULL )
654                 {
655                         SDL_SetClipRect( SDL_GetVideoSurface(), &self->rect );
656                         self->sdl_overlay = SDL_CreateYUVOverlay( width, height, SDL_YUY2_OVERLAY, SDL_GetVideoSurface() );
657                 }
658
659                 if ( self->running && SDL_GetVideoSurface() && self->sdl_overlay != NULL )
660                 {
661                         self->buffer = self->sdl_overlay->pixels[ 0 ];
662                         if ( SDL_LockYUVOverlay( self->sdl_overlay ) >= 0 )
663                         {
664                                 if ( image != NULL )
665                                         memcpy( self->buffer, image, width * height * 2 );
666                                 SDL_UnlockYUVOverlay( self->sdl_overlay );
667                                 SDL_DisplayYUVOverlay( self->sdl_overlay, &SDL_GetVideoSurface()->clip_rect );
668                         }
669                 }
670
671                 sdl_unlock_display();
672                 mlt_cocoa_autorelease_close( pool );
673                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
674         }
675         else if ( self->running )
676         {
677                 vfmt = preview_format == mlt_image_none ? mlt_image_rgb24a : preview_format;
678                 if ( !video_off )
679                         mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
680                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
681         }
682
683         return 0;
684 }
685
686 static void *video_thread( void *arg )
687 {
688         // Identify the arg
689         consumer_sdl self = arg;
690
691         // Obtain time of thread start
692         struct timeval now;
693         int64_t start = 0;
694         int64_t elapsed = 0;
695         struct timespec tm;
696         mlt_frame next = NULL;
697         mlt_properties properties = NULL;
698         double speed = 0;
699
700         // Get real time flag
701         int real_time = mlt_properties_get_int( self->properties, "real_time" );
702
703         // Get the current time
704         gettimeofday( &now, NULL );
705
706         // Determine start time
707         start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec;
708
709         while ( self->running )
710         {
711                 // Pop the next frame
712                 pthread_mutex_lock( &self->video_mutex );
713                 next = mlt_deque_pop_front( self->queue );
714                 while ( next == NULL && self->running )
715                 {
716                         pthread_cond_wait( &self->video_cond, &self->video_mutex );
717                         next = mlt_deque_pop_front( self->queue );
718                 }
719                 pthread_mutex_unlock( &self->video_mutex );
720
721                 if ( !self->running || next == NULL ) break;
722
723                 // Get the properties
724                 properties =  MLT_FRAME_PROPERTIES( next );
725
726                 // Get the speed of the frame
727                 speed = mlt_properties_get_double( properties, "_speed" );
728
729                 // Get the current time
730                 gettimeofday( &now, NULL );
731
732                 // Get the elapsed time
733                 elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - start;
734
735                 // See if we have to delay the display of the current frame
736                 if ( mlt_properties_get_int( properties, "rendered" ) == 1 && self->running )
737                 {
738                         // Obtain the scheduled playout time
739                         int64_t scheduled = mlt_properties_get_int( properties, "playtime" );
740
741                         // Determine the difference between the elapsed time and the scheduled playout time
742                         int64_t difference = scheduled - elapsed;
743
744                         // Smooth playback a bit
745                         if ( real_time && ( difference > 20000 && speed == 1.0 ) )
746                         {
747                                 tm.tv_sec = difference / 1000000;
748                                 tm.tv_nsec = ( difference % 1000000 ) * 500;
749                                 nanosleep( &tm, NULL );
750                         }
751
752                         // Show current frame if not too old
753                         if ( !real_time || ( difference > -10000 || speed != 1.0 || mlt_deque_count( self->queue ) < 2 ) )
754                                 consumer_play_video( self, next );
755
756                         // If the queue is empty, recalculate start to allow build up again
757                         if ( real_time && ( mlt_deque_count( self->queue ) == 0 && speed == 1.0 ) )
758                         {
759                                 gettimeofday( &now, NULL );
760                                 start = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - scheduled + 20000;
761                         }
762                 }
763                 else
764                 {
765                         static int dropped = 0;
766                         mlt_log_info( MLT_CONSUMER_SERVICE(&self->parent), "dropped video frame %d\n", ++dropped );
767                 }
768
769                 // This frame can now be closed
770                 mlt_frame_close( next );
771                 next = NULL;
772         }
773
774         if ( next != NULL )
775                 mlt_frame_close( next );
776
777         mlt_consumer_stopped( &self->parent );
778
779         return NULL;
780 }
781
782 /** Threaded wrapper for pipe.
783 */
784
785 static void *consumer_thread( void *arg )
786 {
787         // Identify the arg
788         consumer_sdl self = arg;
789
790         // Get the consumer
791         mlt_consumer consumer = &self->parent;
792
793         // Convenience functionality
794         int terminate_on_pause = mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( consumer ), "terminate_on_pause" );
795         int terminated = 0;
796
797         // Video thread
798         pthread_t thread;
799
800         // internal intialization
801         int init_audio = 1;
802         int init_video = 1;
803         mlt_frame frame = NULL;
804         int duration = 0;
805         int64_t playtime = 0;
806         struct timespec tm = { 0, 100000 };
807
808         // Loop until told not to
809         while( self->running )
810         {
811                 // Get a frame from the attached producer
812                 frame = !terminated? mlt_consumer_rt_frame( consumer ) : NULL;
813
814                 // Check for termination
815                 if ( terminate_on_pause && frame )
816                         terminated = mlt_properties_get_double( MLT_FRAME_PROPERTIES( frame ), "_speed" ) == 0.0;
817
818                 // Ensure that we have a frame
819                 if ( frame )
820                 {
821                         // Play audio
822                         init_audio = consumer_play_audio( self, frame, init_audio, &duration );
823
824                         // Determine the start time now
825                         if ( self->playing && init_video )
826                         {
827                                 // Create the video thread
828                                 pthread_create( &thread, NULL, video_thread, self );
829
830                                 // Video doesn't need to be initialised any more
831                                 init_video = 0;
832                         }
833
834                         // Set playtime for this frame
835                         mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "playtime", playtime );
836
837                         while ( self->running && mlt_deque_count( self->queue ) > 15 )
838                                 nanosleep( &tm, NULL );
839
840                         // Push this frame to the back of the queue
841                         pthread_mutex_lock( &self->video_mutex );
842                         if ( self->is_purge )
843                         {
844                                 mlt_frame_close( frame );
845                                 frame = NULL;
846                                 self->is_purge = 0;
847                         }
848                         else
849                         {
850                                 mlt_deque_push_back( self->queue, frame );
851                                 pthread_cond_broadcast( &self->video_cond );
852                         }
853                         pthread_mutex_unlock( &self->video_mutex );
854
855                         // Calculate the next playtime
856                         playtime += ( duration * 1000 );
857                 }
858                 else if ( terminated )
859                 {
860                         if ( init_video || mlt_deque_count( self->queue ) == 0 )
861                                 break;
862                         else
863                                 nanosleep( &tm, NULL );
864                 }
865         }
866
867         self->running = 0;
868         
869         // Unblock sdl_preview
870         if ( mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( consumer ), "put_mode" ) == 1 )
871         {
872                 frame = mlt_consumer_get_frame( consumer );
873                 if ( frame )
874                         mlt_frame_close( frame );
875                 frame = NULL;
876         }
877
878         // Kill the video thread
879         if ( init_video == 0 )
880         {
881                 pthread_mutex_lock( &self->video_mutex );
882                 pthread_cond_broadcast( &self->video_cond );
883                 pthread_mutex_unlock( &self->video_mutex );
884                 pthread_join( thread, NULL );
885         }
886
887         while( mlt_deque_count( self->queue ) )
888                 mlt_frame_close( mlt_deque_pop_back( self->queue ) );
889
890         self->audio_avail = 0;
891
892         return NULL;
893 }
894
895 static int consumer_get_dimensions( int *width, int *height )
896 {
897         int changed = 0;
898
899         // SDL windows manager structure
900         SDL_SysWMinfo wm;
901
902         // Specify the SDL Version
903         SDL_VERSION( &wm.version );
904
905         // Lock the display
906         //sdl_lock_display();
907
908 #ifndef __DARWIN__
909         // Get the wm structure
910         if ( SDL_GetWMInfo( &wm ) == 1 )
911         {
912 #ifndef WIN32
913                 // Check that we have the X11 wm
914                 if ( wm.subsystem == SDL_SYSWM_X11 ) 
915                 {
916                         // Get the SDL window
917                         Window window = wm.info.x11.window;
918
919                         // Get the display session
920                         Display *display = wm.info.x11.display;
921
922                         // Get the window attributes
923                         XWindowAttributes attr;
924                         XGetWindowAttributes( display, window, &attr );
925
926                         // Determine whether window has changed
927                         changed = *width != attr.width || *height != attr.height;
928
929                         // Return width and height
930                         *width = attr.width;
931                         *height = attr.height;
932                 }
933 #endif
934         }
935 #endif
936
937         // Unlock the display
938         //sdl_unlock_display();
939
940         return changed;
941 }
942
943 /** Callback to allow override of the close method.
944 */
945
946 static void consumer_close( mlt_consumer parent )
947 {
948         // Get the actual object
949         consumer_sdl self = parent->child;
950
951         // Stop the consumer
952         ///mlt_consumer_stop( parent );
953
954         // Now clean up the rest
955         mlt_consumer_close( parent );
956
957         // Close the queue
958         mlt_deque_close( self->queue );
959
960         // Destroy mutexes
961         pthread_mutex_destroy( &self->audio_mutex );
962         pthread_cond_destroy( &self->audio_cond );
963                 
964         // Finally clean up this
965         free( self );
966 }