2 * consumer_sdl.c -- A Simple DirectMedia Layer consumer
3 * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4 * Author: Dan Dennedy <dan@dennedy.org>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program 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
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 #include "consumer_sdl.h"
22 #include <framework/mlt_frame.h>
23 #include <framework/mlt_deque.h>
29 #include <SDL/SDL_syswm.h>
33 # include "consumer_sdl_osx_hack.h"
34 # import <AppKit/NSApplication.h>
35 # import <Foundation/Foundation.h>
39 /** This classes definition.
42 typedef struct consumer_sdl_s *consumer_sdl;
46 struct mlt_consumer_s parent;
47 mlt_properties properties;
52 uint8_t audio_buffer[ 4096 * 10 ];
54 pthread_mutex_t audio_mutex;
55 pthread_cond_t audio_cond;
56 pthread_mutex_t video_mutex;
57 pthread_cond_t video_cond;
62 double last_frame_aspect;
67 SDL_Surface *sdl_screen;
68 SDL_Overlay *sdl_overlay;
74 /** Forward references to static functions.
77 static int consumer_start( mlt_consumer parent );
78 static int consumer_stop( mlt_consumer parent );
79 static int consumer_is_stopped( mlt_consumer parent );
80 static void consumer_close( mlt_consumer parent );
81 static void *consumer_thread( void * );
82 static int consumer_get_dimensions( int *width, int *height );
83 static void consumer_sdl_event( mlt_listener listener, mlt_properties owner, mlt_service this, void **args );
85 /** This is what will be called by the factory - anything can be passed in
86 via the argument, but keep it simple.
89 mlt_consumer consumer_sdl_init( char *arg )
94 [NSApplication sharedApplication];
96 // Spawn a fake thread so that cocoa knows to be multithreaded
97 DummyThread *dummy = [[DummyThread alloc] init];
98 [NSThread detachNewThreadSelector:@selector(startThread:) toTarget:dummy withObject:nil];
101 // Create the consumer object
102 consumer_sdl this = calloc( sizeof( struct consumer_sdl_s ), 1 );
104 // If no malloc'd and consumer init ok
105 if ( this != NULL && mlt_consumer_init( &this->parent, this ) == 0 )
108 this->queue = mlt_deque_init( );
110 // Get the parent consumer object
111 mlt_consumer parent = &this->parent;
113 // We have stuff to clean up, so override the close method
114 parent->close = consumer_close;
116 // get a handle on properties
117 mlt_service service = MLT_CONSUMER_SERVICE( parent );
118 this->properties = MLT_SERVICE_PROPERTIES( service );
120 // Set the default volume
121 mlt_properties_set_double( this->properties, "volume", 1.0 );
123 // This is the initialisation of the consumer
124 pthread_mutex_init( &this->audio_mutex, NULL );
125 pthread_cond_init( &this->audio_cond, NULL);
126 pthread_mutex_init( &this->video_mutex, NULL );
127 pthread_cond_init( &this->video_cond, NULL);
129 // Default scaler (for now we'll use nearest)
130 mlt_properties_set( this->properties, "rescale", "nearest" );
132 // Default buffer for low latency
133 mlt_properties_set_int( this->properties, "buffer", 1 );
135 // Default progressive true
136 mlt_properties_set_int( this->properties, "progressive", 0 );
138 // Default audio buffer
139 mlt_properties_set_int( this->properties, "audio_buffer", 512 );
141 // Get sample aspect ratio
142 this->aspect_ratio = mlt_properties_get_double( this->properties, "aspect_ratio" );
144 // Ensure we don't join on a non-running object
147 // Default display aspect ratio
148 this->display_aspect = 4.0 / 3.0;
150 // process actual param
151 if ( arg == NULL || sscanf( arg, "%dx%d", &this->width, &this->height ) != 2 )
153 this->width = mlt_properties_get_int( this->properties, "width" );
154 this->height = mlt_properties_get_int( this->properties, "height" );
157 // Default window size
158 this->window_width = ( float )this->height * this->display_aspect;
159 this->window_height = this->height;
162 this->sdl_flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL | SDL_RESIZABLE | SDL_DOUBLEBUF;
164 // Allow thread to be started/stopped
165 parent->start = consumer_start;
166 parent->stop = consumer_stop;
167 parent->is_stopped = consumer_is_stopped;
169 // Register specific events
170 mlt_events_register( this->properties, "consumer-sdl-event", ( mlt_transmitter )consumer_sdl_event );
172 // Return the consumer produced
176 // malloc or consumer init failed
183 static void consumer_sdl_event( mlt_listener listener, mlt_properties owner, mlt_service this, void **args )
185 if ( listener != NULL )
186 listener( owner, this, ( SDL_Event * )args[ 0 ] );
189 int consumer_start( mlt_consumer parent )
191 consumer_sdl this = parent->child;
193 if ( !this->running )
195 consumer_stop( parent );
200 // Allow the user to force resizing to window size
201 if ( mlt_properties_get_int( this->properties, "resize" ) )
203 mlt_properties_set_int( this->properties, "width", this->width );
204 mlt_properties_set_int( this->properties, "height", this->height );
207 pthread_create( &this->thread, NULL, consumer_thread, this );
213 int consumer_stop( mlt_consumer parent )
215 // Get the actual object
216 consumer_sdl this = parent->child;
218 if ( this->joined == 0 )
220 // Kill the thread and clean up
223 pthread_join( this->thread, NULL );
229 int consumer_is_stopped( mlt_consumer parent )
231 consumer_sdl this = parent->child;
232 return !this->running;
235 static int sdl_lock_display( )
237 SDL_Surface *screen = SDL_GetVideoSurface( );
238 return screen != NULL && ( !SDL_MUSTLOCK( screen ) || SDL_LockSurface( screen ) >= 0 );
241 static void sdl_unlock_display( )
243 SDL_Surface *screen = SDL_GetVideoSurface( );
244 if ( screen != NULL && SDL_MUSTLOCK( screen ) )
245 SDL_UnlockSurface( screen );
248 static void sdl_fill_audio( void *udata, uint8_t *stream, int len )
250 consumer_sdl this = udata;
253 float volume = mlt_properties_get_double( this->properties, "volume" );
255 pthread_mutex_lock( &this->audio_mutex );
257 // Block until audio received
258 while ( this->running && len > this->audio_avail )
259 pthread_cond_wait( &this->audio_cond, &this->audio_mutex );
261 if ( this->audio_avail >= len )
263 // Place in the audio buffer
264 memcpy( stream, this->audio_buffer, len );
266 // Remove len from the audio available
267 this->audio_avail -= len;
269 // Remove the samples
270 memmove( this->audio_buffer, this->audio_buffer + len, this->audio_avail );
274 // Just to be safe, wipe the stream first
275 memset( stream, 0, len );
277 // Copy what we have into the stream
278 memcpy( stream, this->audio_buffer, this->audio_avail );
281 SDL_MixAudio( stream, stream, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
284 this->audio_avail = 0;
287 // We're definitely playing now
290 pthread_cond_broadcast( &this->audio_cond );
291 pthread_mutex_unlock( &this->audio_mutex );
294 static int consumer_play_audio( consumer_sdl this, mlt_frame frame, int init_audio, int *duration )
296 // Get the properties of this consumer
297 mlt_properties properties = this->properties;
298 mlt_audio_format afmt = mlt_audio_pcm;
300 // Set the preferred params of the test card signal
301 int channels = mlt_properties_get_int( properties, "channels" );
302 int frequency = mlt_properties_get_int( properties, "frequency" );
303 static int counter = 0;
305 int samples = mlt_sample_calculator( mlt_properties_get_double( this->properties, "fps" ), frequency, counter++ );
310 mlt_frame_get_audio( frame, &pcm, &afmt, &frequency, &channels, &samples );
311 *duration = ( ( samples * 1000 ) / frequency );
313 if ( mlt_properties_get_int( properties, "audio_off" ) )
320 if ( init_audio == 1 )
322 SDL_AudioSpec request;
325 int audio_buffer = mlt_properties_get_int( properties, "audio_buffer" );
327 // specify audio format
328 memset( &request, 0, sizeof( SDL_AudioSpec ) );
330 request.freq = frequency;
331 request.format = AUDIO_S16;
332 request.channels = channels;
333 request.samples = audio_buffer;
334 request.callback = sdl_fill_audio;
335 request.userdata = (void *)this;
336 if ( SDL_OpenAudio( &request, &got ) != 0 )
338 fprintf( stderr, "SDL failed to open audio: %s\n", SDL_GetError() );
341 else if ( got.size != 0 )
348 if ( init_audio == 0 )
350 mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
351 bytes = ( samples * channels * 2 );
352 pthread_mutex_lock( &this->audio_mutex );
353 while ( this->running && bytes > ( sizeof( this->audio_buffer) - this->audio_avail ) )
354 pthread_cond_wait( &this->audio_cond, &this->audio_mutex );
357 if ( mlt_properties_get_double( properties, "_speed" ) == 1 )
358 memcpy( &this->audio_buffer[ this->audio_avail ], pcm, bytes );
360 memset( &this->audio_buffer[ this->audio_avail ], 0, bytes );
361 this->audio_avail += bytes;
363 pthread_cond_broadcast( &this->audio_cond );
364 pthread_mutex_unlock( &this->audio_mutex );
374 static int consumer_play_video( consumer_sdl this, mlt_frame frame )
376 // Get the properties of this consumer
377 mlt_properties properties = this->properties;
379 mlt_image_format vfmt = mlt_image_yuv422;
380 int width = this->width, height = this->height;
384 if ( this->running && mlt_properties_get_int( properties, "video_off" ) == 0 )
386 // Get the image, width and height
387 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
388 mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
391 if ( this->sdl_screen != NULL )
395 changed = consumer_get_dimensions( &this->window_width, &this->window_height );
397 while ( SDL_PollEvent( &event ) )
399 mlt_events_fire( this->properties, "consumer-sdl-event", &event, NULL );
403 case SDL_VIDEORESIZE:
404 this->window_width = event.resize.w;
405 this->window_height = event.resize.h;
413 mlt_producer producer = mlt_properties_get_data( properties, "transport_producer", NULL );
414 char keyboard[ 2 ] = " ";
415 void (*callback)( mlt_producer, char * ) = mlt_properties_get_data( properties, "transport_callback", NULL );
416 if ( callback != NULL && producer != NULL && event.key.keysym.unicode < 0x80 && event.key.keysym.unicode > 0 )
418 keyboard[ 0 ] = ( char )event.key.keysym.unicode;
419 callback( producer, keyboard );
427 if ( width != this->width || height != this->height )
429 if ( this->sdl_overlay != NULL )
430 SDL_FreeYUVOverlay( this->sdl_overlay );
431 this->sdl_overlay = NULL;
434 if ( this->running && ( this->sdl_screen == NULL || changed ) )
436 // Force an overlay recreation
437 if ( this->sdl_overlay != NULL )
438 SDL_FreeYUVOverlay( this->sdl_overlay );
439 this->sdl_overlay = NULL;
441 // open SDL window with video overlay, if possible
443 this->sdl_screen = SDL_SetVideoMode( this->window_width, this->window_height, this->bpp, this->sdl_flags );
444 sdl_unlock_display();
445 if ( consumer_get_dimensions( &this->window_width, &this->window_height ) )
446 this->sdl_screen = SDL_SetVideoMode( this->window_width, this->window_height, this->bpp, this->sdl_flags );
447 //SDL_Flip( this->sdl_screen );
448 mlt_properties_set_int( properties, "changed", 0 );
450 else if ( mlt_properties_get_int( properties, "changed" ) )
453 this->sdl_screen = SDL_SetVideoMode( this->window_width, this->window_height, this->bpp, this->sdl_flags );
454 SDL_SetClipRect( this->sdl_screen, &this->rect );
455 sdl_unlock_display();
456 mlt_properties_set_int( properties, "changed", 0 );
461 // Determine window's new display aspect ratio
462 float this_aspect = ( float )this->window_width / this->window_height;
464 // Determine frame's display aspect ratio
465 float frame_aspect = mlt_frame_get_aspect_ratio( frame ) * width / height;
467 this->height = height;
469 // If using hardware scaler
470 if ( mlt_properties_get( properties, "rescale" ) != NULL &&
471 !strcmp( mlt_properties_get( properties, "rescale" ), "none" ) )
473 // Special case optimisation to negate odd effect of sample aspect ratio
474 // not corresponding exactly with image resolution.
475 if ( ( (int)( this_aspect * 1000 ) == (int)( this->display_aspect * 1000 ) ) &&
476 ( (int)( mlt_frame_get_aspect_ratio( frame ) * 1000 ) == (int)( this->aspect_ratio * 1000 ) ) )
478 this->rect.w = this->window_width;
479 this->rect.h = this->window_height;
483 // Use hardware scaler to normalise display aspect ratio
484 this->rect.w = frame_aspect / this_aspect * this->window_width;
485 this->rect.h = this->window_height;
486 if ( this->rect.w > this->window_width )
488 this->rect.w = this->window_width;
489 this->rect.h = this_aspect / frame_aspect * this->window_height;
493 // Special case optimisation to negate odd effect of sample aspect ratio
494 // not corresponding exactly with image resolution.
495 else if ( (int)( this_aspect * 1000 ) == (int)( this->display_aspect * 1000 ) )
497 this->rect.w = this->window_width;
498 this->rect.h = this->window_height;
500 // Use hardware scaler to normalise sample aspect ratio
501 else if ( this->window_height * this->display_aspect > this->window_width )
503 this->rect.w = this->window_width;
504 this->rect.h = this->window_width / this->display_aspect;
508 this->rect.w = this->window_height * this->display_aspect;
509 this->rect.h = this->window_height;
512 this->rect.x = ( this->window_width - this->rect.w ) / 2;
513 this->rect.y = ( this->window_height - this->rect.h ) / 2;
515 mlt_properties_set_int( this->properties, "rect_x", this->rect.x );
516 mlt_properties_set_int( this->properties, "rect_y", this->rect.y );
517 mlt_properties_set_int( this->properties, "rect_w", this->rect.w );
518 mlt_properties_set_int( this->properties, "rect_h", this->rect.h );
520 SDL_SetClipRect( this->sdl_screen, &this->rect );
523 if ( this->running && this->sdl_screen != NULL && this->sdl_overlay == NULL )
525 SDL_SetClipRect( this->sdl_screen, &this->rect );
526 SDL_Flip( this->sdl_screen );
528 this->sdl_overlay = SDL_CreateYUVOverlay( this->width, this->height, SDL_YUY2_OVERLAY, this->sdl_screen );
529 sdl_unlock_display();
532 if ( this->running && this->sdl_screen != NULL && this->sdl_overlay != NULL )
534 this->buffer = this->sdl_overlay->pixels[ 0 ];
536 if ( SDL_LockYUVOverlay( this->sdl_overlay ) >= 0 )
539 memcpy( this->buffer, image, width * height * 2 );
540 SDL_UnlockYUVOverlay( this->sdl_overlay );
541 SDL_DisplayYUVOverlay( this->sdl_overlay, &this->sdl_screen->clip_rect );
543 sdl_unlock_display();
550 static void *video_thread( void *arg )
553 consumer_sdl this = arg;
556 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
559 // Obtain time of thread start
564 mlt_frame next = NULL;
565 mlt_properties properties = NULL;
568 // Get real time flag
569 int real_time = mlt_properties_get_int( this->properties, "real_time" );
571 // Get the current time
572 gettimeofday( &now, NULL );
574 // Determine start time
575 start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec;
577 while ( this->running )
579 // Pop the next frame
580 pthread_mutex_lock( &this->video_mutex );
581 next = mlt_deque_pop_front( this->queue );
582 while ( next == NULL && this->running )
584 pthread_cond_wait( &this->video_cond, &this->video_mutex );
585 next = mlt_deque_pop_front( this->queue );
587 pthread_mutex_unlock( &this->video_mutex );
589 if ( !this->running || next == NULL ) break;
591 // Get the properties
592 properties = MLT_FRAME_PROPERTIES( next );
594 // Get the speed of the frame
595 speed = mlt_properties_get_double( properties, "_speed" );
597 // Get the current time
598 gettimeofday( &now, NULL );
600 // Get the elapsed time
601 elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - start;
603 // See if we have to delay the display of the current frame
604 if ( mlt_properties_get_int( properties, "rendered" ) == 1 && this->running )
606 // Obtain the scheduled playout time
607 mlt_position scheduled = mlt_properties_get_position( properties, "playtime" );
609 // Determine the difference between the elapsed time and the scheduled playout time
610 mlt_position difference = scheduled - elapsed;
612 // Smooth playback a bit
613 if ( real_time && ( difference > 20000 && speed == 1.0 ) )
615 tm.tv_sec = difference / 1000000;
616 tm.tv_nsec = ( difference % 1000000 ) * 500;
617 nanosleep( &tm, NULL );
620 // Show current frame if not too old
621 if ( !real_time || ( difference > -10000 || speed != 1.0 || mlt_deque_count( this->queue ) < 2 ) )
622 consumer_play_video( this, next );
624 // If the queue is empty, recalculate start to allow build up again
625 if ( real_time && ( mlt_deque_count( this->queue ) == 0 && speed == 1.0 ) )
627 gettimeofday( &now, NULL );
628 start = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec ) - scheduled + 20000;
632 // This frame can now be closed
633 mlt_frame_close( next );
638 mlt_frame_close( next );
640 mlt_consumer_stopped( &this->parent );
649 /** Threaded wrapper for pipe.
652 static void *consumer_thread( void *arg )
655 consumer_sdl this = arg;
658 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
662 mlt_consumer consumer = &this->parent;
667 // internal intialization
670 mlt_frame frame = NULL;
671 mlt_properties properties = NULL;
673 int64_t playtime = 0;
674 struct timespec tm = { 0, 100000 };
676 this->bpp = mlt_properties_get_int( this->properties, "bpp" );
678 if ( mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( consumer ), "sdl_started" ) == 0 )
680 if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE ) < 0 )
682 fprintf( stderr, "Failed to initialize SDL: %s\n", SDL_GetError() );
686 SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL );
687 SDL_EnableUNICODE( 1 );
691 if ( SDL_GetVideoSurface( ) != NULL )
693 this->sdl_screen = SDL_GetVideoSurface( );
694 consumer_get_dimensions( &this->window_width, &this->window_height );
695 mlt_properties_set_int( this->properties, "changed", 0 );
699 if ( !mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( consumer ), "audio_off" ) )
700 SDL_InitSubSystem( SDL_INIT_AUDIO );
702 // Loop until told not to
703 while( this->running )
705 // Get a frame from the attached producer
706 frame = mlt_consumer_rt_frame( consumer );
708 // Ensure that we have a frame
711 // Get the frame properties
712 properties = MLT_FRAME_PROPERTIES( frame );
715 init_audio = consumer_play_audio( this, frame, init_audio, &duration );
717 // Determine the start time now
718 if ( this->playing && init_video )
720 // Create the video thread
721 pthread_create( &thread, NULL, video_thread, this );
723 // Video doesn't need to be initialised any more
727 // Set playtime for this frame
728 mlt_properties_set_position( properties, "playtime", playtime );
730 while ( this->running && mlt_deque_count( this->queue ) > 15 )
731 nanosleep( &tm, NULL );
733 // Push this frame to the back of the queue
734 pthread_mutex_lock( &this->video_mutex );
735 mlt_deque_push_back( this->queue, frame );
736 pthread_cond_broadcast( &this->video_cond );
737 pthread_mutex_unlock( &this->video_mutex );
739 // Calculate the next playtime
740 playtime += ( duration * 1000 );
744 // Kill the video thread
745 if ( init_video == 0 )
747 pthread_mutex_lock( &this->video_mutex );
748 pthread_cond_broadcast( &this->video_cond );
749 pthread_mutex_unlock( &this->video_mutex );
750 pthread_join( thread, NULL );
754 if ( this->sdl_overlay != NULL )
755 SDL_FreeYUVOverlay( this->sdl_overlay );
757 if ( !mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( consumer ), "audio_off" ) )
758 SDL_QuitSubSystem( SDL_INIT_AUDIO );
760 //if ( mlt_properties_get_int( MLT_CONSUMER_PROPERTIES( consumer ), "sdl_started" ) == 0 )
763 while( mlt_deque_count( this->queue ) )
764 mlt_frame_close( mlt_deque_pop_back( this->queue ) );
766 this->sdl_screen = NULL;
767 this->sdl_overlay = NULL;
768 this->audio_avail = 0;
777 static int consumer_get_dimensions( int *width, int *height )
781 // SDL windows manager structure
784 // Specify the SDL Version
785 SDL_VERSION( &wm.version );
791 // Get the wm structure
792 if ( SDL_GetWMInfo( &wm ) == 1 )
794 // Check that we have the X11 wm
795 if ( wm.subsystem == SDL_SYSWM_X11 )
797 // Get the SDL window
798 Window window = wm.info.x11.window;
800 // Get the display session
801 Display *display = wm.info.x11.display;
803 // Get the window attributes
804 XWindowAttributes attr;
805 XGetWindowAttributes( display, window, &attr );
807 // Determine whether window has changed
808 changed = *width != attr.width || *height != attr.height;
810 // Return width and height
812 *height = attr.height;
817 // Unlock the display
823 /** Callback to allow override of the close method.
826 static void consumer_close( mlt_consumer parent )
828 // Get the actual object
829 consumer_sdl this = parent->child;
832 ///mlt_consumer_stop( parent );
834 // Now clean up the rest
835 mlt_consumer_close( parent );
838 mlt_deque_close( this->queue );
841 pthread_mutex_destroy( &this->audio_mutex );
842 pthread_cond_destroy( &this->audio_cond );
844 // Finally clean up this