consumer avformat added, various cleanups and consumer realtime switching
[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/time.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 buffer for low latency
106 mlt_properties_set_int( this->properties, "buffer", 1 );
107
108 // Default progressive true
109 mlt_properties_set_int( this->properties, "progressive", 0 );
110
111 // Get aspect ratio
112 this->aspect_ratio = mlt_properties_get_double( this->properties, "aspect_ratio" );
113
114 // process actual param
115 if ( arg == NULL || sscanf( arg, "%dx%d", &this->width, &this->height ) != 2 )
116 {
117 this->width = mlt_properties_get_int( this->properties, "width" );
118 this->height = mlt_properties_get_int( this->properties, "height" );
119 }
120
121 // Default window size
122 this->window_width = (int)( (float)this->height * 4.0/3.0 + 0.5);
123 this->window_height = this->height;
124
125 // Set the sdl flags
126 this->sdl_flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL | SDL_RESIZABLE;
127
128 // Allow thread to be started/stopped
129 parent->start = consumer_start;
130 parent->stop = consumer_stop;
131 parent->is_stopped = consumer_is_stopped;
132
133 // Return the consumer produced
134 return parent;
135 }
136
137 // malloc or consumer init failed
138 free( this );
139
140 // Indicate failure
141 return NULL;
142 }
143
144 int consumer_start( mlt_consumer parent )
145 {
146 consumer_sdl this = parent->child;
147
148 if ( !this->running )
149 {
150 this->running = 1;
151 pthread_create( &this->thread, NULL, consumer_thread, this );
152 }
153
154 return 0;
155 }
156
157 int consumer_stop( mlt_consumer parent )
158 {
159 // Get the actual object
160 consumer_sdl this = parent->child;
161
162 if ( this->running )
163 {
164 // Kill the thread and clean up
165 this->running = 0;
166
167 pthread_mutex_lock( &this->audio_mutex );
168 pthread_cond_broadcast( &this->audio_cond );
169 pthread_mutex_unlock( &this->audio_mutex );
170
171 pthread_join( this->thread, NULL );
172 }
173
174 return 0;
175 }
176
177 int consumer_is_stopped( mlt_consumer parent )
178 {
179 consumer_sdl this = parent->child;
180 return !this->running;
181 }
182
183 static int sdl_lock_display( )
184 {
185 SDL_Surface *screen = SDL_GetVideoSurface( );
186 return screen != NULL && ( !SDL_MUSTLOCK( screen ) || SDL_LockSurface( screen ) >= 0 );
187 }
188
189 static void sdl_unlock_display( )
190 {
191 SDL_Surface *screen = SDL_GetVideoSurface( );
192 if ( screen != NULL && SDL_MUSTLOCK( screen ) )
193 SDL_UnlockSurface( screen );
194 }
195
196 static void sdl_fill_audio( void *udata, uint8_t *stream, int len )
197 {
198 consumer_sdl this = udata;
199
200 // Get the volume
201 float volume = mlt_properties_get_double( this->properties, "volume" );
202
203 pthread_mutex_lock( &this->audio_mutex );
204
205 // Block until audio received
206 while ( this->running && len > this->audio_avail )
207 pthread_cond_wait( &this->audio_cond, &this->audio_mutex );
208
209 if ( this->audio_avail >= len )
210 {
211 // Place in the audio buffer
212 SDL_MixAudio( stream, this->audio_buffer, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
213
214 // Remove len from the audio available
215 this->audio_avail -= len;
216
217 // Remove the samples
218 memmove( this->audio_buffer, this->audio_buffer + len, this->audio_avail );
219 }
220 else
221 {
222 // Just to be safe, wipe the stream first
223 memset( stream, 0, len );
224
225 // Copy what we have into the stream
226 memcpy( stream, this->audio_buffer, this->audio_avail );
227
228 // Mix the audio
229 SDL_MixAudio( stream, stream, len, ( int )( ( float )SDL_MIX_MAXVOLUME * volume ) );
230
231 // No audio left
232 this->audio_avail = 0;
233 }
234
235 // We're definitely playing now
236 this->playing = 1;
237
238 pthread_cond_broadcast( &this->audio_cond );
239 pthread_mutex_unlock( &this->audio_mutex );
240 }
241
242 static int consumer_play_audio( consumer_sdl this, mlt_frame frame, int init_audio, int *duration )
243 {
244 // Get the properties of this consumer
245 mlt_properties properties = this->properties;
246 mlt_audio_format afmt = mlt_audio_pcm;
247
248 // Set the preferred params of the test card signal
249 int channels = mlt_properties_get_int( properties, "channels" );
250 int frequency = mlt_properties_get_int( properties, "frequency" );
251 static int counter = 0;
252
253 int samples = mlt_sample_calculator( mlt_properties_get_double( this->properties, "fps" ), frequency, counter++ );
254
255 int16_t *pcm;
256 int bytes;
257
258 mlt_frame_get_audio( frame, &pcm, &afmt, &frequency, &channels, &samples );
259 *duration = ( ( samples * 1000 ) / frequency );
260
261 if ( mlt_properties_get_int( properties, "audio_off" ) )
262 {
263 this->playing = 1;
264 init_audio = 1;
265 return init_audio;
266 }
267
268 if ( init_audio == 1 )
269 {
270 SDL_AudioSpec request;
271 SDL_AudioSpec got;
272
273 // specify audio format
274 memset( &request, 0, sizeof( SDL_AudioSpec ) );
275 this->playing = 0;
276 request.freq = frequency;
277 request.format = AUDIO_S16;
278 request.channels = channels;
279 request.samples = 1024;
280 request.callback = sdl_fill_audio;
281 request.userdata = (void *)this;
282 if ( SDL_OpenAudio( &request, &got ) != 0 )
283 {
284 fprintf( stderr, "SDL failed to open audio: %s\n", SDL_GetError() );
285 init_audio = 2;
286 }
287 else if ( got.size != 0 )
288 {
289 SDL_PauseAudio( 0 );
290 init_audio = 0;
291 }
292 }
293
294 if ( init_audio == 0 )
295 {
296 mlt_properties properties = mlt_frame_properties( frame );
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 if ( mlt_properties_get_double( properties, "_speed" ) == 1 )
302 memcpy( &this->audio_buffer[ this->audio_avail ], pcm, bytes );
303 else
304 memset( &this->audio_buffer[ this->audio_avail ], 0, bytes );
305 this->audio_avail += bytes;
306 pthread_cond_broadcast( &this->audio_cond );
307 pthread_mutex_unlock( &this->audio_mutex );
308 }
309 else
310 {
311 this->playing = 1;
312 }
313
314 return init_audio;
315 }
316
317 static int consumer_play_video( consumer_sdl this, mlt_frame frame )
318 {
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
327 if ( mlt_properties_get_int( properties, "video_off" ) == 0 )
328 {
329 // Get the image, width and height
330 mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
331
332 // Handle events
333 if ( this->sdl_screen != NULL )
334 {
335 SDL_Event event;
336
337 changed = consumer_get_dimensions( &this->window_width, &this->window_height );
338
339 while ( SDL_PollEvent( &event ) )
340 {
341 switch( event.type )
342 {
343 case SDL_VIDEORESIZE:
344 this->window_width = event.resize.w;
345 this->window_height = event.resize.h;
346 changed = 1;
347 break;
348 case SDL_QUIT:
349 this->running = 0;
350 break;
351 case SDL_KEYDOWN:
352 {
353 mlt_producer producer = mlt_properties_get_data( properties, "transport_producer", NULL );
354 char keyboard[ 2 ] = " ";
355 void (*callback)( mlt_producer, char * ) = mlt_properties_get_data( properties, "transport_callback", NULL );
356 if ( callback != NULL && producer != NULL && event.key.keysym.unicode < 0x80 && event.key.keysym.unicode > 0 )
357 {
358 keyboard[ 0 ] = ( char )event.key.keysym.unicode;
359 callback( producer, keyboard );
360 }
361 }
362 break;
363 }
364 }
365 }
366
367 if ( width != this->width || height != this->height )
368 {
369 this->width = width;
370 this->height = height;
371 changed = 1;
372 }
373
374 if ( this->sdl_screen == NULL || changed )
375 {
376 double aspect_ratio = ( float )this->aspect_ratio * this->width / this->height;
377 float display_aspect_ratio = ( float )width / height;
378 SDL_Rect rect;
379 if ( mlt_properties_get( properties, "rescale" ) != NULL &&
380 !strcmp( mlt_properties_get( properties, "rescale" ), "none" ) )
381 aspect_ratio = mlt_frame_get_aspect_ratio( frame ) * mlt_properties_get_int(mlt_frame_properties(frame),"width") / mlt_properties_get_int(mlt_frame_properties(frame),"height");
382
383 if ( aspect_ratio == 1 )
384 {
385 rect.w = this->window_width;
386 rect.h = this->window_height;
387 }
388 else if ( this->window_width < this->window_height * aspect_ratio )
389 {
390 rect.w = this->window_width;
391 rect.h = this->window_width / aspect_ratio + 1;
392 }
393 else
394 {
395 rect.w = this->window_height * aspect_ratio + 1;
396 rect.h = this->window_height;
397 }
398
399 if ( mlt_properties_get_int( properties, "scale_overlay" ) )
400 {
401 if ( ( float )rect.w * display_aspect_ratio < this->window_width )
402 rect.w = ( int )( ( float )rect.w * display_aspect_ratio );
403 else if ( ( float )rect.h * display_aspect_ratio < this->window_height )
404 rect.h = ( int )( ( float )rect.h * display_aspect_ratio );
405 }
406
407 rect.x = ( this->window_width - rect.w ) / 2;
408 rect.y = ( this->window_height - rect.h ) / 2;
409
410 // Force an overlay recreation
411 if ( this->sdl_overlay != NULL )
412 SDL_FreeYUVOverlay( this->sdl_overlay );
413
414 // open SDL window with video overlay, if possible
415 this->sdl_screen = SDL_SetVideoMode( this->window_width, this->window_height, 0, this->sdl_flags );
416
417 if ( this->sdl_screen != NULL )
418 {
419 SDL_SetClipRect( this->sdl_screen, &rect );
420
421 sdl_lock_display();
422 this->sdl_overlay = SDL_CreateYUVOverlay( this->width - (this->width % 4), this->height- (this->height % 2 ), SDL_YUY2_OVERLAY, this->sdl_screen );
423 sdl_unlock_display();
424 }
425 }
426
427 if ( this->sdl_screen != NULL && this->sdl_overlay != NULL )
428 {
429 this->buffer = this->sdl_overlay->pixels[ 0 ];
430 if ( SDL_LockYUVOverlay( this->sdl_overlay ) >= 0 )
431 {
432 memcpy( this->buffer, image, width * height * 2 );
433 SDL_UnlockYUVOverlay( this->sdl_overlay );
434 SDL_DisplayYUVOverlay( this->sdl_overlay, &this->sdl_screen->clip_rect );
435 }
436 }
437 }
438
439 // Close the frame
440 mlt_frame_close( frame );
441
442 return 0;
443 }
444
445 /** Threaded wrapper for pipe.
446 */
447
448 static void *consumer_thread( void *arg )
449 {
450 // Identify the arg
451 consumer_sdl this = arg;
452
453 // Get the consumer
454 mlt_consumer consumer = &this->parent;
455
456 // internal intialization
457 int init_audio = 1;
458
459 // Obtain time of thread start
460 struct timeval now;
461 int64_t start = 0;
462 int64_t elapsed = 0;
463 int duration = 0;
464 int64_t playtime = 0;
465 struct timespec tm;
466 mlt_frame next = NULL;
467 mlt_frame frame = NULL;
468
469 if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE ) < 0 )
470 {
471 fprintf( stderr, "Failed to initialize SDL: %s\n", SDL_GetError() );
472 return NULL;
473 }
474
475 SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL );
476 SDL_EnableUNICODE( 1 );
477
478 // Loop until told not to
479 while( this->running )
480 {
481 // Get a frame from the attached producer
482 frame = mlt_consumer_rt_frame( consumer );
483
484 // Ensure that we have a frame
485 if ( frame != NULL )
486 {
487 // Play audio
488 init_audio = consumer_play_audio( this, frame, init_audio, &duration );
489
490 if ( this->playing )
491 {
492 // Get the current time
493 gettimeofday( &now, NULL );
494
495 // Determine elapsed time
496 if ( start == 0 )
497 start = ( int64_t )now.tv_sec * 1000000 + now.tv_usec;
498 else
499 elapsed = ( ( int64_t )now.tv_sec * 1000000 + now.tv_usec) - start;
500 }
501
502 // Set playtime for this frame
503 mlt_properties_set_position( mlt_frame_properties( frame ), "playtime", playtime );
504
505 // Push this frame to the back of the queue
506 mlt_deque_push_back( this->queue, frame );
507
508 // Calculate the next playtime
509 playtime += ( duration * 1000 );
510 }
511
512 if ( this->playing )
513 {
514 // Pop the next frame
515 next = mlt_deque_pop_front( this->queue );
516
517 // See if we have to delay the display of the current frame
518 if ( next != NULL && mlt_properties_get_int( mlt_frame_properties( next ), "rendered" ) == 1 )
519 {
520 mlt_position scheduled = mlt_properties_get_position( mlt_frame_properties( next ), "playtime" ) + 5000;
521 if ( scheduled > elapsed && mlt_deque_count( this->queue ) > 25 )
522 {
523 tm.tv_sec = ( scheduled - elapsed ) / 1000000;
524 tm.tv_nsec = ( ( scheduled - elapsed ) % 1000000 ) * 1000;
525 nanosleep( &tm, NULL );
526
527 // Show current frame
528 consumer_play_video( this, next );
529 }
530 else if ( scheduled > elapsed )
531 {
532 // More time to kill
533 mlt_deque_push_front( this->queue, next );
534 }
535 else
536 {
537 // Show current frame
538 consumer_play_video( this, next );
539 }
540 }
541 else
542 {
543 // This is an unrendered frame - just close it
544 mlt_frame_close( next );
545 }
546 }
547 }
548
549 // internal cleanup
550 if ( init_audio == 0 )
551 SDL_AudioQuit( );
552 if ( this->sdl_overlay != NULL )
553 SDL_FreeYUVOverlay( this->sdl_overlay );
554 SDL_Quit( );
555
556 while( mlt_deque_count( this->queue ) )
557 mlt_frame_close( mlt_deque_pop_back( this->queue ) );
558
559 this->sdl_screen = NULL;
560 this->sdl_overlay = NULL;
561 this->audio_avail = 0;
562
563 return NULL;
564 }
565
566 static int consumer_get_dimensions( int *width, int *height )
567 {
568 int changed = 0;
569
570 // SDL windows manager structure
571 SDL_SysWMinfo wm;
572
573 // Specify the SDL Version
574 SDL_VERSION( &wm.version );
575
576 // Get the wm structure
577 if ( SDL_GetWMInfo( &wm ) == 1 )
578 {
579 // Check that we have the X11 wm
580 if ( wm.subsystem == SDL_SYSWM_X11 )
581 {
582 // Get the SDL window
583 Window window = wm.info.x11.window;
584
585 // Get the display session
586 Display *display = wm.info.x11.display;
587
588 // Get the window attributes
589 XWindowAttributes attr;
590 XGetWindowAttributes( display, window, &attr );
591
592 // Determine whether window has changed
593 changed = *width != attr.width || *height != attr.height;
594
595 // Return width and height
596 *width = attr.width;
597 *height = attr.height;
598 }
599 }
600
601 return changed;
602 }
603
604 /** Callback to allow override of the close method.
605 */
606
607 static void consumer_close( mlt_consumer parent )
608 {
609 // Get the actual object
610 consumer_sdl this = parent->child;
611
612 // Stop the consumer
613 mlt_consumer_stop( parent );
614
615 // Destroy mutexes
616 pthread_mutex_destroy( &this->audio_mutex );
617 pthread_cond_destroy( &this->audio_cond );
618
619 // Now clean up the rest
620 mlt_consumer_close( parent );
621
622 // Finally clean up this
623 free( this );
624 }