sdl hacks
[melted] / src / modules / sdl / consumer_sdl.c
1 /*
2 * consumer_sdl.c -- A Simple DirectMedia Layer consumer
3 * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4 * Author: Dan Dennedy <dan@dennedy.org>
5 *
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.
10 *
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.
15 *
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.
19 */
20
21 #include "consumer_sdl.h"
22 #include <framework/mlt_frame.h>
23 #include <framework/mlt_deque.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <pthread.h>
28 #include <SDL/SDL.h>
29 #include <SDL/SDL_syswm.h>
30 #include <sys/timeb.h>
31
32 /** This classes definition.
33 */
34
35 typedef struct consumer_sdl_s *consumer_sdl;
36
37 struct consumer_sdl_s
38 {
39 struct mlt_consumer_s parent;
40 mlt_properties properties;
41 mlt_deque queue;
42 pthread_t thread;
43 int running;
44 uint8_t audio_buffer[ 4096 * 24 ];
45 int audio_avail;
46 pthread_mutex_t audio_mutex;
47 pthread_cond_t audio_cond;
48 int window_width;
49 int window_height;
50 float aspect_ratio;
51 int width;
52 int height;
53 int playing;
54 int sdl_flags;
55 SDL_Surface *sdl_screen;
56 SDL_Overlay *sdl_overlay;
57 uint8_t *buffer;
58 };
59
60 /** Forward references to static functions.
61 */
62
63 static int consumer_start( mlt_consumer parent );
64 static int consumer_stop( mlt_consumer parent );
65 static int consumer_is_stopped( mlt_consumer parent );
66 static void consumer_close( mlt_consumer parent );
67 static void *consumer_thread( void * );
68 static int consumer_get_dimensions( int *width, int *height );
69
70 /** This is what will be called by the factory - anything can be passed in
71 via the argument, but keep it simple.
72 */
73
74 mlt_consumer consumer_sdl_init( char *arg )
75 {
76 // Create the consumer object
77 consumer_sdl this = calloc( sizeof( struct consumer_sdl_s ), 1 );
78
79 // If no malloc'd and consumer init ok
80 if ( this != NULL && mlt_consumer_init( &this->parent, this ) == 0 )
81 {
82 // Create the queue
83 this->queue = mlt_deque_init( );
84
85 // Get the parent consumer object
86 mlt_consumer parent = &this->parent;
87
88 // We have stuff to clean up, so override the close method
89 parent->close = consumer_close;
90
91 // get a handle on properties
92 mlt_service service = mlt_consumer_service( parent );
93 this->properties = mlt_service_properties( service );
94
95 // Set the default volume
96 mlt_properties_set_double( this->properties, "volume", 1.0 );
97
98 // This is the initialisation of the consumer
99 pthread_mutex_init( &this->audio_mutex, NULL );
100 pthread_cond_init( &this->audio_cond, NULL);
101
102 // Default scaler (for now we'll use nearest)
103 mlt_properties_set( this->properties, "rescale", "nearest" );
104
105 // Default progressive true
106 mlt_properties_set_int( this->properties, "progressive", 1 );
107
108 // Get aspect ratio
109 this->aspect_ratio = mlt_properties_get_double( this->properties, "aspect_ratio" );
110
111 // process actual param
112 if ( arg == NULL || sscanf( arg, "%dx%d", &this->width, &this->height ) != 2 )
113 {
114 this->width = mlt_properties_get_int( this->properties, "width" );
115 this->height = mlt_properties_get_int( this->properties, "height" );
116 }
117
118 // Default window size
119 this->window_width = (int)( (float)this->height * this->aspect_ratio ) + 1;
120 this->window_height = this->height;
121
122 // Set the sdl flags
123 this->sdl_flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL | SDL_RESIZABLE;
124
125 // Allow thread to be started/stopped
126 parent->start = consumer_start;
127 parent->stop = consumer_stop;
128 parent->is_stopped = consumer_is_stopped;
129
130 // Return the consumer produced
131 return parent;
132 }
133
134 // malloc or consumer init failed
135 free( this );
136
137 // Indicate failure
138 return NULL;
139 }
140
141 int consumer_start( mlt_consumer parent )
142 {
143 consumer_sdl this = parent->child;
144
145 if ( !this->running )
146 {
147 this->running = 1;
148 pthread_create( &this->thread, NULL, consumer_thread, this );
149 }
150
151 return 0;
152 }
153
154 int consumer_stop( mlt_consumer parent )
155 {
156 // Get the actual object
157 consumer_sdl this = parent->child;
158
159 if ( this->running )
160 {
161 // Kill the thread and clean up
162 this->running = 0;
163
164 pthread_mutex_lock( &this->audio_mutex );
165 pthread_cond_broadcast( &this->audio_cond );
166 pthread_mutex_unlock( &this->audio_mutex );
167
168 pthread_join( this->thread, NULL );
169 }
170
171 return 0;
172 }
173
174 int consumer_is_stopped( mlt_consumer parent )
175 {
176 consumer_sdl this = parent->child;
177 return !this->running;
178 }
179
180 static int sdl_lock_display( )
181 {
182 SDL_Surface *screen = SDL_GetVideoSurface( );
183 return screen != NULL && ( !SDL_MUSTLOCK( screen ) || SDL_LockSurface( screen ) >= 0 );
184 }
185
186 static void sdl_unlock_display( )
187 {
188 SDL_Surface *screen = SDL_GetVideoSurface( );
189 if ( screen != NULL && SDL_MUSTLOCK( screen ) )
190 SDL_UnlockSurface( screen );
191 }
192
193 static void sdl_fill_audio( void *udata, uint8_t *stream, int len )
194 {
195 consumer_sdl this = udata;
196
197 // Get the volume
198 float volume = mlt_properties_get_double( this->properties, "volume" );
199
200 pthread_mutex_lock( &this->audio_mutex );
201
202 // Block until audio received
203 while ( this->running && len > this->audio_avail )
204 pthread_cond_wait( &this->audio_cond, &this->audio_mutex );
205
206 if ( this->audio_avail >= len )
207 {
208 // Place in the audio buffer
209 SDL_MixAudio( stream, this->audio_buffer, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
210
211 // Remove len from the audio available
212 this->audio_avail -= len;
213
214 // Remove the samples
215 memmove( this->audio_buffer, this->audio_buffer + len, this->audio_avail );
216 }
217 else
218 {
219 // Just to be safe, wipe the stream first
220 memset( stream, 0, len );
221
222 // Copy what we have into the stream
223 memcpy( stream, this->audio_buffer, this->audio_avail );
224
225 // Mix the audio
226 SDL_MixAudio( stream, stream, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
227
228 // No audio left
229 this->audio_avail = 0;
230 }
231
232 // We're definitely playing now
233 this->playing = 1;
234
235 pthread_cond_broadcast( &this->audio_cond );
236 pthread_mutex_unlock( &this->audio_mutex );
237 }
238
239 static int consumer_play_audio( consumer_sdl this, mlt_frame frame, int init_audio, int *duration )
240 {
241 // Get the properties of this consumer
242 mlt_properties properties = this->properties;
243 mlt_audio_format afmt = mlt_audio_pcm;
244
245 // Set the preferred params of the test card signal
246 int channels = 2;
247 int frequency = 48000;
248 static int counter = 0;
249 if ( mlt_properties_get_int( properties, "frequency" ) != 0 )
250 frequency = mlt_properties_get_int( properties, "frequency" );
251
252 int samples = mlt_sample_calculator( mlt_properties_get_double( this->properties, "fps" ), frequency, counter++ );
253
254 int16_t *pcm;
255 int bytes;
256
257 mlt_frame_get_audio( frame, &pcm, &afmt, &frequency, &channels, &samples );
258 *duration = ( ( samples * 1000 ) / frequency );
259
260 if ( mlt_properties_get_int( properties, "audio_off" ) )
261 {
262 this->playing = 1;
263 return init_audio;
264 }
265
266 if ( init_audio == 1 )
267 {
268 SDL_AudioSpec request;
269 SDL_AudioSpec got;
270
271 // specify audio format
272 memset( &request, 0, sizeof( SDL_AudioSpec ) );
273 this->playing = 0;
274 request.freq = frequency;
275 request.format = AUDIO_S16;
276 request.channels = channels;
277 request.samples = 2048;
278 request.callback = sdl_fill_audio;
279 request.userdata = (void *)this;
280 if ( SDL_OpenAudio( &request, &got ) != 0 )
281 {
282 fprintf( stderr, "SDL failed to open audio: %s\n", SDL_GetError() );
283 mlt_properties_set_int( properties, "audio_off", 1 );
284 init_audio = 2;
285 }
286 else if ( got.size != 0 )
287 {
288 SDL_PauseAudio( 0 );
289 init_audio = 0;
290 }
291 }
292
293 if ( init_audio == 0 )
294 {
295 bytes = ( samples * channels * 2 );
296 pthread_mutex_lock( &this->audio_mutex );
297 while ( bytes > ( sizeof( this->audio_buffer) - this->audio_avail ) )
298 pthread_cond_wait( &this->audio_cond, &this->audio_mutex );
299 mlt_properties properties = mlt_frame_properties( frame );
300 if ( mlt_properties_get_double( properties, "_speed" ) == 1 )
301 memcpy( &this->audio_buffer[ this->audio_avail ], pcm, bytes );
302 else
303 memset( &this->audio_buffer[ this->audio_avail ], 0, bytes );
304 this->audio_avail += bytes;
305 pthread_cond_broadcast( &this->audio_cond );
306 pthread_mutex_unlock( &this->audio_mutex );
307 }
308 else
309 {
310 this->playing = 1;
311 }
312
313 return init_audio;
314 }
315
316 static int consumer_play_video( consumer_sdl this, mlt_frame frame, int64_t elapsed, int64_t playtime )
317 {
318 int error = 0;
319 // Get the properties of this consumer
320 mlt_properties properties = this->properties;
321
322 mlt_image_format vfmt = mlt_image_yuv422;
323 int width = this->width, height = this->height;
324 uint8_t *image;
325 int changed = 0;
326 struct timeb now;
327 ftime( &now );
328 int64_t start = ( ( int64_t )now.time * 1000 + now.millitm );
329
330 if ( mlt_properties_get_int( properties, "video_off" ) )
331 {
332 mlt_frame_close( frame );
333 return 0;
334 }
335
336 if ( frame != NULL )
337 {
338 // Set playtime
339 mlt_properties_set_position( mlt_frame_properties( frame ), "playtime", playtime );
340 mlt_properties_set_double( mlt_frame_properties( frame ), "consumer_scale", ( double )height / mlt_properties_get_double( properties, "height" ) );
341
342 // Push this frame to the back of the queue
343 mlt_deque_push_back( this->queue, frame );
344 }
345
346 if ( this->playing )
347 {
348 // We might want to use an old frame if the current frame is skipped
349 mlt_frame candidate = NULL;
350 frame = NULL;
351
352 while ( frame == NULL && mlt_deque_count( this->queue ) )
353 {
354 frame = mlt_deque_peek_front( this->queue );
355 playtime = mlt_properties_get_position( mlt_frame_properties( frame ), "playtime" );
356
357 // Check if frame is in the future or past
358 if ( playtime > elapsed + 500 )
359 {
360 // Too far in the future - play it now
361 frame = mlt_deque_pop_front( this->queue );
362 }
363 else if ( playtime > elapsed + 160 )
364 {
365 // Time to squeeze a few more frames in
366 frame = candidate;
367 candidate = NULL;
368 error = 1;
369 break;
370 }
371 else if ( playtime < elapsed )
372 {
373 if ( candidate != NULL )
374 mlt_frame_close( candidate );
375 candidate = mlt_deque_pop_front( this->queue );
376 frame = NULL;
377 }
378 else
379 {
380 // Get the frame at the front of the queue
381 frame = mlt_deque_pop_front( this->queue );
382 }
383 }
384
385 if ( frame == NULL )
386 frame = candidate;
387 else if ( candidate != NULL )
388 mlt_frame_close( candidate );
389 }
390 else
391 {
392 if ( frame != NULL )
393 mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
394 frame = NULL;
395 }
396
397 if ( this->playing && frame != NULL )
398 {
399 // Get the image, width and height
400 mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
401 ftime( &now );
402 elapsed += ( ( int64_t )now.time * 1000 + now.millitm ) - start;
403
404 playtime = mlt_properties_get_position( mlt_frame_properties( frame ), "playtime" );
405 struct timespec slow = { 0, ( playtime - elapsed ) * 1000 };
406 if ( slow.tv_nsec > 50 )
407 nanosleep( &slow, NULL );
408
409 // Handle events
410 if ( this->sdl_screen != NULL )
411 {
412 SDL_Event event;
413
414 changed = consumer_get_dimensions( &this->window_width, &this->window_height );
415
416 while ( SDL_PollEvent( &event ) )
417 {
418 switch( event.type )
419 {
420 case SDL_VIDEORESIZE:
421 this->window_width = event.resize.w;
422 this->window_height = event.resize.h;
423 changed = 1;
424 break;
425 case SDL_KEYDOWN:
426 {
427 mlt_producer producer = mlt_properties_get_data( properties, "transport_producer", NULL );
428 char keyboard[ 2 ] = " ";
429 void (*callback)( mlt_producer, char * ) = mlt_properties_get_data( properties, "transport_callback", NULL );
430 if ( callback != NULL && producer != NULL && event.key.keysym.unicode < 0x80 && event.key.keysym.unicode > 0 )
431 {
432 keyboard[ 0 ] = ( char )event.key.keysym.unicode;
433 callback( producer, keyboard );
434 }
435 }
436 break;
437 }
438 }
439 }
440
441 if ( width != this->width || height != this->height )
442 {
443 this->width = width;
444 this->height = height;
445 changed = 1;
446 }
447
448 if ( this->sdl_screen == NULL || changed )
449 {
450 double aspect_ratio = mlt_frame_get_aspect_ratio( frame );
451 float display_aspect_ratio = (float)width / (float)height;
452 SDL_Rect rect;
453
454 if ( mlt_properties_get_double( properties, "aspect_ratio" ) )
455 aspect_ratio = mlt_properties_get_double( properties, "aspect_ratio" );
456
457 if ( aspect_ratio == 1 )
458 {
459 rect.w = this->window_width;
460 rect.h = this->window_height;
461 }
462 else if ( this->window_width < this->window_height * aspect_ratio )
463 {
464 rect.w = this->window_width;
465 rect.h = this->window_width / aspect_ratio;
466 }
467 else
468 {
469 rect.w = this->window_height * aspect_ratio;
470 rect.h = this->window_height;
471 }
472
473 if ( mlt_properties_get_int( properties, "scale_overlay" ) )
474 {
475 if ( ( float )rect.w * display_aspect_ratio < this->window_width )
476 rect.w = ( int )( ( float )rect.w * display_aspect_ratio );
477 else if ( ( float )rect.h * display_aspect_ratio < this->window_height )
478 rect.h = ( int )( ( float )rect.h * display_aspect_ratio );
479 }
480
481 rect.x = ( this->window_width - rect.w ) / 2;
482 rect.y = ( this->window_height - rect.h ) / 2;
483
484 // Force an overlay recreation
485 if ( this->sdl_overlay != NULL )
486 SDL_FreeYUVOverlay( this->sdl_overlay );
487
488 // open SDL window with video overlay, if possible
489 this->sdl_screen = SDL_SetVideoMode( this->window_width, this->window_height, 0, this->sdl_flags );
490
491 if ( this->sdl_screen != NULL )
492 {
493 SDL_SetClipRect( this->sdl_screen, &rect );
494
495 sdl_lock_display();
496 this->sdl_overlay = SDL_CreateYUVOverlay( this->width - (this->width % 4), this->height- (this->height % 2 ), SDL_YUY2_OVERLAY, this->sdl_screen );
497 sdl_unlock_display();
498 }
499 }
500
501 if ( this->sdl_screen != NULL && this->sdl_overlay != NULL )
502 {
503 this->buffer = this->sdl_overlay->pixels[ 0 ];
504 if ( SDL_LockYUVOverlay( this->sdl_overlay ) >= 0 )
505 {
506 memcpy( this->buffer, image, width * height * 2 );
507 SDL_UnlockYUVOverlay( this->sdl_overlay );
508 SDL_DisplayYUVOverlay( this->sdl_overlay, &this->sdl_screen->clip_rect );
509 }
510 }
511 }
512
513 // Close the frame
514 if ( frame != NULL )
515 mlt_frame_close( frame );
516
517 return error;
518 }
519
520 /** Threaded wrapper for pipe.
521 */
522
523 static void *consumer_thread( void *arg )
524 {
525 // Identify the arg
526 consumer_sdl this = arg;
527
528 // Get the consumer
529 mlt_consumer consumer = &this->parent;
530
531 // internal intialization
532 int init_audio = 1;
533
534 // Obtain time of thread start
535 struct timeb now;
536 int64_t start = 0;
537 int64_t elapsed = 0;
538 int duration = 0;
539 int64_t playtime = 0;
540
541 // Initialise the SDL subsystem
542 if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE ) < 0 )
543 {
544 fprintf( stderr, "Failed to initialize SDL: %s\n", SDL_GetError() );
545 return NULL;
546 }
547
548 // Additional initialisation
549 SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL );
550 SDL_EnableUNICODE( 1 );
551
552 // Loop until told not to
553 while( this->running )
554 {
555 // Get a frame from the attached producer
556 mlt_frame frame = mlt_consumer_get_frame( consumer );
557 mlt_frame video_frame = frame;
558 int done = 0;
559
560 // Ensure that we have a frame
561 while ( !done )
562 {
563 // Play audio
564 if ( sizeof( this->audio_buffer ) - this->audio_avail > 8192 || mlt_deque_count( this->queue ) == 1 )
565 {
566 init_audio = consumer_play_audio( this, frame, init_audio, &duration );
567 done = 1;
568 }
569
570 if ( this->playing )
571 {
572 // Get the current time
573 ftime( &now );
574
575 // Determine elapsed time
576 if ( start == 0 )
577 start = ( int64_t )now.time * 1000 + now.millitm;
578 else
579 elapsed = ( ( int64_t )now.time * 1000 + now.millitm ) - start;
580 }
581
582 if ( consumer_play_video( this, video_frame, elapsed, playtime ) )
583 {
584 if ( !done )
585 {
586 init_audio = consumer_play_audio( this, frame, init_audio, &duration );
587 done = 1;
588 }
589 }
590
591 if ( video_frame != NULL )
592 {
593 video_frame = NULL;
594 playtime += duration;
595 }
596 }
597 }
598
599 // internal cleanup
600 if ( init_audio == 0 )
601 SDL_AudioQuit( );
602 if ( this->sdl_overlay != NULL )
603 SDL_FreeYUVOverlay( this->sdl_overlay );
604 SDL_Quit( );
605
606 while( mlt_deque_count( this->queue ) )
607 mlt_frame_close( mlt_deque_pop_back( this->queue ) );
608
609 this->sdl_screen = NULL;
610 this->sdl_overlay = NULL;
611 this->audio_avail = 0;
612
613 return NULL;
614 }
615
616 static int consumer_get_dimensions( int *width, int *height )
617 {
618 int changed = 0;
619
620 // SDL windows manager structure
621 SDL_SysWMinfo wm;
622
623 // Specify the SDL Version
624 SDL_VERSION( &wm.version );
625
626 // Get the wm structure
627 if ( SDL_GetWMInfo( &wm ) == 1 )
628 {
629 // Check that we have the X11 wm
630 if ( wm.subsystem == SDL_SYSWM_X11 )
631 {
632 // Get the SDL window
633 Window window = wm.info.x11.window;
634
635 // Get the display session
636 Display *display = wm.info.x11.display;
637
638 // Get the window attributes
639 XWindowAttributes attr;
640 XGetWindowAttributes( display, window, &attr );
641
642 // Determine whether window has changed
643 changed = *width != attr.width || *height != attr.height;
644
645 // Return width and height
646 *width = attr.width;
647 *height = attr.height;
648 }
649 }
650
651 return changed;
652 }
653
654 /** Callback to allow override of the close method.
655 */
656
657 static void consumer_close( mlt_consumer parent )
658 {
659 // Get the actual object
660 consumer_sdl this = parent->child;
661
662 // Stop the consumer
663 mlt_consumer_stop( parent );
664
665 // Destroy mutexes
666 pthread_mutex_destroy( &this->audio_mutex );
667 pthread_cond_destroy( &this->audio_cond );
668
669 // Now clean up the rest
670 mlt_consumer_close( parent );
671
672 // Finally clean up this
673 free( this );
674 }
675