]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - snd_alsa.c
TE_EXPLOSION2: don't crash on colorLength == 0.
[xonotic/darkplaces.git] / snd_alsa.c
1 /*
2         Copyright (C) 2006  Mathieu Olivier
3
4         This program is free software; you can redistribute it and/or
5         modify it under the terms of the GNU General Public License
6         as published by the Free Software Foundation; either version 2
7         of the License, or (at your option) any later version.
8
9         This program is distributed in the hope that it will be useful,
10         but WITHOUT ANY WARRANTY; without even the implied warranty of
11         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13         See the GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to:
17
18                 Free Software Foundation, Inc.
19                 59 Temple Place - Suite 330
20                 Boston, MA  02111-1307, USA
21
22 */
23
24 // ALSA module, used by Linux
25
26 #include "quakedef.h"
27
28 #include <alsa/asoundlib.h>
29
30 #include "snd_main.h"
31
32
33 #define NB_PERIODS 4
34
35 static snd_pcm_t* pcm_handle = NULL;
36 static snd_pcm_sframes_t expected_delay = 0;
37 static unsigned int alsasoundtime;
38
39 static snd_seq_t* seq_handle = NULL;
40
41 /*
42 ====================
43 SndSys_Init
44
45 Create "snd_renderbuffer" with the proper sound format if the call is successful
46 May return a suggested format if the requested format isn't available
47 ====================
48 */
49 qboolean SndSys_Init (const snd_format_t* requested, snd_format_t* suggested)
50 {
51         const char* pcm_name, *seq_name;
52         int i, err, seq_client, seq_port;
53         snd_pcm_hw_params_t* hw_params = NULL;
54         snd_pcm_format_t snd_pcm_format;
55         snd_pcm_uframes_t buffer_size;
56
57         Con_Print ("SndSys_Init: using the ALSA module\n");
58
59         seq_name = NULL;
60 // COMMANDLINEOPTION: Linux ALSA Sound: -sndseqin <client>:<port> selects which sequencer port to use for input, by default no sequencer port is used (MIDI note events from that port get mapped to MIDINOTE<n> keys that can be bound)
61         i = COM_CheckParm ("-sndseqin"); // TODO turn this into a cvar, maybe
62         if (i != 0 && i < com_argc - 1)
63                 seq_name = com_argv[i + 1];
64         if(seq_name)
65         {
66                 seq_client = atoi(seq_name);
67                 seq_port = 0;
68                 if(strchr(seq_name, ':'))
69                         seq_port = atoi(strchr(seq_name, ':') + 1);
70                 Con_Printf ("SndSys_Init: seq input port has been set to \"%d:%d\". Enabling sequencer input...\n", seq_client, seq_port);
71                 err = snd_seq_open (&seq_handle, "default", SND_SEQ_OPEN_INPUT, 0);
72                 if (err < 0)
73                 {
74                         Con_Print ("SndSys_Init: can't open seq device\n");
75                         goto seqdone;
76                 }
77                 err = snd_seq_set_client_name(seq_handle, gamename);
78                 if (err < 0)
79                 {
80                         Con_Print ("SndSys_Init: can't set name of seq device\n");
81                         goto seqerror;
82                 }
83                 err = snd_seq_create_simple_port(seq_handle, gamename, SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE, SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);
84                 if(err < 0)
85                 {
86                         Con_Print ("SndSys_Init: can't create seq port\n");
87                         goto seqerror;
88                 }
89                 err = snd_seq_connect_from(seq_handle, 0, seq_client, seq_port);
90                 if(err < 0)
91                 {
92                         Con_Printf ("SndSys_Init: can't connect to seq port \"%d:%d\"\n", seq_client, seq_port);
93                         goto seqerror;
94                 }
95                 err = snd_seq_nonblock(seq_handle, 1);
96                 if(err < 0)
97                 {
98                         Con_Print ("SndSys_Init: can't make seq nonblocking\n");
99                         goto seqerror;
100                 }
101
102                 goto seqdone;
103
104 seqerror:
105                 snd_seq_close(seq_handle);
106                 seq_handle = NULL;
107         }
108
109 seqdone:
110         // Check the requested sound format
111         if (requested->width < 1 || requested->width > 2)
112         {
113                 Con_Printf ("SndSys_Init: invalid sound width (%hu)\n",
114                                         requested->width);
115
116                 if (suggested != NULL)
117                 {
118                         memcpy (suggested, requested, sizeof (*suggested));
119
120                         if (requested->width < 1)
121                                 suggested->width = 1;
122                         else
123                                 suggested->width = 2;
124
125                         Con_Printf ("SndSys_Init: suggesting sound width = %hu\n",
126                                                 suggested->width);
127                 }
128
129                 return false;
130     }
131
132         if (pcm_handle != NULL)
133         {
134                 Con_Print ("SndSys_Init: WARNING: Init called before Shutdown!\n");
135                 SndSys_Shutdown ();
136         }
137
138         // Determine the name of the PCM handle we'll use
139         switch (requested->channels)
140         {
141                 case 4:
142                         pcm_name = "surround40";
143                         break;
144                 case 6:
145                         pcm_name = "surround51";
146                         break;
147                 case 8:
148                         pcm_name = "surround71";
149                         break;
150                 default:
151                         pcm_name = "default";
152                         break;
153         }
154 // COMMANDLINEOPTION: Linux ALSA Sound: -sndpcm <devicename> selects which pcm device to use, default is "default"
155         i = COM_CheckParm ("-sndpcm");
156         if (i != 0 && i < com_argc - 1)
157                 pcm_name = com_argv[i + 1];
158
159         // Open the audio device
160         Con_Printf ("SndSys_Init: PCM device is \"%s\"\n", pcm_name);
161         err = snd_pcm_open (&pcm_handle, pcm_name, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
162         if (err < 0)
163         {
164                 Con_Printf ("SndSys_Init: can't open audio device \"%s\" (%s)\n",
165                                         pcm_name, snd_strerror (err));
166                 return false;
167         }
168
169         // Allocate the hardware parameters
170         err = snd_pcm_hw_params_malloc (&hw_params);
171         if (err < 0)
172         {
173                 Con_Printf ("SndSys_Init: can't allocate hardware parameters (%s)\n",
174                                         snd_strerror (err));
175                 goto init_error;
176         }
177         err = snd_pcm_hw_params_any (pcm_handle, hw_params);
178         if (err < 0)
179         {
180                 Con_Printf ("SndSys_Init: can't initialize hardware parameters (%s)\n",
181                                         snd_strerror (err));
182                 goto init_error;
183         }
184
185         // Set the access type
186         err = snd_pcm_hw_params_set_access (pcm_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
187         if (err < 0)
188         {
189                 Con_Printf ("SndSys_Init: can't set access type (%s)\n",
190                                         snd_strerror (err));
191                 goto init_error;
192         }
193
194         // Set the sound width
195         if (requested->width == 1)
196                 snd_pcm_format = SND_PCM_FORMAT_U8;
197         else
198                 snd_pcm_format = SND_PCM_FORMAT_S16;
199         err = snd_pcm_hw_params_set_format (pcm_handle, hw_params, snd_pcm_format);
200         if (err < 0)
201         {
202                 Con_Printf ("SndSys_Init: can't set sound width to %hu (%s)\n",
203                                         requested->width, snd_strerror (err));
204                 goto init_error;
205         }
206
207         // Set the sound channels
208         err = snd_pcm_hw_params_set_channels (pcm_handle, hw_params, requested->channels);
209         if (err < 0)
210         {
211                 Con_Printf ("SndSys_Init: can't set sound channels to %hu (%s)\n",
212                                         requested->channels, snd_strerror (err));
213                 goto init_error;
214         }
215
216         // Set the sound speed
217         err = snd_pcm_hw_params_set_rate (pcm_handle, hw_params, requested->speed, 0);
218         if (err < 0)
219         {
220                 Con_Printf ("SndSys_Init: can't set sound speed to %u (%s)\n",
221                                         requested->speed, snd_strerror (err));
222                 goto init_error;
223         }
224
225         // pick a buffer size that is a power of 2 (by masking off low bits)
226         buffer_size = i = (int)(requested->speed * 0.15f);
227         while (buffer_size & (buffer_size-1))
228                 buffer_size &= (buffer_size-1);
229         // then check if it is the nearest power of 2 and bump it up if not
230         if (i - buffer_size >= buffer_size >> 1)
231                 buffer_size *= 2;
232
233         err = snd_pcm_hw_params_set_buffer_size_near (pcm_handle, hw_params, &buffer_size);
234         if (err < 0)
235         {
236                 Con_Printf ("SndSys_Init: can't set sound buffer size to %lu (%s)\n",
237                                         buffer_size, snd_strerror (err));
238                 goto init_error;
239         }
240
241         // pick a period size near the buffer_size we got from ALSA
242         snd_pcm_hw_params_get_buffer_size (hw_params, &buffer_size);
243         buffer_size /= NB_PERIODS;
244         err = snd_pcm_hw_params_set_period_size_near(pcm_handle, hw_params, &buffer_size, 0);
245         if (err < 0)
246         {
247                 Con_Printf ("SndSys_Init: can't set sound period size to %lu (%s)\n",
248                                         buffer_size, snd_strerror (err));
249                 goto init_error;
250         }
251
252         err = snd_pcm_hw_params (pcm_handle, hw_params);
253         if (err < 0)
254         {
255                 Con_Printf ("SndSys_Init: can't set hardware parameters (%s)\n",
256                                         snd_strerror (err));
257                 goto init_error;
258         }
259
260         snd_pcm_hw_params_free (hw_params);
261
262         snd_renderbuffer = Snd_CreateRingBuffer(requested, 0, NULL);
263         expected_delay = 0;
264         alsasoundtime = 0;
265         if (snd_channellayout.integer == SND_CHANNELLAYOUT_AUTO)
266                 Cvar_SetValueQuick (&snd_channellayout, SND_CHANNELLAYOUT_ALSA);
267
268         return true;
269
270
271 // It's not very clean, but it avoids a lot of duplicated code.
272 init_error:
273
274         if (hw_params != NULL)
275                 snd_pcm_hw_params_free (hw_params);
276
277         snd_pcm_close(pcm_handle);
278         pcm_handle = NULL;
279
280         return false;
281 }
282
283
284 /*
285 ====================
286 SndSys_Shutdown
287
288 Stop the sound card, delete "snd_renderbuffer" and free its other resources
289 ====================
290 */
291 void SndSys_Shutdown (void)
292 {
293         if (seq_handle != NULL)
294         {
295                 snd_seq_close(seq_handle);
296                 seq_handle = NULL;
297         }
298
299         if (pcm_handle != NULL)
300         {
301                 snd_pcm_close(pcm_handle);
302                 pcm_handle = NULL;
303         }
304
305         if (snd_renderbuffer != NULL)
306         {
307                 Mem_Free(snd_renderbuffer->ring);
308                 Mem_Free(snd_renderbuffer);
309                 snd_renderbuffer = NULL;
310         }
311 }
312
313
314 /*
315 ====================
316 SndSys_Recover
317
318 Try to recover from errors
319 ====================
320 */
321 static qboolean SndSys_Recover (int err_num)
322 {
323         int err;
324
325         // We can only do something on underrun ("broken pipe") errors
326         if (err_num != -EPIPE)
327                 return false;
328
329         err = snd_pcm_prepare (pcm_handle);
330         if (err < 0)
331         {
332                 Con_Printf ("SndSys_Recover: unable to recover (%s)\n",
333                                          snd_strerror (err));
334
335                 // TOCHECK: should we stop the playback ?
336
337                 return false;
338         }
339
340         return true;
341 }
342
343
344 /*
345 ====================
346 SndSys_Write
347 ====================
348 */
349 static snd_pcm_sframes_t SndSys_Write (const unsigned char* buffer, unsigned int nbframes)
350 {
351         snd_pcm_sframes_t written;
352
353         written = snd_pcm_writei (pcm_handle, buffer, nbframes);
354         if (written < 0)
355         {
356                 if (developer_insane.integer && vid_activewindow)
357                         Con_DPrintf ("SndSys_Write: audio write returned %ld (%s)!\n",
358                                                  written, snd_strerror (written));
359
360                 if (SndSys_Recover (written))
361                 {
362                         written = snd_pcm_writei (pcm_handle, buffer, nbframes);
363                         if (written < 0)
364                                 Con_DPrintf ("SndSys_Write: audio write failed again (error %ld: %s)!\n",
365                                                          written, snd_strerror (written));
366                 }
367         }
368         if (written > 0)
369         {
370                 snd_renderbuffer->startframe += written;
371                 expected_delay += written;
372         }
373
374         return written;
375 }
376
377
378 /*
379 ====================
380 SndSys_Submit
381
382 Submit the contents of "snd_renderbuffer" to the sound card
383 ====================
384 */
385 void SndSys_Submit (void)
386 {
387         unsigned int startoffset, factor;
388         snd_pcm_uframes_t limit, nbframes;
389         snd_pcm_sframes_t written;
390
391         if (pcm_handle == NULL ||
392                 snd_renderbuffer->startframe == snd_renderbuffer->endframe)
393                 return;
394
395         startoffset = snd_renderbuffer->startframe % snd_renderbuffer->maxframes;
396         factor = snd_renderbuffer->format.width * snd_renderbuffer->format.channels;
397         limit = snd_renderbuffer->maxframes - startoffset;
398         nbframes = snd_renderbuffer->endframe - snd_renderbuffer->startframe;
399
400         if (nbframes > limit)
401         {
402                 written = SndSys_Write (&snd_renderbuffer->ring[startoffset * factor], limit);
403                 if (written < 0 || (snd_pcm_uframes_t)written != limit)
404                         return;
405
406                 nbframes -= limit;
407                 startoffset = 0;
408         }
409
410         written = SndSys_Write (&snd_renderbuffer->ring[startoffset * factor], nbframes);
411         if (written < 0)
412                 return;
413 }
414
415
416 /*
417 ====================
418 SndSys_GetSoundTime
419
420 Returns the number of sample frames consumed since the sound started
421 ====================
422 */
423 unsigned int SndSys_GetSoundTime (void)
424 {
425         snd_pcm_sframes_t delay, timediff;
426         int err;
427
428         if (pcm_handle == NULL)
429                 return 0;
430
431         err = snd_pcm_delay (pcm_handle, &delay);
432         if (err < 0)
433         {
434                 if (developer_insane.integer && vid_activewindow)
435                         Con_DPrintf ("SndSys_GetSoundTime: can't get playback delay (%s)\n",
436                                                  snd_strerror (err));
437
438                 if (! SndSys_Recover (err))
439                         return 0;
440
441                 err = snd_pcm_delay (pcm_handle, &delay);
442                 if (err < 0)
443                 {
444                         Con_DPrintf ("SndSys_GetSoundTime: can't get playback delay, again (%s)\n",
445                                                  snd_strerror (err));
446                         return 0;
447                 }
448         }
449
450         if (expected_delay < delay)
451         {
452                 Con_DPrintf ("SndSys_GetSoundTime: expected_delay(%ld) < delay(%ld)\n",
453                                          expected_delay, delay);
454                 timediff = 0;
455         }
456         else
457                 timediff = expected_delay - delay;
458         expected_delay = delay;
459
460         alsasoundtime += (unsigned int)timediff;
461
462         return alsasoundtime;
463 }
464
465
466 /*
467 ====================
468 SndSys_LockRenderBuffer
469
470 Get the exclusive lock on "snd_renderbuffer"
471 ====================
472 */
473 qboolean SndSys_LockRenderBuffer (void)
474 {
475         // Nothing to do
476         return true;
477 }
478
479
480 /*
481 ====================
482 SndSys_UnlockRenderBuffer
483
484 Release the exclusive lock on "snd_renderbuffer"
485 ====================
486 */
487 void SndSys_UnlockRenderBuffer (void)
488 {
489         // Nothing to do
490 }
491
492 /*
493 ====================
494 SndSys_SendKeyEvents
495
496 Send keyboard events originating from the sound system (e.g. MIDI)
497 ====================
498 */
499 void SndSys_SendKeyEvents(void)
500 {
501         snd_seq_event_t *event;
502         if(!seq_handle)
503                 return;
504         for(;;)
505         {
506                 if(snd_seq_event_input(seq_handle, &event) <= 0)
507                         break;
508                 if(event)
509                 {
510                         switch(event->type)
511                         {
512                                 case SND_SEQ_EVENT_NOTEON:
513                                         if(event->data.note.velocity)
514                                         {
515                                                 Key_Event(K_MIDINOTE0 + event->data.note.note, 0, true);
516                                                 break;
517                                         }
518                                 case SND_SEQ_EVENT_NOTEOFF:
519                                         Key_Event(K_MIDINOTE0 + event->data.note.note, 0, false);
520                                         break;
521                         }
522                 }
523         }
524 }