Update to MPlayer SVN rev 28973 and FFmpeg SVN rev 17997.
[vaapi:challenzhous-mplayer.git] / libao2 / ao_win32.c
1 /*
2  * Windows waveOut interface
3  *
4  * Copyright (c) 2002 - 2004 Sascha Sommer <saschasommer@freenet.de>
5  *
6  * This file is part of MPlayer.
7  *
8  * MPlayer is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * MPlayer is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with MPlayer; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <windows.h>
26 #include <mmsystem.h>
27
28 #include "config.h"
29 #include "libaf/af_format.h"
30 #include "audio_out.h"
31 #include "audio_out_internal.h"
32 #include "mp_msg.h"
33 #include "libvo/fastmemcpy.h"
34 #include "osdep/timer.h"
35
36 #define WAVE_FORMAT_DOLBY_AC3_SPDIF 0x0092
37 #define WAVE_FORMAT_EXTENSIBLE      0xFFFE
38
39 static const  GUID KSDATAFORMAT_SUBTYPE_PCM = {
40         0x1,0x0000,0x0010,{0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71}
41 };
42
43 typedef struct {
44   WAVEFORMATEX  Format;
45   union {
46     WORD  wValidBitsPerSample;
47     WORD  wSamplesPerBlock;
48     WORD  wReserved;
49   } Samples;
50   DWORD  dwChannelMask;
51   GUID  SubFormat;
52 } WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;
53
54 #define SPEAKER_FRONT_LEFT              0x1
55 #define SPEAKER_FRONT_RIGHT             0x2
56 #define SPEAKER_FRONT_CENTER            0x4
57 #define SPEAKER_LOW_FREQUENCY           0x8
58 #define SPEAKER_BACK_LEFT               0x10
59 #define SPEAKER_BACK_RIGHT              0x20
60 #define SPEAKER_FRONT_LEFT_OF_CENTER    0x40
61 #define SPEAKER_FRONT_RIGHT_OF_CENTER   0x80
62 #define SPEAKER_BACK_CENTER             0x100
63 #define SPEAKER_SIDE_LEFT               0x200
64 #define SPEAKER_SIDE_RIGHT              0x400
65 #define SPEAKER_TOP_CENTER              0x800
66 #define SPEAKER_TOP_FRONT_LEFT          0x1000
67 #define SPEAKER_TOP_FRONT_CENTER        0x2000
68 #define SPEAKER_TOP_FRONT_RIGHT         0x4000
69 #define SPEAKER_TOP_BACK_LEFT           0x8000
70 #define SPEAKER_TOP_BACK_CENTER         0x10000
71 #define SPEAKER_TOP_BACK_RIGHT          0x20000
72
73 static const int channel_mask[] = {
74   SPEAKER_FRONT_LEFT   | SPEAKER_FRONT_RIGHT  | SPEAKER_LOW_FREQUENCY,
75   SPEAKER_FRONT_LEFT   | SPEAKER_FRONT_CENTER | SPEAKER_FRONT_RIGHT  | SPEAKER_LOW_FREQUENCY,
76   SPEAKER_FRONT_LEFT   | SPEAKER_FRONT_CENTER | SPEAKER_FRONT_RIGHT  | SPEAKER_BACK_CENTER  | SPEAKER_LOW_FREQUENCY,
77   SPEAKER_FRONT_LEFT   | SPEAKER_FRONT_CENTER | SPEAKER_FRONT_RIGHT  | SPEAKER_BACK_LEFT    | SPEAKER_BACK_RIGHT     | SPEAKER_LOW_FREQUENCY
78 };
79
80
81
82 #define SAMPLESIZE   1024
83 #define BUFFER_SIZE  4096
84 #define BUFFER_COUNT 16
85
86
87 static WAVEHDR*     waveBlocks;         //pointer to our ringbuffer memory
88 static HWAVEOUT     hWaveOut;           //handle to the waveout device
89 static unsigned int buf_write=0;
90 static volatile int buf_read=0;
91
92
93 static const ao_info_t info =
94 {
95         "Windows waveOut audio output",
96         "win32",
97         "Sascha Sommer <saschasommer@freenet.de>",
98         ""
99 };
100
101 LIBAO_EXTERN(win32)
102
103 static void CALLBACK waveOutProc(HWAVEOUT hWaveOut,UINT uMsg,DWORD dwInstance,
104     DWORD dwParam1,DWORD dwParam2)
105 {
106         if(uMsg != WOM_DONE)
107         return;
108         buf_read = (buf_read + 1) % BUFFER_COUNT;
109 }
110
111 // to set/get/query special features/parameters
112 static int control(int cmd,void *arg)
113 {
114         DWORD volume;
115         switch (cmd)
116         {
117                 case AOCONTROL_GET_VOLUME:
118                 {
119                         ao_control_vol_t* vol = (ao_control_vol_t*)arg;
120                         waveOutGetVolume(hWaveOut,&volume);
121                         vol->left = (float)(LOWORD(volume)/655.35);
122                         vol->right = (float)(HIWORD(volume)/655.35);
123                         mp_msg(MSGT_AO, MSGL_DBG2,"ao_win32: volume left:%f volume right:%f\n",vol->left,vol->right);
124                         return CONTROL_OK;
125                 }
126                 case AOCONTROL_SET_VOLUME:
127                 {
128                         ao_control_vol_t* vol = (ao_control_vol_t*)arg;
129                         volume = MAKELONG(vol->left*655.35,vol->right*655.35);
130                         waveOutSetVolume(hWaveOut,volume);
131                         return CONTROL_OK;
132                 }
133         }
134     return -1;
135 }
136
137 // open & setup audio device
138 // return: 1=success 0=fail
139 static int init(int rate,int channels,int format,int flags)
140 {
141         WAVEFORMATEXTENSIBLE wformat;
142         MMRESULT result;
143         unsigned char* buffer;
144         int i;
145
146         switch(format){
147                 case AF_FORMAT_AC3:
148                 case AF_FORMAT_S24_LE:
149                 case AF_FORMAT_S16_LE:
150                 case AF_FORMAT_U8:
151                         break;
152                 default:
153                         mp_msg(MSGT_AO, MSGL_V,"ao_win32: format %s not supported defaulting to Signed 16-bit Little-Endian\n",af_fmt2str_short(format));
154                         format=AF_FORMAT_S16_LE;
155         }
156
157         // FIXME multichannel mode is buggy
158         if(channels > 2)
159                 channels = 2;
160
161         //fill global ao_data
162         ao_data.channels=channels;
163         ao_data.samplerate=rate;
164         ao_data.format=format;
165         ao_data.bps=channels*rate;
166         if(format != AF_FORMAT_U8 && format != AF_FORMAT_S8)
167           ao_data.bps*=2;
168         ao_data.outburst = BUFFER_SIZE;
169         if(ao_data.buffersize==-1)
170         {
171                 ao_data.buffersize=af_fmt2bits(format)/8;
172         ao_data.buffersize*= channels;
173                 ao_data.buffersize*= SAMPLESIZE;
174         }
175         mp_msg(MSGT_AO, MSGL_V,"ao_win32: Samplerate:%iHz Channels:%i Format:%s\n",rate, channels, af_fmt2str_short(format));
176     mp_msg(MSGT_AO, MSGL_V,"ao_win32: Buffersize:%d\n",ao_data.buffersize);
177
178         //fill waveformatex
179     ZeroMemory( &wformat, sizeof(WAVEFORMATEXTENSIBLE));
180     wformat.Format.cbSize          = (channels>2)?sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX):0;
181     wformat.Format.nChannels       = channels;
182     wformat.Format.nSamplesPerSec  = rate;
183     if(format == AF_FORMAT_AC3)
184     {
185         wformat.Format.wFormatTag      = WAVE_FORMAT_DOLBY_AC3_SPDIF;
186         wformat.Format.wBitsPerSample  = 16;
187         wformat.Format.nBlockAlign     = 4;
188     }
189     else
190     {
191         wformat.Format.wFormatTag      = (channels>2)?WAVE_FORMAT_EXTENSIBLE:WAVE_FORMAT_PCM;
192         wformat.Format.wBitsPerSample  = af_fmt2bits(format);
193         wformat.Format.nBlockAlign     = wformat.Format.nChannels * (wformat.Format.wBitsPerSample >> 3);
194     }
195         if(channels>2)
196         {
197         wformat.dwChannelMask = channel_mask[channels-3];
198         wformat.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
199             wformat.Samples.wValidBitsPerSample=af_fmt2bits(format);
200     }
201
202     wformat.Format.nAvgBytesPerSec = wformat.Format.nSamplesPerSec * wformat.Format.nBlockAlign;
203  
204     //open sound device
205     //WAVE_MAPPER always points to the default wave device on the system
206     result = waveOutOpen(&hWaveOut,WAVE_MAPPER,(WAVEFORMATEX*)&wformat,(DWORD_PTR)waveOutProc,0,CALLBACK_FUNCTION);
207         if(result == WAVERR_BADFORMAT)
208         {
209                 mp_msg(MSGT_AO, MSGL_ERR,"ao_win32: format not supported switching to default\n");
210         ao_data.channels = wformat.Format.nChannels = 2;
211             ao_data.samplerate = wformat.Format.nSamplesPerSec = 44100;
212             ao_data.format = AF_FORMAT_S16_LE;
213                 ao_data.bps=ao_data.channels * ao_data.samplerate*2;
214             wformat.Format.wBitsPerSample=16;
215         wformat.Format.wFormatTag=WAVE_FORMAT_PCM;
216                 wformat.Format.nBlockAlign     = wformat.Format.nChannels * (wformat.Format.wBitsPerSample >> 3);
217         wformat.Format.nAvgBytesPerSec = wformat.Format.nSamplesPerSec * wformat.Format.nBlockAlign;
218                 ao_data.buffersize=(wformat.Format.wBitsPerSample>>3)*wformat.Format.nChannels*SAMPLESIZE;
219         result = waveOutOpen(&hWaveOut,WAVE_MAPPER,(WAVEFORMATEX*)&wformat,(DWORD_PTR)waveOutProc,0,CALLBACK_FUNCTION);
220         }
221         if(result != MMSYSERR_NOERROR)
222         {
223                 mp_msg(MSGT_AO, MSGL_ERR,"ao_win32: unable to open wave mapper device (result=%i)\n",result);
224                 return 0;
225     }
226         //allocate buffer memory as one big block
227         buffer = calloc(BUFFER_COUNT, BUFFER_SIZE + sizeof(WAVEHDR));
228     //and setup pointers to each buffer
229     waveBlocks = (WAVEHDR*)buffer;
230     buffer += sizeof(WAVEHDR) * BUFFER_COUNT;
231     for(i = 0; i < BUFFER_COUNT; i++) {
232         waveBlocks[i].lpData = buffer;
233         buffer += BUFFER_SIZE;
234     }
235     buf_write=0;
236     buf_read=0;
237
238     return 1;
239 }
240
241 // close audio device
242 static void uninit(int immed)
243 {
244     if(!immed)
245         usec_sleep(get_delay() * 1000 * 1000);
246     else
247         waveOutReset(hWaveOut);
248     while (waveOutClose(hWaveOut) == WAVERR_STILLPLAYING) usec_sleep(0);
249         mp_msg(MSGT_AO, MSGL_V,"waveOut device closed\n");
250     free(waveBlocks);
251         mp_msg(MSGT_AO, MSGL_V,"buffer memory freed\n");
252 }
253
254 // stop playing and empty buffers (for seeking/pause)
255 static void reset(void)
256 {
257         waveOutReset(hWaveOut);
258         buf_write=0;
259         buf_read=0;
260 }
261
262 // stop playing, keep buffers (for pause)
263 static void audio_pause(void)
264 {
265     waveOutPause(hWaveOut);
266 }
267
268 // resume playing, after audio_pause()
269 static void audio_resume(void)
270 {
271         waveOutRestart(hWaveOut);
272 }
273
274 // return: how many bytes can be played without blocking
275 static int get_space(void)
276 {
277     int free = buf_read - buf_write - 1;
278     if (free < 0) free += BUFFER_COUNT;
279     return free * BUFFER_SIZE;
280 }
281
282 //writes data into buffer, based on ringbuffer code in ao_sdl.c
283 static int write_waveOutBuffer(unsigned char* data,int len){
284   WAVEHDR* current;
285   int len2=0;
286   int x;
287   while(len>0){
288     int buf_next = (buf_write + 1) % BUFFER_COUNT;
289     current = &waveBlocks[buf_write];
290     if(buf_next == buf_read) break;
291     //unprepare the header if it is prepared
292         if(current->dwFlags & WHDR_PREPARED)
293            waveOutUnprepareHeader(hWaveOut, current, sizeof(WAVEHDR));
294         x=BUFFER_SIZE;
295     if(x>len) x=len;
296     fast_memcpy(current->lpData,data+len2,x);
297     len2+=x; len-=x;
298         //prepare header and write data to device
299         current->dwBufferLength = x;
300         waveOutPrepareHeader(hWaveOut, current, sizeof(WAVEHDR));
301         waveOutWrite(hWaveOut, current, sizeof(WAVEHDR));
302
303        buf_write = buf_next;
304   }
305   return len2;
306 }
307
308 // plays 'len' bytes of 'data'
309 // it should round it down to outburst*n
310 // return: number of bytes played
311 static int play(void* data,int len,int flags)
312 {
313         if (!(flags & AOPLAY_FINAL_CHUNK))
314         len = (len/ao_data.outburst)*ao_data.outburst;
315         return write_waveOutBuffer(data,len);
316 }
317
318 // return: delay in seconds between first and last sample in buffer
319 static float get_delay(void)
320 {
321         int used = buf_write - buf_read;
322         if (used < 0) used += BUFFER_COUNT;
323         return (float)(used * BUFFER_SIZE + ao_data.buffersize)/(float)ao_data.bps;
324 }