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