]> git.sesse.net Git - mlt/blob - src/modules/sdl/consumer_sdl.c
d35e4a7869f24346a6ed46883d13cbd5bb85aaa8
[mlt] / 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 * 6 ];
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, int skip, 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         int show = 1;
328
329         if ( mlt_properties_get_int( properties, "video_off" ) )
330         {
331                 mlt_frame_close( frame );
332                 return 0;
333         }
334
335         // Handle events
336         if ( this->sdl_screen != NULL )
337         {
338                 SDL_Event event;
339
340                 changed = consumer_get_dimensions( &this->window_width, &this->window_height );
341
342                 while ( SDL_PollEvent( &event ) )
343                 {
344                         switch( event.type )
345                         {
346                                 case SDL_VIDEORESIZE:
347                                         this->window_width = event.resize.w;
348                                         this->window_height = event.resize.h;
349                                         changed = 1;
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         // Set skip
368         mlt_properties_set_int( mlt_frame_properties( frame ), "skip", skip );
369         mlt_properties_set_position( mlt_frame_properties( frame ), "playtime", playtime );
370
371         // Push this frame to the back of the queue
372         mlt_deque_push_back( this->queue, frame );
373         frame = NULL;
374
375         if ( this->playing )
376         {
377                 // We might want to use an old frame if the current frame is skipped
378                 mlt_frame candidate = NULL;
379
380                 while ( frame == NULL && mlt_deque_count( this->queue ) )
381                 {
382                         frame = mlt_deque_peek_front( this->queue );
383                         show = !mlt_properties_get_int( mlt_frame_properties( frame ), "skip" );
384                         playtime = mlt_properties_get_position( mlt_frame_properties( frame ), "playtime" );
385
386                         // Check if frame is in the future or past
387                         if ( !show )
388                         {
389                                 frame = mlt_deque_pop_front( this->queue );
390                                 mlt_frame_close( frame );
391                                 frame = NULL;
392                         }
393                         else if ( playtime > elapsed )
394                         {
395                                 // no frame to show or remove
396                                 frame = NULL;
397                                 break;
398                         }
399                         else if ( playtime < elapsed - 40 )
400                         {
401                                 if ( candidate != NULL )
402                                         mlt_frame_close( candidate );
403                                 candidate = mlt_deque_pop_front( this->queue );
404                                 frame = NULL;
405                         }
406                         else
407                         {
408                                 // Get the frame at the front of the queue
409                                 frame = mlt_deque_pop_front( this->queue );
410                         }
411                 }
412
413                 if ( frame == NULL )
414                         frame = candidate;
415                 else if ( candidate != NULL )
416                         mlt_frame_close( candidate );
417         }
418
419         if ( this->playing && frame != NULL )
420         {
421                 // Get the image, width and height
422                 mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
423
424                 if ( width != this->width || height != this->height )
425                 {
426                         this->width = width;
427                         this->height = height;
428                         changed = 1;
429                 }
430
431                 if ( this->sdl_screen == NULL || changed )
432                 {
433                         double aspect_ratio = mlt_frame_get_aspect_ratio( frame );
434                         float display_aspect_ratio = (float)width / (float)height;
435                         SDL_Rect rect;
436
437                         if ( mlt_properties_get_double( properties, "aspect_ratio" ) )
438                                 aspect_ratio = mlt_properties_get_double( properties, "aspect_ratio" );
439
440                         if ( aspect_ratio == 1 )
441                         {
442                                 rect.w = this->window_width;
443                                 rect.h = this->window_height;
444                         }
445                         else if ( this->window_width < this->window_height * aspect_ratio )
446                         {
447                                 rect.w = this->window_width;
448                                 rect.h = this->window_width / aspect_ratio;
449                         }
450                         else
451                         {
452                                 rect.w = this->window_height * aspect_ratio;
453                                 rect.h = this->window_height;
454                         }
455
456                         if ( mlt_properties_get_int( properties, "scale_overlay" ) )
457                         {
458                                 if ( ( float )rect.w * display_aspect_ratio < this->window_width )
459                                         rect.w = ( int )( ( float )rect.w * display_aspect_ratio );
460                                 else if ( ( float )rect.h * display_aspect_ratio < this->window_height )
461                                         rect.h = ( int )( ( float )rect.h * display_aspect_ratio );
462                         }
463
464                         rect.x = ( this->window_width - rect.w ) / 2;
465                         rect.y = ( this->window_height - rect.h ) / 2;
466
467                         // Force an overlay recreation
468                         if ( this->sdl_overlay != NULL )
469                                 SDL_FreeYUVOverlay( this->sdl_overlay );
470
471                         // open SDL window with video overlay, if possible
472                         this->sdl_screen = SDL_SetVideoMode( this->window_width, this->window_height, 0, this->sdl_flags );
473
474                         if ( this->sdl_screen != NULL )
475                         {
476                                 SDL_SetClipRect( this->sdl_screen, &rect );
477                         
478                                 sdl_lock_display();
479                                 this->sdl_overlay = SDL_CreateYUVOverlay( this->width - (this->width % 4), this->height- (this->height % 2 ), SDL_YUY2_OVERLAY, this->sdl_screen );
480                                 sdl_unlock_display();
481                         }
482                 }
483                         
484                 if ( this->sdl_screen != NULL && this->sdl_overlay != NULL )
485                 {
486                         this->buffer = this->sdl_overlay->pixels[ 0 ];
487                         if ( SDL_LockYUVOverlay( this->sdl_overlay ) >= 0 )
488                         {
489                                 memcpy( this->buffer, image, width * height * 2 );
490                                 SDL_UnlockYUVOverlay( this->sdl_overlay );
491                                 SDL_DisplayYUVOverlay( this->sdl_overlay, &this->sdl_screen->clip_rect );
492                         }
493                 }
494         }
495
496         // Close the frame
497         if ( frame != NULL )
498                 mlt_frame_close( frame );
499
500         if ( mlt_deque_count( this->queue ) && !skip )
501         {
502                 // Tell the producers about our scale relative to the normalisation
503                 frame = mlt_deque_peek_front( this->queue );
504                 mlt_properties_set_double( mlt_frame_properties( frame ), "consumer_scale",
505                         ( double )height / mlt_properties_get_double( properties, "height" ) );
506                 mlt_frame_get_image( frame, &image, &vfmt, &width, &height, 0 );
507         }
508
509         return 0;
510 }
511
512 /** Threaded wrapper for pipe.
513 */
514
515 static void *consumer_thread( void *arg )
516 {
517         // Identify the arg
518         consumer_sdl this = arg;
519
520         // Get the consumer
521         mlt_consumer consumer = &this->parent;
522
523         // internal intialization
524         int init_audio = 1;
525
526         // Obtain time of thread start
527         struct timeb now;
528         int64_t start = 0;
529         int64_t elapsed = 0;
530         int duration = 0;
531         int64_t playtime = 0;
532         int skip = 0;
533
534         if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE ) < 0 )
535         {
536                 fprintf( stderr, "Failed to initialize SDL: %s\n", SDL_GetError() );
537                 return NULL;
538         }
539         
540         // Loop until told not to
541         while( this->running )
542         {
543                 // Get a frame from the attached producer
544                 mlt_frame frame = mlt_consumer_get_frame( consumer );
545
546                 // Ensure that we have a frame
547                 if ( frame != NULL )
548                 {
549                         skip = 0;
550
551                         // SDL adapts display aspect, but set this so pixel aspect can be normalised
552 //                      mlt_properties_set_double( mlt_frame_properties( frame ), "consumer_aspect_ratio",
553 //                              mlt_frame_get_aspect_ratio( frame ) );
554                         
555                         // Play audio
556                         init_audio = consumer_play_audio( this, frame, init_audio, &duration );
557
558                         if ( this->playing )
559                         {
560                                 // Get the current time
561                                 ftime( &now );
562
563                                 // Determine elapsed time
564                                 if ( start == 0 )
565                                         start = ( int64_t )now.time * 1000 + now.millitm;
566                                 else
567                                         elapsed = ( ( int64_t )now.time * 1000 + now.millitm ) - start;
568
569                                 skip = playtime < elapsed;
570
571                                 if ( skip )
572                                         start = start + ( elapsed - playtime );
573                         }
574
575                         consumer_play_video( this, frame, elapsed, skip, playtime );
576
577                         playtime += duration;
578                 }
579         }
580
581         // internal cleanup
582         if ( init_audio == 0 )
583                 SDL_AudioQuit( );
584         if ( this->sdl_overlay != NULL )
585                 SDL_FreeYUVOverlay( this->sdl_overlay );
586         SDL_Quit( );
587
588         while( mlt_deque_count( this->queue ) )
589                 mlt_frame_close( mlt_deque_pop_back( this->queue ) );
590
591         this->sdl_screen = NULL;
592         this->sdl_overlay = NULL;
593         this->audio_avail = 0;
594
595         return NULL;
596 }
597
598 static int consumer_get_dimensions( int *width, int *height )
599 {
600         int changed = 0;
601
602         // SDL windows manager structure
603         SDL_SysWMinfo wm;
604
605         // Specify the SDL Version
606         SDL_VERSION( &wm.version );
607
608         // Get the wm structure
609         if ( SDL_GetWMInfo( &wm ) == 1 )
610         {
611                 // Check that we have the X11 wm
612                 if ( wm.subsystem == SDL_SYSWM_X11 ) 
613                 {
614                         // Get the SDL window
615                         Window window = wm.info.x11.window;
616
617                         // Get the display session
618                         Display *display = wm.info.x11.display;
619
620                         // Get the window attributes
621                         XWindowAttributes attr;
622                         XGetWindowAttributes( display, window, &attr );
623
624                         // Determine whether window has changed
625                         changed = *width != attr.width || *height != attr.height;
626
627                         // Return width and height
628                         *width = attr.width;
629                         *height = attr.height;
630                 }
631         }
632
633         return changed;
634 }
635
636 /** Callback to allow override of the close method.
637 */
638
639 static void consumer_close( mlt_consumer parent )
640 {
641         // Get the actual object
642         consumer_sdl this = parent->child;
643
644         // Stop the consumer
645         mlt_consumer_stop( parent );
646
647         // Destroy mutexes
648         pthread_mutex_destroy( &this->audio_mutex );
649         pthread_cond_destroy( &this->audio_cond );
650                 
651         // Now clean up the rest
652         mlt_consumer_close( parent );
653
654         // Finally clean up this
655         free( this );
656 }
657