2e830cf777ce023b242539d8f3d8daf41a579868
[vlc.git] / modules / audio_output / directx.c
1 /*****************************************************************************
2  * directx.c: Windows DirectX audio output method
3  *****************************************************************************
4  * Copyright (C) 2001 VideoLAN
5  * $Id: directx.c,v 1.8 2002/11/15 16:27:10 gbazin 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 <windows.h>
38 #include <mmsystem.h>
39 #include <dsound.h>
40
41 #define FRAME_SIZE 2048              /* The size is in samples, not in bytes */
42 #define FRAMES_NUM 4
43
44 /* frame buffer status */
45 #define FRAME_QUEUED 0
46 #define FRAME_EMPTY 1
47
48 /*****************************************************************************
49  * DirectSound GUIDs.
50  * Defining them here allows us to get rid of the dxguid library during
51  * the linking stage.
52  *****************************************************************************/
53 #include <initguid.h>
54 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf, 0x8, 0x0, 0xa0, 0xc9, 0x25, 0xcd, 0x16);
55
56 /*****************************************************************************
57  * Useful macros
58  *****************************************************************************/
59 #ifndef WAVE_FORMAT_IEEE_FLOAT
60 #   define WAVE_FORMAT_IEEE_FLOAT 0x0003
61 #endif
62
63 /*****************************************************************************
64  * notification_thread_t: DirectX event thread
65  *****************************************************************************/
66 typedef struct notification_thread_t
67 {
68     VLC_COMMON_MEMBERS
69
70     aout_instance_t * p_aout;
71     int i_frame_status[FRAMES_NUM];           /* status of each frame buffer */
72     DSBPOSITIONNOTIFY p_events[FRAMES_NUM];      /* play notification events */
73     int i_frame_size;                         /* Size in bytes of one frame */
74
75     mtime_t start_date;
76
77 } notification_thread_t;
78
79 /*****************************************************************************
80  * aout_sys_t: directx audio output method descriptor
81  *****************************************************************************
82  * This structure is part of the audio output thread descriptor.
83  * It describes the direct sound specific properties of an audio device.
84  *****************************************************************************/
85 struct aout_sys_t
86 {
87     LPDIRECTSOUND       p_dsobject;              /* main Direct Sound object */
88
89     LPDIRECTSOUNDBUFFER p_dsbuffer_primary;     /* the actual sound card buffer
90                                                    (not used directly) */
91
92     LPDIRECTSOUNDBUFFER p_dsbuffer;   /* the sound buffer we use (direct sound
93                                        * takes care of mixing all the
94                                        * secondary buffers into the primary) */
95
96     LPDIRECTSOUNDNOTIFY p_dsnotify;         /* the position notify interface */
97
98     HINSTANCE           hdsound_dll;      /* handle of the opened dsound dll */
99
100     notification_thread_t * p_notif;                 /* DirectSoundThread id */
101
102     int b_playing;                                         /* playing status */
103 };
104
105 /*****************************************************************************
106  * Local prototypes.
107  *****************************************************************************/
108 static int  OpenAudio  ( vlc_object_t * );
109 static void CloseAudio ( vlc_object_t * );
110
111 static void Play       ( aout_instance_t * );
112
113 /* local functions */
114 static int  DirectxCreateSecondaryBuffer ( aout_instance_t * );
115 static void DirectxDestroySecondaryBuffer( aout_instance_t * );
116 static int  DirectxInitDSound            ( aout_instance_t * );
117 static void DirectSoundThread            ( notification_thread_t * );
118 static int  DirectxFillBuffer            ( aout_instance_t *, int,
119                                            aout_buffer_t * );
120
121 /*****************************************************************************
122  * Module descriptor
123  *****************************************************************************/
124 vlc_module_begin();
125     set_description( _("DirectX audio module") );
126     set_capability( "audio output", 100 );
127     add_shortcut( "directx" );
128     set_callbacks( OpenAudio, CloseAudio );
129 vlc_module_end();
130
131 /*****************************************************************************
132  * OpenAudio: open the audio device
133  *****************************************************************************
134  * This function opens and setups Direct Sound.
135  *****************************************************************************/
136 static int OpenAudio( vlc_object_t *p_this )
137 {
138     aout_instance_t * p_aout = (aout_instance_t *)p_this;
139     HRESULT dsresult;
140     DSBUFFERDESC dsbuffer_desc;
141     int i;
142
143     msg_Dbg( p_aout, "Open" );
144
145    /* Allocate structure */
146     p_aout->output.p_sys = malloc( sizeof( aout_sys_t ) );
147     if( p_aout->output.p_sys == NULL )
148     {
149         msg_Err( p_aout, "out of memory" );
150         return VLC_EGENERIC;
151     }
152
153     /* Initialize some variables */
154     p_aout->output.p_sys->p_dsobject = NULL;
155     p_aout->output.p_sys->p_dsbuffer_primary = NULL;
156     p_aout->output.p_sys->p_dsbuffer = NULL;
157     p_aout->output.p_sys->p_dsnotify = NULL;
158     p_aout->output.p_sys->p_notif = NULL;
159     p_aout->output.p_sys->b_playing = 0;
160
161     p_aout->output.pf_play = Play;
162     aout_VolumeSoftInit( p_aout );
163
164     /* Initialise DirectSound */
165     if( DirectxInitDSound( p_aout ) )
166     {
167         msg_Err( p_aout, "cannot initialize DirectSound" );
168         goto error;
169     }
170
171     /* Obtain (not create) Direct Sound primary buffer */
172     memset( &dsbuffer_desc, 0, sizeof(DSBUFFERDESC) );
173     dsbuffer_desc.dwSize = sizeof(DSBUFFERDESC);
174     dsbuffer_desc.dwFlags = DSBCAPS_PRIMARYBUFFER;
175     msg_Warn( p_aout, "create direct sound primary buffer" );
176     dsresult = IDirectSound_CreateSoundBuffer(p_aout->output.p_sys->p_dsobject,
177                                      &dsbuffer_desc,
178                                      &p_aout->output.p_sys->p_dsbuffer_primary,
179                                      NULL);
180     if( dsresult != DS_OK )
181     {
182         msg_Err( p_aout, "cannot create direct sound primary buffer" );
183         goto error;
184     }
185
186     /* Now we need to setup DirectSound play notification */
187     p_aout->output.p_sys->p_notif =
188         vlc_object_create( p_aout, sizeof(notification_thread_t) );
189     p_aout->output.p_sys->p_notif->p_aout = p_aout;
190
191     /* first we need to create the notification events */
192     for( i = 0; i < FRAMES_NUM; i++ )
193         p_aout->output.p_sys->p_notif->p_events[i].hEventNotify =
194             CreateEvent( NULL, FALSE, FALSE, NULL );
195
196     /* then create a new secondary buffer */
197     p_aout->output.output.i_format = VLC_FOURCC('f','l','3','2');
198     if( DirectxCreateSecondaryBuffer( p_aout ) )
199     {
200         msg_Err( p_aout, "cannot create WAVE_FORMAT_IEEE_FLOAT buffer" );
201
202         p_aout->output.output.i_format = VLC_FOURCC('s','1','6','l');
203         if( DirectxCreateSecondaryBuffer( p_aout ) )
204         {
205             msg_Err( p_aout, "cannot create WAVE_FORMAT_PCM buffer" );
206             return 1;
207         }
208     }
209
210     /* then launch the notification thread */
211     msg_Dbg( p_aout, "creating DirectSoundThread" );
212     if( vlc_thread_create( p_aout->output.p_sys->p_notif,
213                            "DirectSound Notification Thread",
214                            DirectSoundThread,
215                            THREAD_PRIORITY_TIME_CRITICAL, 1 ) )
216     {
217         msg_Err( p_aout, "cannot create DirectSoundThread" );
218         goto error;
219     }
220
221     vlc_object_attach( p_aout->output.p_sys->p_notif, p_aout );
222
223     return 0;
224
225  error:
226     CloseAudio( VLC_OBJECT(p_aout) );
227     return VLC_EGENERIC;
228 }
229
230 /*****************************************************************************
231  * Play: we'll start playing the directsound buffer here because at least here
232  *       we know the first buffer has been put in the aout fifo and we also
233  *       know its date.
234  *****************************************************************************/
235 static void Play( aout_instance_t *p_aout )
236 {
237     if( !p_aout->output.p_sys->b_playing )
238     {
239         aout_buffer_t *p_buffer;
240
241         p_aout->output.p_sys->b_playing = 1;
242
243         /* get the playing date of the first aout buffer */
244         p_aout->output.p_sys->p_notif->start_date =
245             aout_FifoFirstDate( p_aout, &p_aout->output.fifo );
246
247         /* fill in the first samples */
248         p_buffer = aout_FifoPop( p_aout, &p_aout->output.fifo );
249         DirectxFillBuffer( p_aout, 0, p_buffer );
250
251         /* wake up the audio output thread */
252         SetEvent( p_aout->output.p_sys->p_notif->p_events[0].hEventNotify );
253     }
254 }
255
256 /*****************************************************************************
257  * CloseAudio: close the audio device
258  *****************************************************************************/
259 static void CloseAudio( vlc_object_t *p_this )
260 {
261     aout_instance_t * p_aout = (aout_instance_t *)p_this;
262
263     msg_Dbg( p_aout, "Close" );
264
265     /* kill the position notification thread, if any */
266     if( p_aout->output.p_sys->p_notif )
267     {
268         vlc_object_detach( p_aout->output.p_sys->p_notif );
269         if( p_aout->output.p_sys->p_notif->b_thread )
270         {
271             p_aout->output.p_sys->p_notif->b_die = 1;
272
273             if( !p_aout->output.p_sys->b_playing )
274                 /* wake up the audio thread */
275                 SetEvent(
276                     p_aout->output.p_sys->p_notif->p_events[0].hEventNotify );
277
278             vlc_thread_join( p_aout->output.p_sys->p_notif );
279         }
280         vlc_object_destroy( p_aout->output.p_sys->p_notif );
281     }
282
283     /* release the secondary buffer */
284     DirectxDestroySecondaryBuffer( p_aout );
285
286     /* then release the primary buffer */
287     if( p_aout->output.p_sys->p_dsbuffer_primary )
288         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer_primary );
289
290     /* finally release the DirectSound object */
291     if( p_aout->output.p_sys->p_dsobject )
292         IDirectSound_Release( p_aout->output.p_sys->p_dsobject );
293     
294     /* free DSOUND.DLL */
295     if( p_aout->output.p_sys->hdsound_dll )
296        FreeLibrary( p_aout->output.p_sys->hdsound_dll );
297
298     free( p_aout->output.p_sys );
299 }
300
301 /*****************************************************************************
302  * DirectxInitDSound: handle all the gory details of DirectSound initialisation
303  *****************************************************************************/
304 static int DirectxInitDSound( aout_instance_t *p_aout )
305 {
306     HRESULT (WINAPI *OurDirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
307
308     p_aout->output.p_sys->hdsound_dll = LoadLibrary("DSOUND.DLL");
309     if( p_aout->output.p_sys->hdsound_dll == NULL )
310     {
311         msg_Warn( p_aout, "cannot open DSOUND.DLL" );
312         goto error;
313     }
314
315     OurDirectSoundCreate = (void *)GetProcAddress(
316                                            p_aout->output.p_sys->hdsound_dll,
317                                            "DirectSoundCreate" );
318     if( OurDirectSoundCreate == NULL )
319     {
320         msg_Warn( p_aout, "GetProcAddress FAILED" );
321         goto error;
322     }
323
324     /* Create the direct sound object */
325     if( OurDirectSoundCreate( NULL, &p_aout->output.p_sys->p_dsobject, NULL )
326         != DS_OK )
327     {
328         msg_Warn( p_aout, "cannot create a direct sound device" );
329         goto error;
330     }
331
332     /* Set DirectSound Cooperative level, ie what control we want over Windows
333      * sound device. In our case, DSSCL_EXCLUSIVE means that we can modify the
334      * settings of the primary buffer, but also that only the sound of our
335      * application will be hearable when it will have the focus.
336      * !!! (this is not really working as intended yet because to set the
337      * cooperative level you need the window handle of your application, and
338      * I don't know of any easy way to get it. Especially since we might play
339      * sound without any video, and so what window handle should we use ???
340      * The hack for now is to use the Desktop window handle - it seems to be
341      * working */
342     if( IDirectSound_SetCooperativeLevel( p_aout->output.p_sys->p_dsobject,
343                                           GetDesktopWindow(),
344                                           DSSCL_EXCLUSIVE) )
345     {
346         msg_Warn( p_aout, "cannot set direct sound cooperative level" );
347     }
348
349     return 0;
350
351  error:
352     p_aout->output.p_sys->p_dsobject = NULL;
353     if( p_aout->output.p_sys->hdsound_dll )
354     {
355         FreeLibrary( p_aout->output.p_sys->hdsound_dll );
356         p_aout->output.p_sys->hdsound_dll = NULL;
357     }
358     return 1;
359
360 }
361
362 /*****************************************************************************
363  * DirectxCreateSecondaryBuffer
364  *****************************************************************************
365  * This function creates the buffer we'll use to play audio.
366  * In DirectSound there are two kinds of buffers:
367  * - the primary buffer: which is the actual buffer that the soundcard plays
368  * - the secondary buffer(s): these buffers are the one actually used by
369  *    applications and DirectSound takes care of mixing them into the primary.
370  *
371  * Once you create a secondary buffer, you cannot change its format anymore so
372  * you have to release the current and create another one.
373  *****************************************************************************/
374 static int DirectxCreateSecondaryBuffer( aout_instance_t *p_aout )
375 {
376     WAVEFORMATEX         waveformat;
377     DSBUFFERDESC         dsbdesc;
378     DSBCAPS              dsbcaps;
379     int                  i_nb_channels, i;
380
381     i_nb_channels = aout_FormatNbChannels( &p_aout->output.output );
382     if ( i_nb_channels >= 2 )
383     {
384         i_nb_channels = 2;
385         p_aout->output.output.i_physical_channels =
386             AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
387     }
388     else
389     {
390         i_nb_channels = 1;
391         p_aout->output.output.i_physical_channels =
392             AOUT_CHAN_CENTER;
393     }
394
395     /* First set the buffer format */
396     memset( &waveformat, 0, sizeof(WAVEFORMATEX) );
397     switch( p_aout->output.output.i_format )
398     {
399     case VLC_FOURCC('s','1','6','l'):
400         waveformat.wFormatTag     = WAVE_FORMAT_PCM;
401         waveformat.wBitsPerSample = 16;
402         break;
403     case VLC_FOURCC('f','l','3','2'):
404         waveformat.wFormatTag     = WAVE_FORMAT_IEEE_FLOAT;
405         waveformat.wBitsPerSample = sizeof(float) * 8;
406         break;
407     }
408     waveformat.nChannels       = i_nb_channels;
409     waveformat.nSamplesPerSec  = p_aout->output.output.i_rate;
410     waveformat.nBlockAlign     = waveformat.wBitsPerSample / 8 *
411                                  waveformat.nChannels;
412     waveformat.nAvgBytesPerSec = waveformat.nSamplesPerSec *
413                                      waveformat.nBlockAlign;
414
415     aout_FormatPrepare( &p_aout->output.output );
416
417     /* Then fill in the descriptor */
418     memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
419     dsbdesc.dwSize = sizeof(DSBUFFERDESC);
420     dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2/* Better position accuracy */
421                     | DSBCAPS_CTRLPOSITIONNOTIFY     /* We need notification */
422                     | DSBCAPS_GLOBALFOCUS;      /* Allows background playing */
423     dsbdesc.dwBufferBytes = FRAME_SIZE * FRAMES_NUM           /* buffer size */
424                             * p_aout->output.output.i_bytes_per_frame;
425     dsbdesc.lpwfxFormat = &waveformat;
426  
427     if( IDirectSound_CreateSoundBuffer( p_aout->output.p_sys->p_dsobject,
428                                         &dsbdesc,
429                                         &p_aout->output.p_sys->p_dsbuffer,
430                                         NULL) != DS_OK )
431     {
432         msg_Warn( p_aout, "cannot create direct sound secondary buffer" );
433         goto error;
434     }
435
436     /* backup the size of a frame */
437     p_aout->output.p_sys->p_notif->i_frame_size = FRAME_SIZE *
438         p_aout->output.output.i_bytes_per_frame;
439
440     memset(&dsbcaps, 0, sizeof(DSBCAPS));
441     dsbcaps.dwSize = sizeof(DSBCAPS);
442     IDirectSoundBuffer_GetCaps( p_aout->output.p_sys->p_dsbuffer, &dsbcaps  );
443     msg_Dbg( p_aout, "requested %li bytes buffer and got %li bytes.",
444              FRAMES_NUM * p_aout->output.p_sys->p_notif->i_frame_size,
445              dsbcaps.dwBufferBytes );
446
447     /* Now the secondary buffer is created, we need to setup its position
448      * notification */
449     for( i = 0; i < FRAMES_NUM; i++ )
450     {
451         p_aout->output.p_sys->p_notif->p_events[i].dwOffset = i *
452             p_aout->output.p_sys->p_notif->i_frame_size;
453
454         p_aout->output.p_sys->p_notif->i_frame_status[i] = FRAME_EMPTY;
455     }
456
457     /* Get the IDirectSoundNotify interface */
458     if FAILED( IDirectSoundBuffer_QueryInterface(
459                                 p_aout->output.p_sys->p_dsbuffer,
460                                 &IID_IDirectSoundNotify,
461                                 (LPVOID *)&p_aout->output.p_sys->p_dsnotify ) )
462     {
463         msg_Err( p_aout, "cannot get Notify interface" );
464         goto error;
465     }
466         
467     if FAILED( IDirectSoundNotify_SetNotificationPositions(
468                                     p_aout->output.p_sys->p_dsnotify,
469                                     FRAMES_NUM,
470                                     p_aout->output.p_sys->p_notif->p_events ) )
471     {
472         msg_Err( p_aout, "cannot set position Notification" );
473         goto error;
474     }
475
476     p_aout->output.i_nb_samples = FRAME_SIZE;
477
478     return 0;
479
480  error:
481     if( p_aout->output.p_sys->p_dsbuffer )
482     {
483         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
484         p_aout->output.p_sys->p_dsbuffer = NULL;
485     }
486     if( p_aout->output.p_sys->p_dsnotify )
487     {
488         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
489         p_aout->output.p_sys->p_dsnotify = NULL;
490     }
491     return VLC_EGENERIC;
492 }
493
494 /*****************************************************************************
495  * DirectxCreateSecondaryBuffer
496  *****************************************************************************
497  * This function destroys the secondary buffer.
498  *****************************************************************************/
499 static void DirectxDestroySecondaryBuffer( aout_instance_t *p_aout )
500 {
501     /* make sure the buffer isn't playing */
502     if( p_aout->output.p_sys->p_dsbuffer )
503         IDirectSoundBuffer_Stop( p_aout->output.p_sys->p_dsbuffer );
504
505     if( p_aout->output.p_sys->p_dsnotify )
506     {
507         IDirectSoundNotify_Release( p_aout->output.p_sys->p_dsnotify );
508         p_aout->output.p_sys->p_dsnotify = NULL;
509     }
510
511     if( p_aout->output.p_sys->p_dsbuffer )
512     {
513         IDirectSoundBuffer_Release( p_aout->output.p_sys->p_dsbuffer );
514         p_aout->output.p_sys->p_dsbuffer = NULL;
515     }
516 }
517
518 /*****************************************************************************
519  * DirectxFillBuffer: Fill in one of the direct sound frame buffers.
520  *****************************************************************************
521  * Returns VLC_SUCCESS on success.
522  *****************************************************************************/
523 static int DirectxFillBuffer( aout_instance_t *p_aout, int i_frame,
524                               aout_buffer_t *p_buffer )
525 {
526     notification_thread_t *p_notif = p_aout->output.p_sys->p_notif;
527     void *p_write_position, *p_wrap_around;
528     long l_bytes1, l_bytes2;
529     HRESULT dsresult;
530
531     /* Before copying anything, we have to lock the buffer */
532     dsresult = IDirectSoundBuffer_Lock(
533                 p_aout->output.p_sys->p_dsbuffer,               /* DS buffer */
534                 i_frame * p_notif->i_frame_size,             /* Start offset */
535                 p_notif->i_frame_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_frame * p_notif->i_frame_size,
547                                p_notif->i_frame_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         if( p_buffer ) aout_BufferFree( p_buffer );
558         return VLC_EGENERIC;
559     }
560
561     if ( p_buffer != NULL )
562     {
563         p_aout->p_vlc->pf_memcpy( p_write_position, p_buffer->p_buffer,
564                                   l_bytes1 );
565         aout_BufferFree( p_buffer );
566     }
567     else
568         memset( p_write_position, 0, l_bytes1 );
569
570     /* Now the data has been copied, unlock the buffer */
571     IDirectSoundBuffer_Unlock( p_aout->output.p_sys->p_dsbuffer,
572                                p_write_position, l_bytes1,
573                                p_wrap_around, l_bytes2 );
574
575     return VLC_SUCCESS;
576 }
577
578 /*****************************************************************************
579  * DirectSoundThread: this thread will capture play notification events. 
580  *****************************************************************************
581  * We use this thread to emulate a callback mechanism. The thread probes for
582  * event notification and fills up the DS secondary buffer when needed.
583  *****************************************************************************/
584 static void DirectSoundThread( notification_thread_t *p_notif )
585 {
586     HANDLE  notification_events[FRAMES_NUM];
587     HRESULT dsresult;
588     aout_instance_t *p_aout = p_notif->p_aout;
589     int i, i_which_frame, i_last_frame, i_next_frame;
590     mtime_t mtime;
591
592     for( i = 0; i < FRAMES_NUM; i++ )
593         notification_events[i] = p_notif->p_events[i].hEventNotify;
594
595     /* Tell the main thread that we are ready */
596     vlc_thread_ready( p_notif );
597
598     msg_Dbg( p_notif, "DirectSoundThread ready" );
599
600     /* Wait here until Play() is called */
601     WaitForSingleObject( notification_events[0], INFINITE );
602
603     if( !p_notif->b_die )
604     {
605         mwait( p_notif->start_date - AOUT_PTS_TOLERANCE / 2 );
606
607         /* start playing the buffer */
608         dsresult = IDirectSoundBuffer_Play( p_aout->output.p_sys->p_dsbuffer,
609                                         0,                         /* Unused */
610                                         0,                         /* Unused */
611                                         DSBPLAY_LOOPING );          /* Flags */
612         if( dsresult == DSERR_BUFFERLOST )
613         {
614             IDirectSoundBuffer_Restore( p_aout->output.p_sys->p_dsbuffer );
615             dsresult = IDirectSoundBuffer_Play(
616                                             p_aout->output.p_sys->p_dsbuffer,
617                                             0,                     /* Unused */
618                                             0,                     /* Unused */
619                                             DSBPLAY_LOOPING );      /* Flags */
620         }
621         if( dsresult != DS_OK )
622         {
623             msg_Err( p_aout, "cannot start playing buffer" );
624         }
625     }
626
627     while( !p_notif->b_die )
628     {
629         aout_buffer_t *p_buffer;
630         long l_latency;
631
632         /* wait for the position notification */
633         i_which_frame = WaitForMultipleObjects( FRAMES_NUM,
634                                                 notification_events, 0,
635                                                 INFINITE ) - WAIT_OBJECT_0;
636
637         if( p_notif->b_die )
638             break;
639
640         mtime = mdate();
641
642         /* We take into account the current latency */
643         if( IDirectSoundBuffer_GetCurrentPosition(
644                 p_aout->output.p_sys->p_dsbuffer,
645                 &l_latency, NULL ) == DS_OK )
646         {
647             if( l_latency > (i_which_frame * FRAME_SIZE)
648                   && l_latency < ((i_which_frame+1) * FRAME_SIZE) )
649             {
650                 l_latency = - ( l_latency /
651                                 p_aout->output.output.i_bytes_per_frame %
652                                 FRAME_SIZE );
653             }
654             else
655             {
656                 l_latency = FRAME_SIZE - ( l_latency /
657                                       p_aout->output.output.i_bytes_per_frame %
658                                       FRAME_SIZE );
659             }
660         }
661         else
662         {
663             l_latency = 0;
664         }
665
666         /* Mark last frame as empty */
667         i_last_frame = (i_which_frame + FRAMES_NUM -1) % FRAMES_NUM;
668         i_next_frame = (i_which_frame + 1) % FRAMES_NUM;
669         p_notif->i_frame_status[i_last_frame] = FRAME_EMPTY;
670
671         /* Try to fill in as many frame buffers as possible */
672         for( i = i_next_frame; (i % FRAMES_NUM) != i_which_frame; i++ )
673         {
674
675             /* Check if frame buf is already filled */
676             if( p_notif->i_frame_status[i % FRAMES_NUM] == FRAME_QUEUED )
677                 continue;
678
679             p_buffer = aout_OutputNextBuffer( p_aout,
680                 mtime + 1000000 / p_aout->output.output.i_rate *
681                 ((i - i_next_frame + 1) * FRAME_SIZE + l_latency), VLC_FALSE );
682
683             /* If there is no audio data available and we have some buffered
684              * already, then just wait for the next time */
685             if( !p_buffer && (i != i_next_frame) )
686             {
687                 //msg_Err( p_aout, "only %i frame buffers filled!",
688                 //         i - i_next_frame );
689                 break;
690             }
691
692             if( DirectxFillBuffer( p_aout, (i%FRAMES_NUM), p_buffer )
693                 != VLC_SUCCESS )
694                 break;
695
696             /* Mark the frame buffer as QUEUED */
697             p_notif->i_frame_status[i%FRAMES_NUM] = FRAME_QUEUED;
698         }
699
700     }
701
702     /* free the events */
703     for( i = 0; i < FRAMES_NUM; i++ )
704         CloseHandle( notification_events[i] );
705
706     msg_Dbg( p_notif, "DirectSoundThread exiting" );
707 }