yet more 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 * 19 ];
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 SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL );
272 SDL_EnableUNICODE( 1 );
273
274 // specify audio format
275 memset( &request, 0, sizeof( SDL_AudioSpec ) );
276 this->playing = 0;
277 request.freq = frequency;
278 request.format = AUDIO_S16;
279 request.channels = channels;
280 request.samples = 2048;
281 request.callback = sdl_fill_audio;
282 request.userdata = (void *)this;
283 if ( SDL_OpenAudio( &request, &got ) != 0 )
284 {
285 fprintf( stderr, "SDL failed to open audio: %s\n", SDL_GetError() );
286 init_audio = 2;
287 }
288 else if ( got.size != 0 )
289 {
290 SDL_PauseAudio( 0 );
291 init_audio = 0;
292 }
293 }
294
295 if ( init_audio == 0 )
296 {
297 bytes = ( samples * channels * 2 );
298 pthread_mutex_lock( &this->audio_mutex );
299 while ( bytes > ( sizeof( this->audio_buffer) - this->audio_avail ) )
300 pthread_cond_wait( &this->audio_cond, &this->audio_mutex );
301 mlt_properties properties = mlt_frame_properties( frame );
302 if ( mlt_properties_get_double( properties, "_speed" ) == 1 )
303 memcpy( &this->audio_buffer[ this->audio_avail ], pcm, bytes );
304 else
305 memset( &this->audio_buffer[ this->audio_avail ], 0, bytes );
306 this->audio_avail += bytes;
307 pthread_cond_broadcast( &this->audio_cond );
308 pthread_mutex_unlock( &this->audio_mutex );
309 }
310 else
311 {
312 this->playing = 1;
313 }
314
315 return init_audio;
316 }
317
318 static int consumer_play_video( consumer_sdl this, mlt_frame frame, int64_t elapsed, int64_t playtime )
319 {
320 // Get the properties of this consumer
321 mlt_properties properties = this->properties;
322
323 mlt_image_format vfmt = mlt_image_yuv422;
324 int width = this->width, height = this->height;
325 uint8_t *image;
326 int changed = 0;
327
328 struct timeb before;
329 ftime( &before );
330
331 if ( mlt_properties_get_int( properties, "video_off" ) )
332 {
333 mlt_frame_close( frame );
334 return 0;
335 }
336
337 // Set skip
338 mlt_properties_set_position( mlt_frame_properties( frame ), "playtime", playtime );
339 mlt_properties_set_double( mlt_frame_properties( frame ), "consumer_scale", ( double )height / mlt_properties_get_double( properties, "height" ) );
340
341 // Push this frame to the back of the queue
342 mlt_deque_push_back( this->queue, frame );
343 frame = NULL;
344
345 if ( this->playing )
346 {
347 // We might want to use an old frame if the current frame is skipped
348 mlt_frame candidate = NULL;
349
350 while ( frame == NULL && mlt_deque_count( this->queue ) )
351 {
352 frame = mlt_deque_peek_front( this->queue );
353 playtime = mlt_properties_get_position( mlt_frame_properties( frame ), "playtime" );
354
355 // Check if frame is in the future or past
356 if ( playtime > elapsed + 60 || mlt_deque_count( this->queue ) < 12 )
357 {
358 // no frame to show or remove
359 frame = NULL;
360 break;
361 }
362 else if ( playtime < elapsed - 20 )
363 {
364 if ( candidate != NULL )
365 mlt_frame_close( candidate );
366 candidate = mlt_deque_pop_front( this->queue );
367 frame = NULL;
368 }
369 else
370 {
371 // Get the frame at the front of the queue
372 frame = mlt_deque_pop_front( this->queue );
373 }
374 }
375
376 if ( frame == NULL )
377 frame = candidate;
378 else if ( candidate != NULL )
379 mlt_frame_close( candidate );
380 }
381
382 if ( this->playing && frame != NULL )
383 {
384 //struct timeb after;
385
386 // Get the image, width and height
387 mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
388
389 //ftime( &after );
390 //fprintf( stderr, "showing %lld at %lld\n", playtime, elapsed );
391 //elapsed += ( ( int64_t )after.time * 1000 + after.millitm ) - ( ( int64_t )before.time * 1000 + before.millitm );
392
393 //playtime = mlt_properties_get_position( mlt_frame_properties( frame ), "playtime" );
394 //struct timespec slow = { 0, ( playtime - elapsed ) * 500 };
395 //if ( slow.tv_nsec > 20000 )
396 //nanosleep( &slow, NULL );
397
398
399 // Handle events
400 if ( this->sdl_screen != NULL )
401 {
402 SDL_Event event;
403
404 changed = consumer_get_dimensions( &this->window_width, &this->window_height );
405
406 while ( SDL_PollEvent( &event ) )
407 {
408 switch( event.type )
409 {
410 case SDL_VIDEORESIZE:
411 this->window_width = event.resize.w;
412 this->window_height = event.resize.h;
413 changed = 1;
414 break;
415 case SDL_KEYDOWN:
416 {
417 mlt_producer producer = mlt_properties_get_data( properties, "transport_producer", NULL );
418 char keyboard[ 2 ] = " ";
419 void (*callback)( mlt_producer, char * ) = mlt_properties_get_data( properties, "transport_callback", NULL );
420 if ( callback != NULL && producer != NULL && event.key.keysym.unicode < 0x80 && event.key.keysym.unicode > 0 )
421 {
422 keyboard[ 0 ] = ( char )event.key.keysym.unicode;
423 callback( producer, keyboard );
424 }
425 }
426 break;
427 }
428 }
429 }
430
431 if ( width != this->width || height != this->height )
432 {
433 this->width = width;
434 this->height = height;
435 changed = 1;
436 }
437
438 if ( this->sdl_screen == NULL || changed )
439 {
440 double aspect_ratio = mlt_frame_get_aspect_ratio( frame );
441 float display_aspect_ratio = (float)width / (float)height;
442 SDL_Rect rect;
443
444 if ( mlt_properties_get_double( properties, "aspect_ratio" ) )
445 aspect_ratio = mlt_properties_get_double( properties, "aspect_ratio" );
446
447 if ( aspect_ratio == 1 )
448 {
449 rect.w = this->window_width;
450 rect.h = this->window_height;
451 }
452 else if ( this->window_width < this->window_height * aspect_ratio )
453 {
454 rect.w = this->window_width;
455 rect.h = this->window_width / aspect_ratio;
456 }
457 else
458 {
459 rect.w = this->window_height * aspect_ratio;
460 rect.h = this->window_height;
461 }
462
463 if ( mlt_properties_get_int( properties, "scale_overlay" ) )
464 {
465 if ( ( float )rect.w * display_aspect_ratio < this->window_width )
466 rect.w = ( int )( ( float )rect.w * display_aspect_ratio );
467 else if ( ( float )rect.h * display_aspect_ratio < this->window_height )
468 rect.h = ( int )( ( float )rect.h * display_aspect_ratio );
469 }
470
471 rect.x = ( this->window_width - rect.w ) / 2;
472 rect.y = ( this->window_height - rect.h ) / 2;
473
474 // Force an overlay recreation
475 if ( this->sdl_overlay != NULL )
476 SDL_FreeYUVOverlay( this->sdl_overlay );
477
478 // open SDL window with video overlay, if possible
479 this->sdl_screen = SDL_SetVideoMode( this->window_width, this->window_height, 0, this->sdl_flags );
480
481 if ( this->sdl_screen != NULL )
482 {
483 SDL_SetClipRect( this->sdl_screen, &rect );
484
485 sdl_lock_display();
486 this->sdl_overlay = SDL_CreateYUVOverlay( this->width - (this->width % 4), this->height- (this->height % 2 ), SDL_YUY2_OVERLAY, this->sdl_screen );
487 sdl_unlock_display();
488 }
489 }
490
491 if ( this->sdl_screen != NULL && this->sdl_overlay != NULL )
492 {
493 this->buffer = this->sdl_overlay->pixels[ 0 ];
494 if ( SDL_LockYUVOverlay( this->sdl_overlay ) >= 0 )
495 {
496 memcpy( this->buffer, image, width * height * 2 );
497 SDL_UnlockYUVOverlay( this->sdl_overlay );
498 SDL_DisplayYUVOverlay( this->sdl_overlay, &this->sdl_screen->clip_rect );
499 }
500 }
501 }
502
503 // Close the frame
504 if ( frame != NULL )
505 mlt_frame_close( frame );
506
507 return 0;
508 }
509
510 /** Threaded wrapper for pipe.
511 */
512
513 static void *consumer_thread( void *arg )
514 {
515 // Identify the arg
516 consumer_sdl this = arg;
517
518 // Get the consumer
519 mlt_consumer consumer = &this->parent;
520
521 // internal intialization
522 int init_audio = 1;
523
524 // Obtain time of thread start
525 struct timeb now;
526 int64_t start = 0;
527 int64_t elapsed = 0;
528 int duration = 0;
529 int64_t playtime = 0;
530
531 if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE ) < 0 )
532 {
533 fprintf( stderr, "Failed to initialize SDL: %s\n", SDL_GetError() );
534 return NULL;
535 }
536
537 // Loop until told not to
538 while( this->running )
539 {
540 // Get a frame from the attached producer
541 mlt_frame frame = mlt_consumer_get_frame( consumer );
542
543 // Ensure that we have a frame
544 if ( frame != NULL )
545 {
546 // Play audio
547 init_audio = consumer_play_audio( this, frame, init_audio, &duration );
548
549 if ( this->playing )
550 {
551 // Get the current time
552 ftime( &now );
553
554 // Determine elapsed time
555 if ( start == 0 )
556 start = ( int64_t )now.time * 1000 + now.millitm;
557 else
558 elapsed = ( ( int64_t )now.time * 1000 + now.millitm ) - start;
559 }
560
561 consumer_play_video( this, frame, elapsed, playtime );
562
563 playtime += duration;
564 }
565 }
566
567 // internal cleanup
568 if ( init_audio == 0 )
569 SDL_AudioQuit( );
570 if ( this->sdl_overlay != NULL )
571 SDL_FreeYUVOverlay( this->sdl_overlay );
572 SDL_Quit( );
573
574 while( mlt_deque_count( this->queue ) )
575 mlt_frame_close( mlt_deque_pop_back( this->queue ) );
576
577 this->sdl_screen = NULL;
578 this->sdl_overlay = NULL;
579 this->audio_avail = 0;
580
581 return NULL;
582 }
583
584 static int consumer_get_dimensions( int *width, int *height )
585 {
586 int changed = 0;
587
588 // SDL windows manager structure
589 SDL_SysWMinfo wm;
590
591 // Specify the SDL Version
592 SDL_VERSION( &wm.version );
593
594 // Get the wm structure
595 if ( SDL_GetWMInfo( &wm ) == 1 )
596 {
597 // Check that we have the X11 wm
598 if ( wm.subsystem == SDL_SYSWM_X11 )
599 {
600 // Get the SDL window
601 Window window = wm.info.x11.window;
602
603 // Get the display session
604 Display *display = wm.info.x11.display;
605
606 // Get the window attributes
607 XWindowAttributes attr;
608 XGetWindowAttributes( display, window, &attr );
609
610 // Determine whether window has changed
611 changed = *width != attr.width || *height != attr.height;
612
613 // Return width and height
614 *width = attr.width;
615 *height = attr.height;
616 }
617 }
618
619 return changed;
620 }
621
622 /** Callback to allow override of the close method.
623 */
624
625 static void consumer_close( mlt_consumer parent )
626 {
627 // Get the actual object
628 consumer_sdl this = parent->child;
629
630 // Stop the consumer
631 mlt_consumer_stop( parent );
632
633 // Destroy mutexes
634 pthread_mutex_destroy( &this->audio_mutex );
635 pthread_cond_destroy( &this->audio_cond );
636
637 // Now clean up the rest
638 mlt_consumer_close( parent );
639
640 // Finally clean up this
641 free( this );
642 }
643