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