]> git.sesse.net Git - vlc/blob - modules/video_output/directx/aout.c
* ./src/audio_output/output.c: reverted my previous aout_OutputNextBuffer
[vlc] / modules / video_output / directx / aout.c
1 /*****************************************************************************
2  * aout.c: Windows DirectX audio output method
3  *****************************************************************************
4  * Copyright (C) 2001 VideoLAN
5  * $Id: aout.c,v 1.7 2002/08/25 09:40:00 sam Exp $
6  *
7  * Authors: Gildas Bazin <gbazin@netcourrier.com>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <errno.h>                                                 /* ENOMEM */
28 #include <fcntl.h>                                       /* open(), O_WRONLY */
29 #include <string.h>                                            /* strerror() */
30
31 #include <stdlib.h>                            /* calloc(), malloc(), free() */
32
33 #include <vlc/vlc.h>
34 #include <vlc/aout.h>
35 #include "aout_internal.h"
36
37 #include <mmsystem.h>
38 #include <dsound.h>
39
40 #define FRAME_SIZE 2048              /* The size is in samples, not in bytes */
41
42 /*****************************************************************************
43  * DirectSound GUIDs.
44  * Defining them here allows us to get rid of the dxguid library during
45  * the linking stage.
46  *****************************************************************************/
47 #include <initguid.h>
48 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf, 0x8, 0x0, 0xa0, 0xc9, 0x25, 0xcd, 0x16);
49
50 /*****************************************************************************
51  * notification_thread_t: DirectX event thread
52  *****************************************************************************/
53 typedef struct notification_thread_t
54 {
55     VLC_COMMON_MEMBERS
56
57     aout_instance_t * p_aout;
58     DSBPOSITIONNOTIFY p_events[2];               /* play notification events */
59     int i_buffer_size;                         /* Size in bytes of one frame */
60
61 } notification_thread_t;
62
63 /*****************************************************************************
64  * aout_sys_t: directx audio output method descriptor
65  *****************************************************************************
66  * This structure is part of the audio output thread descriptor.
67  * It describes the direct sound specific properties of an audio device.
68  *****************************************************************************/
69
70 struct aout_sys_t
71 {
72     LPDIRECTSOUND       p_dsobject;              /* main Direct Sound object */
73
74     LPDIRECTSOUNDBUFFER p_dsbuffer_primary;     /* the actual sound card buffer
75                                                    (not used directly) */
76
77     LPDIRECTSOUNDBUFFER p_dsbuffer;   /* the sound buffer we use (direct sound
78                                        * takes care of mixing all the
79                                        * secondary buffers into the primary) */
80
81     LPDIRECTSOUNDNOTIFY p_dsnotify;         /* the position notify interface */
82
83     HINSTANCE           hdsound_dll;      /* handle of the opened dsound dll */
84
85     vlc_mutex_t buffer_lock;                            /* audio buffer lock */
86
87     notification_thread_t * p_notif;                 /* DirectSoundThread id */
88
89 };
90
91 /*****************************************************************************
92  * Prototypes.
93  *****************************************************************************/
94 void E_(CloseAudio) ( vlc_object_t *p_this );
95
96 /*****************************************************************************
97  * Local prototypes.
98  *****************************************************************************/
99 static int  SetFormat ( aout_instance_t * );
100 static void Play      ( aout_instance_t * );
101
102 /* local functions */
103 static int  DirectxCreateSecondaryBuffer ( aout_instance_t * );
104 static void DirectxDestroySecondaryBuffer( aout_instance_t * );
105 static int  DirectxInitDSound            ( aout_instance_t * );
106 static void DirectSoundThread            ( notification_thread_t * );
107
108 /*****************************************************************************
109  * OpenAudio: open the audio device
110  *****************************************************************************
111  * This function opens and setups Direct Sound.
112  *****************************************************************************/
113 int E_(OpenAudio) ( vlc_object_t *p_this )
114 {
115     aout_instance_t * p_aout = (aout_instance_t *)p_this;
116     HRESULT dsresult;
117     DSBUFFERDESC dsbuffer_desc;
118
119     msg_Dbg( p_aout, "Open" );
120
121    /* Allocate structure */
122     p_aout->output.p_sys = malloc( sizeof( aout_sys_t ) );
123     if( p_aout->output.p_sys == NULL )
124     {
125         msg_Err( p_aout, "out of memory" );
126         return 1;
127     }
128
129     /* Initialize some variables */
130     p_aout->output.p_sys->p_dsobject = NULL;
131     p_aout->output.p_sys->p_dsbuffer_primary = NULL;
132     p_aout->output.p_sys->p_dsbuffer = NULL;
133     p_aout->output.p_sys->p_dsnotify = NULL;
134     p_aout->output.p_sys->p_notif = NULL;
135     vlc_mutex_init( p_aout, &p_aout->output.p_sys->buffer_lock );
136
137     p_aout->output.pf_setformat = SetFormat;
138     p_aout->output.pf_play = Play;
139
140     /* Initialise DirectSound */
141     if( DirectxInitDSound( p_aout ) )
142     {
143         msg_Err( p_aout, "cannot initialize DirectSound" );
144         goto error;
145     }
146
147     /* Obtain (not create) Direct Sound primary buffer */
148     memset( &dsbuffer_desc, 0, sizeof(DSBUFFERDESC) );
149     dsbuffer_desc.dwSize = sizeof(DSBUFFERDESC);
150     dsbuffer_desc.dwFlags = DSBCAPS_PRIMARYBUFFER;
151     msg_Warn( p_aout, "create direct sound primary buffer" );
152     dsresult = IDirectSound_CreateSoundBuffer(p_aout->output.p_sys->p_dsobject,
153                                      &dsbuffer_desc,
154                                      &p_aout->output.p_sys->p_dsbuffer_primary,
155                                      NULL);
156     if( dsresult != DS_OK )
157     {
158         msg_Err( p_aout, "cannot create direct sound primary buffer" );
159         goto error;
160     }
161
162
163     /* Now we need to setup DirectSound play notification */
164     p_aout->output.p_sys->p_notif =
165         vlc_object_create( p_aout, sizeof(notification_thread_t) );
166     p_aout->output.p_sys->p_notif->p_aout = p_aout;
167
168     /* first we need to create the notification events */
169     p_aout->output.p_sys->p_notif->p_events[0].hEventNotify =
170         CreateEvent( NULL, FALSE, FALSE, NULL );
171     p_aout->output.p_sys->p_notif->p_events[1].hEventNotify =
172         CreateEvent( NULL, FALSE, FALSE, NULL );
173
174     /* then launch the notification thread */
175     msg_Dbg( p_aout, "creating DirectSoundThread" );
176     if( vlc_thread_create( p_aout->output.p_sys->p_notif,
177                            "DirectSound Notification Thread",
178                            DirectSoundThread, 1 ) )
179     {
180         msg_Err( p_aout, "cannot create DirectSoundThread" );
181         goto error;
182     }
183
184     vlc_object_attach( p_aout->output.p_sys->p_notif, p_aout );
185
186     return 0;
187
188  error:
189     E_(CloseAudio)( VLC_OBJECT(p_aout) );
190     return 1;
191 }
192
193 /*****************************************************************************
194  * SetFormat: reset the audio device and sets its format
195  *****************************************************************************
196  * This functions set a new audio format.
197  * For this we need to close the current secondary buffer and create another
198  * one with the desired format.
199  *****************************************************************************/
200 static int SetFormat( aout_instance_t *p_aout )
201 {
202     HRESULT dsresult;
203
204     msg_Dbg( p_aout, "SetFormat" );
205     vlc_mutex_lock( &p_aout->output.p_sys->buffer_lock );
206
207     /* first release the current secondary buffer */
208     DirectxDestroySecondaryBuffer( p_aout );
209
210     /* calculate the frame size in bytes */
211     p_aout->output.p_sys->p_notif->i_buffer_size = FRAME_SIZE * sizeof(s16)
212                                             * p_aout->output.output.i_channels;
213
214     /* then create a new secondary buffer */
215     if( DirectxCreateSecondaryBuffer( p_aout ) )
216     {
217         msg_Err( p_aout, "cannot create buffer" );
218         vlc_mutex_unlock( &p_aout->output.p_sys->buffer_lock );
219         return 1;
220     }
221
222     vlc_mutex_unlock( &p_aout->output.p_sys->buffer_lock );
223
224     /* start playing the buffer */
225     dsresult = IDirectSoundBuffer_Play( p_aout->output.p_sys->p_dsbuffer,
226                                         0,                         /* Unused */
227                                         0,                         /* Unused */
228                                         DSBPLAY_LOOPING );          /* Flags */
229     if( dsresult == DSERR_BUFFERLOST )
230     {
231         IDirectSoundBuffer_Restore( p_aout->output.p_sys->p_dsbuffer );
232         dsresult = IDirectSoundBuffer_Play( p_aout->output.p_sys->p_dsbuffer,
233                                             0,                     /* Unused */
234                                             0,                     /* Unused */
235                                             DSBPLAY_LOOPING );      /* Flags */
236     }
237     if( dsresult != DS_OK )
238     {
239         msg_Warn( p_aout, "cannot play buffer" );
240     }
241
242     return 0;
243 }
244
245 /*****************************************************************************
246  * Play: play a sound buffer
247  *****************************************************************************
248  * This doesn't actually play the buffer. This just stores the buffer so it
249  * can be played by the callback thread.
250  *****************************************************************************/
251 static void Play( aout_instance_t *p_aout )
252 {
253 }
254
255 /*****************************************************************************
256  * CloseAudio: close the audio device
257  *****************************************************************************/
258 void E_(CloseAudio) ( vlc_object_t *p_this )
259 {
260     aout_instance_t * p_aout = (aout_instance_t *)p_this;
261
262     msg_Dbg( p_aout, "Close" );
263
264     /* kill the position notification thread, if any */
265     if( p_aout->output.p_sys->p_notif )
266     {
267         vlc_object_detach( p_aout->output.p_sys->p_notif );
268         if( p_aout->output.p_sys->p_notif->b_thread )
269         {
270             p_aout->output.p_sys->p_notif->b_die = 1;
271             vlc_thread_join( p_aout->output.p_sys->p_notif );
272         }
273         vlc_object_destroy( p_aout->output.p_sys->p_notif );
274     }
275
276     /* release the secondary buffer */
277     DirectxDestroySecondaryBuffer( p_aout );
278
279     /* then release the primary buffer */
280     if( p_aout->output.p_sys->p_dsbuffer_primary )
281         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer_primary );
282
283     /* finally release the DirectSound object */
284     if( p_aout->output.p_sys->p_dsobject )
285         IDirectSound_Release( p_aout->output.p_sys->p_dsobject );
286     
287     /* free DSOUND.DLL */
288     if( p_aout->output.p_sys->hdsound_dll )
289        FreeLibrary( p_aout->output.p_sys->hdsound_dll );
290
291     /* Close the Output. */
292     if ( p_aout->output.p_sys  )
293     { 
294         free( p_aout->output.p_sys );
295         p_aout->output.p_sys = NULL;
296     }
297 }
298
299 /*****************************************************************************
300  * DirectxInitDSound: handle all the gory details of DirectSound initialisation
301  *****************************************************************************/
302 static int DirectxInitDSound( aout_instance_t *p_aout )
303 {
304     HRESULT (WINAPI *OurDirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
305
306     p_aout->output.p_sys->hdsound_dll = LoadLibrary("DSOUND.DLL");
307     if( p_aout->output.p_sys->hdsound_dll == NULL )
308     {
309         msg_Warn( p_aout, "cannot open DSOUND.DLL" );
310         goto error;
311     }
312
313     OurDirectSoundCreate = (void *)GetProcAddress(
314                                            p_aout->output.p_sys->hdsound_dll,
315                                            "DirectSoundCreate" );
316     if( OurDirectSoundCreate == NULL )
317     {
318         msg_Warn( p_aout, "GetProcAddress FAILED" );
319         goto error;
320     }
321
322     /* Create the direct sound object */
323     if( OurDirectSoundCreate( NULL, &p_aout->output.p_sys->p_dsobject, NULL )
324         != DS_OK )
325     {
326         msg_Warn( p_aout, "cannot create a direct sound device" );
327         goto error;
328     }
329
330     /* Set DirectSound Cooperative level, ie what control we want over Windows
331      * sound device. In our case, DSSCL_EXCLUSIVE means that we can modify the
332      * settings of the primary buffer, but also that only the sound of our
333      * application will be hearable when it will have the focus.
334      * !!! (this is not really working as intended yet because to set the
335      * cooperative level you need the window handle of your application, and
336      * I don't know of any easy way to get it. Especially since we might play
337      * sound without any video, and so what window handle should we use ???
338      * The hack for now is to use the Desktop window handle - it seems to be
339      * working */
340     if( IDirectSound_SetCooperativeLevel( p_aout->output.p_sys->p_dsobject,
341                                           GetDesktopWindow(),
342                                           DSSCL_EXCLUSIVE) )
343     {
344         msg_Warn( p_aout, "cannot set direct sound cooperative level" );
345     }
346
347     return 0;
348
349  error:
350     p_aout->output.p_sys->p_dsobject = NULL;
351     if( p_aout->output.p_sys->hdsound_dll )
352     {
353         FreeLibrary( p_aout->output.p_sys->hdsound_dll );
354         p_aout->output.p_sys->hdsound_dll = NULL;
355     }
356     return 1;
357
358 }
359
360 /*****************************************************************************
361  * DirectxCreateSecondaryBuffer
362  *****************************************************************************
363  * This function creates the buffer we'll use to play audio.
364  * In DirectSound there are two kinds of buffers:
365  * - the primary buffer: which is the actual buffer that the soundcard plays
366  * - the secondary buffer(s): these buffers are the one actually used by
367  *    applications and DirectSound takes care of mixing them into the primary.
368  *
369  * Once you create a secondary buffer, you cannot change its format anymore so
370  * you have to release the current and create another one.
371  *****************************************************************************/
372 static int DirectxCreateSecondaryBuffer( aout_instance_t *p_aout )
373 {
374     WAVEFORMATEX         waveformat;
375     DSBUFFERDESC         dsbdesc;
376     DSBCAPS              dsbcaps;
377
378     /* First set the buffer format */
379     memset(&waveformat, 0, sizeof(WAVEFORMATEX)); 
380     waveformat.wFormatTag      = WAVE_FORMAT_PCM; 
381     waveformat.nChannels       = p_aout->output.output.i_channels;
382     waveformat.nSamplesPerSec  = p_aout->output.output.i_rate; 
383     waveformat.wBitsPerSample  = 16; 
384     waveformat.nBlockAlign     = waveformat.wBitsPerSample / 8 *
385                                  waveformat.nChannels;
386     waveformat.nAvgBytesPerSec = waveformat.nSamplesPerSec *
387                                      waveformat.nBlockAlign;
388
389     /* Then fill in the descriptor */
390     memset(&dsbdesc, 0, sizeof(DSBUFFERDESC)); 
391     dsbdesc.dwSize = sizeof(DSBUFFERDESC); 
392     dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2/* Better position accuracy */
393                     | DSBCAPS_CTRLPOSITIONNOTIFY     /* We need notification */
394                     | DSBCAPS_GLOBALFOCUS;      /* Allows background playing */
395     dsbdesc.dwBufferBytes = FRAME_SIZE * 2 /* frames*/ *      /* buffer size */
396                             sizeof(s16) * p_aout->output.output.i_channels;
397     dsbdesc.lpwfxFormat = &waveformat; 
398  
399     if( IDirectSound_CreateSoundBuffer( p_aout->output.p_sys->p_dsobject,
400                                         &dsbdesc,
401                                         &p_aout->output.p_sys->p_dsbuffer,
402                                         NULL) != DS_OK )
403     {
404         msg_Warn( p_aout, "cannot create direct sound secondary buffer" );
405         goto error;
406     }
407
408     /* backup the size of the secondary sound buffer */
409     memset(&dsbcaps, 0, sizeof(DSBCAPS)); 
410     dsbcaps.dwSize = sizeof(DSBCAPS);
411     IDirectSoundBuffer_GetCaps( p_aout->output.p_sys->p_dsbuffer, &dsbcaps  );
412
413     msg_Dbg( p_aout, "DirectxCreateSecondaryBuffer: %li",
414              dsbcaps.dwBufferBytes );
415
416     /* Now the secondary buffer is created, we need to setup its position
417      * notification */
418     p_aout->output.p_sys->p_notif->p_events[0].dwOffset = 0;
419     p_aout->output.p_sys->p_notif->p_events[1].dwOffset =
420         p_aout->output.p_sys->p_notif->i_buffer_size;
421
422     /* Get the IDirectSoundNotify interface */
423     if FAILED( IDirectSoundBuffer_QueryInterface(
424                                 p_aout->output.p_sys->p_dsbuffer,
425                                 &IID_IDirectSoundNotify,
426                                 (LPVOID *)&p_aout->output.p_sys->p_dsnotify ) )
427     {
428         msg_Warn( p_aout, "cannot get Notify interface" );
429         goto error;
430     }
431         
432     if FAILED( IDirectSoundNotify_SetNotificationPositions(
433                                     p_aout->output.p_sys->p_dsnotify, 2,
434                                     p_aout->output.p_sys->p_notif->p_events ) )
435     {
436         msg_Warn( p_aout, "cannot set position Notification" );
437         goto error;
438     }
439
440     p_aout->output.output.i_format = AOUT_FMT_S16_NE;
441     p_aout->output.i_nb_samples = FRAME_SIZE;
442
443     return 0;
444
445  error:
446     if( p_aout->output.p_sys->p_dsbuffer )
447     {
448         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
449         p_aout->output.p_sys->p_dsbuffer = NULL;
450     }
451     if( p_aout->output.p_sys->p_dsnotify )
452     {
453         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
454         p_aout->output.p_sys->p_dsnotify = NULL;
455     }
456     return 1;
457 }
458
459 /*****************************************************************************
460  * DirectxCreateSecondaryBuffer
461  *****************************************************************************
462  * This function destroys the secondary buffer.
463  *****************************************************************************/
464 static void DirectxDestroySecondaryBuffer( aout_instance_t *p_aout )
465 {
466     /* make sure the buffer isn't playing */
467     if( p_aout->output.p_sys->p_dsbuffer )
468         IDirectSoundBuffer_Stop( p_aout->output.p_sys->p_dsbuffer );
469
470     if( p_aout->output.p_sys->p_dsnotify )
471     {
472         IDirectSoundNotify_Release( p_aout->output.p_sys->p_dsnotify );
473         p_aout->output.p_sys->p_dsnotify = NULL;
474     }
475
476     if( p_aout->output.p_sys->p_dsbuffer )
477     {
478         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
479         p_aout->output.p_sys->p_dsbuffer = NULL;
480     }
481 }
482
483 /*****************************************************************************
484  * DirectSoundThread: this thread will capture play notification events. 
485  *****************************************************************************
486  * We use this thread to emulate a callback mechanism. The thread probes for
487  * event notification and fills up the DS secondary buffer when needed.
488  *****************************************************************************/
489 static void DirectSoundThread( notification_thread_t *p_notif )
490 {
491     HANDLE  notification_events[2];
492     HRESULT dsresult;
493     aout_instance_t *p_aout = p_notif->p_aout;
494
495     notification_events[0] = p_notif->p_events[0].hEventNotify;
496     notification_events[1] = p_notif->p_events[1].hEventNotify;
497
498     /* Tell the main thread that we are ready */
499     vlc_thread_ready( p_notif );
500
501     /* this thread must be high-priority */
502     if( !SetThreadPriority( GetCurrentThread(),
503                             THREAD_PRIORITY_ABOVE_NORMAL ) )
504     {
505         msg_Warn( p_notif, "DirectSoundThread could not raise its priority" );
506     }
507
508     msg_Dbg( p_notif, "DirectSoundThread ready" );
509
510     while( !p_notif->b_die )
511     {
512         int i_which_event;
513         void *p_write_position, *p_wrap_around;
514         long l_bytes1, l_bytes2;
515         aout_buffer_t * p_buffer;
516
517         /* wait for the position notification */
518         i_which_event = WaitForMultipleObjects( 2, notification_events, 0,
519                                                 INFINITE ) - WAIT_OBJECT_0;
520
521         vlc_mutex_lock( &p_aout->output.p_sys->buffer_lock );
522
523         if( p_notif->b_die )
524         {
525             vlc_mutex_unlock( &p_aout->output.p_sys->buffer_lock );
526             break;
527         }
528
529         /* Before copying anything, we have to lock the buffer */
530         dsresult = IDirectSoundBuffer_Lock(
531                                                                 /* DS buffer */
532             p_aout->output.p_sys->p_dsbuffer,
533                                                      /* Offset of lock start */
534             i_which_event ? 0 : p_notif->i_buffer_size,
535             p_notif->i_buffer_size,                 /* Number of bytes */
536             &p_write_position,                      /* Address of lock start */
537             &l_bytes1,           /* Count of bytes locked before wrap around */
538             &p_wrap_around,                /* Buffer adress (if wrap around) */
539             &l_bytes2,                   /* Count of bytes after wrap around */
540             0 );                                                    /* Flags */
541         if( dsresult == DSERR_BUFFERLOST )
542         {
543             IDirectSoundBuffer_Restore( p_aout->output.p_sys->p_dsbuffer );
544             dsresult = IDirectSoundBuffer_Lock(
545                            p_aout->output.p_sys->p_dsbuffer,
546                            i_which_event ? 0 : p_notif->i_buffer_size,
547                            p_notif->i_buffer_size,
548                            &p_write_position,
549                            &l_bytes1,
550                            &p_wrap_around,
551                            &l_bytes2,
552                            0 );
553         }
554         if( dsresult != DS_OK )
555         {
556             msg_Warn( p_notif, "cannot lock buffer" );
557             vlc_mutex_unlock( &p_aout->output.p_sys->buffer_lock );
558             continue;
559         }
560
561         /* FIXME : take into account DirectSound latency instead of mdate() */
562         p_buffer = aout_OutputNextBuffer( p_aout, mdate(), VLC_FALSE );
563
564         /* Now do the actual memcpy into the circular buffer */
565         if ( l_bytes1 != p_notif->i_buffer_size )
566             msg_Err( p_aout, "Wrong buffer size: %d, %d", l_bytes1,
567                      p_notif->i_buffer_size );
568
569         if ( p_buffer != NULL )
570         {
571             p_aout->p_vlc->pf_memcpy( p_write_position, p_buffer->p_buffer,
572                                       l_bytes1 );
573             aout_BufferFree( p_buffer );
574         }
575         else
576         {
577             memset( p_write_position, 0, l_bytes1 );
578         }
579
580         /* Now the data has been copied, unlock the buffer */
581         IDirectSoundBuffer_Unlock( p_aout->output.p_sys->p_dsbuffer,
582                         p_write_position, l_bytes1, p_wrap_around, l_bytes2 );
583
584         vlc_mutex_unlock( &p_aout->output.p_sys->buffer_lock );
585
586     }
587
588     /* free the events */
589     CloseHandle( notification_events[0] );
590     CloseHandle( notification_events[1] );
591
592     msg_Dbg( p_notif, "DirectSoundThread exiting" );
593
594 }