WaveOut needs to have rather large chunks. This is about as low as we can
[profile/ivi/pulseaudio.git] / src / modules / module-waveout.c
1 /* $Id$ */
2
3 /***
4   This file is part of polypaudio.
5  
6   polypaudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as published
8   by the Free Software Foundation; either version 2 of the License,
9   or (at your option) any later version.
10  
11   polypaudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15  
16   You should have received a copy of the GNU Lesser General Public License
17   along with polypaudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <windows.h>
27 #include <mmsystem.h>
28 #include <assert.h>
29
30 #include <polyp/mainloop-api.h>
31
32 #include <polypcore/sink.h>
33 #include <polypcore/source.h>
34 #include <polypcore/module.h>
35 #include <polypcore/modargs.h>
36 #include <polypcore/sample-util.h>
37 #include <polypcore/util.h>
38 #include <polypcore/log.h>
39 #include <polypcore/xmalloc.h>
40
41 #include "module-waveout-symdef.h"
42
43 PA_MODULE_AUTHOR("Pierre Ossman")
44 PA_MODULE_DESCRIPTION("Windows waveOut Sink/Source")
45 PA_MODULE_VERSION(PACKAGE_VERSION)
46 PA_MODULE_USAGE("sink_name=<name for the sink> source_name=<name for the source> record=<enable source?> playback=<enable sink?> format=<sample format> channels=<number of channels> rate=<sample rate> fragments=<number of fragments> fragment_size=<fragment size>")
47
48 #define DEFAULT_SINK_NAME "wave_output"
49 #define DEFAULT_SOURCE_NAME "wave_input"
50
51 #define WAVEOUT_MAX_VOLUME 0xFFFF
52
53 struct userdata {
54     pa_sink *sink;
55     pa_source *source;
56     pa_core *core;
57     pa_time_event *event;
58     pa_defer_event *defer;
59     pa_usec_t poll_timeout;
60
61     uint32_t fragments, fragment_size;
62
63     uint32_t free_ofrags, free_ifrags;
64
65     DWORD written_bytes;
66
67     int cur_ohdr, cur_ihdr;
68     unsigned int oremain;
69     WAVEHDR *ohdrs, *ihdrs;
70     pa_memchunk silence;
71
72     HWAVEOUT hwo;
73     HWAVEIN hwi;
74     pa_module *module;
75
76     CRITICAL_SECTION crit;
77 };
78
79 static const char* const valid_modargs[] = {
80     "sink_name",
81     "source_name",
82     "record",
83     "playback",
84     "fragments",
85     "fragment_size",
86     "format",
87     "rate",
88     "channels",
89     NULL
90 };
91
92 static void update_usage(struct userdata *u) {
93    pa_module_set_used(u->module,
94                       (u->sink ? pa_idxset_size(u->sink->inputs) : 0) +
95                       (u->sink ? pa_idxset_size(u->sink->monitor_source->outputs) : 0) +
96                       (u->source ? pa_idxset_size(u->source->outputs) : 0));
97 }
98
99 static void do_write(struct userdata *u)
100 {
101     uint32_t free_frags, remain;
102     pa_memchunk memchunk, *cur_chunk;
103     WAVEHDR *hdr;
104     MMRESULT res;
105
106     if (!u->sink)
107         return;
108
109     EnterCriticalSection(&u->crit);
110
111     free_frags = u->free_ofrags;
112     u->free_ofrags = 0;
113
114     LeaveCriticalSection(&u->crit);
115
116     if (free_frags == u->fragments)
117         pa_log_debug(__FILE__": WaveOut underflow!");
118
119     while (free_frags) {
120         hdr = &u->ohdrs[u->cur_ohdr];
121         if (hdr->dwFlags & WHDR_PREPARED)
122             waveOutUnprepareHeader(u->hwo, hdr, sizeof(WAVEHDR));
123
124         remain = u->oremain;
125         while (remain) {
126             cur_chunk = &memchunk;
127
128             if (pa_sink_render(u->sink, remain, cur_chunk) < 0) {
129                 /*
130                  * Don't fill with silence unless we're getting close to
131                  * underflowing.
132                  */
133                 if (free_frags > u->fragments/2)
134                     cur_chunk = &u->silence;
135                 else {
136                     EnterCriticalSection(&u->crit);
137
138                     u->free_ofrags += free_frags;
139
140                     LeaveCriticalSection(&u->crit);
141
142                     u->oremain = remain;
143                     return;
144                 }
145             }
146
147             assert(cur_chunk->memblock);
148             assert(cur_chunk->memblock->data);
149             assert(cur_chunk->length);
150
151             memcpy(hdr->lpData + u->fragment_size - remain,
152                 (char*)cur_chunk->memblock->data + cur_chunk->index,
153                 (cur_chunk->length < remain)?cur_chunk->length:remain);
154
155             remain -= (cur_chunk->length < remain)?cur_chunk->length:remain;
156
157             if (cur_chunk != &u->silence) {
158                 pa_memblock_unref(cur_chunk->memblock);
159                 cur_chunk->memblock = NULL;
160             }
161         }
162
163         res = waveOutPrepareHeader(u->hwo, hdr, sizeof(WAVEHDR));
164         if (res != MMSYSERR_NOERROR) {
165             pa_log_error(__FILE__ ": ERROR: Unable to prepare waveOut block: %d",
166                 res);
167         }
168         res = waveOutWrite(u->hwo, hdr, sizeof(WAVEHDR));
169         if (res != MMSYSERR_NOERROR) {
170             pa_log_error(__FILE__ ": ERROR: Unable to write waveOut block: %d",
171                 res);
172         }
173         
174         u->written_bytes += u->fragment_size;
175
176         free_frags--;
177         u->cur_ohdr++;
178         u->cur_ohdr %= u->fragments;
179         u->oremain = u->fragment_size;
180     }
181 }
182
183 static void do_read(struct userdata *u)
184 {
185     uint32_t free_frags;
186     pa_memchunk memchunk;
187     WAVEHDR *hdr;
188     MMRESULT res;
189
190     if (!u->source)
191         return;
192
193     EnterCriticalSection(&u->crit);
194
195     free_frags = u->free_ifrags;
196     u->free_ifrags = 0;
197
198     LeaveCriticalSection(&u->crit);
199
200     if (free_frags == u->fragments)
201         pa_log_debug(__FILE__": WaveIn overflow!");
202
203     while (free_frags) {
204         hdr = &u->ihdrs[u->cur_ihdr];
205         if (hdr->dwFlags & WHDR_PREPARED)
206             waveInUnprepareHeader(u->hwi, hdr, sizeof(WAVEHDR));
207
208         if (hdr->dwBytesRecorded) {
209             memchunk.memblock = pa_memblock_new(hdr->dwBytesRecorded, u->core->memblock_stat);
210             assert(memchunk.memblock);
211
212             memcpy((char*)memchunk.memblock->data, hdr->lpData, hdr->dwBytesRecorded);
213
214             memchunk.length = memchunk.memblock->length = hdr->dwBytesRecorded;
215             memchunk.index = 0;
216
217             pa_source_post(u->source, &memchunk);
218             pa_memblock_unref(memchunk.memblock);
219         }
220
221         res = waveInPrepareHeader(u->hwi, hdr, sizeof(WAVEHDR));
222         if (res != MMSYSERR_NOERROR) {
223             pa_log_error(__FILE__ ": ERROR: Unable to prepare waveIn block: %d",
224                 res);
225         }
226         res = waveInAddBuffer(u->hwi, hdr, sizeof(WAVEHDR));
227         if (res != MMSYSERR_NOERROR) {
228             pa_log_error(__FILE__ ": ERROR: Unable to add waveIn block: %d",
229                 res);
230         }
231         
232         free_frags--;
233         u->cur_ihdr++;
234         u->cur_ihdr %= u->fragments;
235     }
236 }
237
238 static void poll_cb(pa_mainloop_api*a, pa_time_event *e, const struct timeval *tv, void *userdata) {
239     struct userdata *u = userdata;
240     struct timeval ntv;
241
242     assert(u);
243
244     update_usage(u);
245
246     do_write(u);
247     do_read(u);
248
249     pa_gettimeofday(&ntv);
250     pa_timeval_add(&ntv, u->poll_timeout);
251
252     a->time_restart(e, &ntv);
253 }
254
255 static void defer_cb(pa_mainloop_api*a, pa_defer_event *e, void *userdata) {
256     struct userdata *u = userdata;
257
258     assert(u);
259
260     a->defer_enable(e, 0);
261
262     do_write(u);
263     do_read(u);
264 }
265
266 static void CALLBACK chunk_done_cb(HWAVEOUT hwo, UINT msg, DWORD_PTR inst, DWORD param1, DWORD param2) {
267     struct userdata *u = (struct userdata *)inst;
268
269     if (msg != WOM_DONE)
270         return;
271
272     EnterCriticalSection(&u->crit);
273
274     u->free_ofrags++;
275     assert(u->free_ofrags <= u->fragments);
276
277     LeaveCriticalSection(&u->crit);
278 }
279
280 static void CALLBACK chunk_ready_cb(HWAVEIN hwi, UINT msg, DWORD_PTR inst, DWORD param1, DWORD param2) {
281     struct userdata *u = (struct userdata *)inst;
282
283     if (msg != WIM_DATA)
284         return;
285
286     EnterCriticalSection(&u->crit);
287
288     u->free_ifrags++;
289     assert(u->free_ifrags <= u->fragments);
290
291     LeaveCriticalSection(&u->crit);
292 }
293
294 static pa_usec_t sink_get_latency_cb(pa_sink *s) {
295     struct userdata *u = s->userdata;
296     uint32_t free_frags;
297     MMTIME mmt;
298     assert(s && u && u->sink);
299
300     memset(&mmt, 0, sizeof(mmt));
301     mmt.wType = TIME_BYTES;
302     if (waveOutGetPosition(u->hwo, &mmt, sizeof(mmt)) == MMSYSERR_NOERROR)
303         return pa_bytes_to_usec(u->written_bytes - mmt.u.cb, &s->sample_spec);
304     else {
305         EnterCriticalSection(&u->crit);
306
307         free_frags = u->free_ofrags;
308
309         LeaveCriticalSection(&u->crit);
310
311         return pa_bytes_to_usec((u->fragments - free_frags) * u->fragment_size,
312                               &s->sample_spec);
313     }
314 }
315
316 static pa_usec_t source_get_latency_cb(pa_source *s) {
317     pa_usec_t r = 0;
318     struct userdata *u = s->userdata;
319     uint32_t free_frags;
320     assert(s && u && u->sink);
321
322     EnterCriticalSection(&u->crit);
323
324     free_frags = u->free_ifrags;
325
326     LeaveCriticalSection(&u->crit);
327
328     r += pa_bytes_to_usec((free_frags + 1) * u->fragment_size, &s->sample_spec);
329
330     return r;
331 }
332
333 static void notify_sink_cb(pa_sink *s) {
334     struct userdata *u = s->userdata;
335     assert(u);
336
337     u->core->mainloop->defer_enable(u->defer, 1);
338 }
339
340 static void notify_source_cb(pa_source *s) {
341     struct userdata *u = s->userdata;
342     assert(u);
343
344     u->core->mainloop->defer_enable(u->defer, 1);
345 }
346
347 static int sink_get_hw_volume_cb(pa_sink *s) {
348     struct userdata *u = s->userdata;
349     DWORD vol;
350     pa_volume_t left, right;
351
352     if (waveOutGetVolume(u->hwo, &vol) != MMSYSERR_NOERROR)
353         return -1;
354
355     left = (vol & 0xFFFF) * PA_VOLUME_NORM / WAVEOUT_MAX_VOLUME;
356     right = ((vol >> 16) & 0xFFFF) * PA_VOLUME_NORM / WAVEOUT_MAX_VOLUME;
357
358     /* Windows supports > 2 channels, except for volume control */
359     if (s->hw_volume.channels > 2)
360         pa_cvolume_set(&s->hw_volume, s->hw_volume.channels, (left + right)/2);
361
362     s->hw_volume.values[0] = left;
363     if (s->hw_volume.channels > 1)
364         s->hw_volume.values[1] = right;
365
366     return 0;
367 }
368
369 static int sink_set_hw_volume_cb(pa_sink *s) {
370     struct userdata *u = s->userdata;
371     DWORD vol;
372
373     vol = s->hw_volume.values[0] * WAVEOUT_MAX_VOLUME / PA_VOLUME_NORM;
374     if (s->hw_volume.channels > 1)
375         vol |= (s->hw_volume.values[0] * WAVEOUT_MAX_VOLUME / PA_VOLUME_NORM) << 16;
376
377     if (waveOutSetVolume(u->hwo, vol) != MMSYSERR_NOERROR)
378         return -1;
379
380     return 0;
381 }
382
383 static int ss_to_waveformat(pa_sample_spec *ss, LPWAVEFORMATEX wf) {
384     wf->wFormatTag = WAVE_FORMAT_PCM;
385
386     if (ss->channels > 2) {
387         pa_log_error(__FILE__": ERROR: More than two channels not supported.");
388         return -1;
389     }
390
391     wf->nChannels = ss->channels;
392
393     switch (ss->rate) {
394     case 8000:
395     case 11025:
396     case 22005:
397     case 44100:
398         break;
399     default:
400         pa_log_error(__FILE__": ERROR: Unsupported sample rate.");
401         return -1;
402     }
403
404     wf->nSamplesPerSec = ss->rate;
405
406     if (ss->format == PA_SAMPLE_U8)
407         wf->wBitsPerSample = 8;
408     else if (ss->format == PA_SAMPLE_S16NE)
409         wf->wBitsPerSample = 16;
410     else {
411         pa_log_error(__FILE__": ERROR: Unsupported sample format.");
412         return -1;
413     }
414
415     wf->nBlockAlign = wf->nChannels * wf->wBitsPerSample/8;
416     wf->nAvgBytesPerSec = wf->nSamplesPerSec * wf->nBlockAlign;
417
418     wf->cbSize = 0;
419
420     return 0;
421 }
422
423 int pa__init(pa_core *c, pa_module*m) {
424     struct userdata *u = NULL;
425     HWAVEOUT hwo = INVALID_HANDLE_VALUE;
426     HWAVEIN hwi = INVALID_HANDLE_VALUE;
427     WAVEFORMATEX wf;
428     int nfrags, frag_size;
429     int record = 1, playback = 1;
430     pa_sample_spec ss;
431     pa_modargs *ma = NULL;
432     unsigned int i;
433     struct timeval tv;
434
435     assert(c && m);
436
437     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
438         pa_log(__FILE__": failed to parse module arguments.");
439         goto fail;
440     }
441
442     if (pa_modargs_get_value_boolean(ma, "record", &record) < 0 || pa_modargs_get_value_boolean(ma, "playback", &playback) < 0) {
443         pa_log(__FILE__": record= and playback= expect boolean argument.");
444         goto fail;
445     }
446
447     if (!playback && !record) {
448         pa_log(__FILE__": neither playback nor record enabled for device.");
449         goto fail;
450     }
451
452     nfrags = 5;
453     frag_size = 8192;
454     if (pa_modargs_get_value_s32(ma, "fragments", &nfrags) < 0 || pa_modargs_get_value_s32(ma, "fragment_size", &frag_size) < 0) {
455         pa_log(__FILE__": failed to parse fragments arguments");
456         goto fail;
457     }
458
459     ss = c->default_sample_spec;
460     if (pa_modargs_get_sample_spec(ma, &ss) < 0) {
461         pa_log(__FILE__": failed to parse sample specification");
462         goto fail;
463     }
464
465     if (ss_to_waveformat(&ss, &wf) < 0)
466         goto fail;
467
468     u = pa_xmalloc(sizeof(struct userdata));
469
470     if (record) {
471         if (waveInOpen(&hwi, WAVE_MAPPER, &wf, (DWORD_PTR)chunk_ready_cb, (DWORD_PTR)u, CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
472             goto fail;
473         if (waveInStart(hwi) != MMSYSERR_NOERROR)
474             goto fail;
475         pa_log_debug(__FILE__": Opened waveIn subsystem.");
476     }
477
478     if (playback) {
479         if (waveOutOpen(&hwo, WAVE_MAPPER, &wf, (DWORD_PTR)chunk_done_cb, (DWORD_PTR)u, CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
480             goto fail;
481         pa_log_debug(__FILE__": Opened waveOut subsystem.");
482     }
483
484     InitializeCriticalSection(&u->crit);
485
486     if (hwi != INVALID_HANDLE_VALUE) {
487         u->source = pa_source_new(c, __FILE__, pa_modargs_get_value(ma, "source_name", DEFAULT_SOURCE_NAME), 0, &ss, NULL);
488         assert(u->source);
489         u->source->userdata = u;
490         u->source->notify = notify_source_cb;
491         u->source->get_latency = source_get_latency_cb;
492         pa_source_set_owner(u->source, m);
493         u->source->description = pa_sprintf_malloc("Windows waveIn PCM");
494     } else
495         u->source = NULL;
496
497     if (hwo != INVALID_HANDLE_VALUE) {
498         u->sink = pa_sink_new(c, __FILE__, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME), 0, &ss, NULL);
499         assert(u->sink);
500         u->sink->notify = notify_sink_cb;
501         u->sink->get_latency = sink_get_latency_cb;
502         u->sink->get_hw_volume = sink_get_hw_volume_cb;
503         u->sink->set_hw_volume = sink_set_hw_volume_cb;
504         u->sink->userdata = u;
505         pa_sink_set_owner(u->sink, m);
506         u->sink->description = pa_sprintf_malloc("Windows waveOut PCM");
507     } else
508         u->sink = NULL;
509
510     assert(u->source || u->sink);
511
512     u->core = c;
513     u->hwi = hwi;
514     u->hwo = hwo;
515
516     u->fragments = nfrags;
517     u->free_ifrags = u->fragments;
518     u->free_ofrags = u->fragments;
519     u->fragment_size = frag_size - (frag_size % pa_frame_size(&ss));
520
521     u->written_bytes = 0;
522
523     u->oremain = u->fragment_size;
524
525     u->poll_timeout = pa_bytes_to_usec(u->fragments * u->fragment_size / 10, &ss);
526
527     pa_gettimeofday(&tv);
528     pa_timeval_add(&tv, u->poll_timeout);
529
530     u->event = c->mainloop->time_new(c->mainloop, &tv, poll_cb, u);
531     assert(u->event);
532
533     u->defer = c->mainloop->defer_new(c->mainloop, defer_cb, u);
534     assert(u->defer);
535     c->mainloop->defer_enable(u->defer, 0);
536
537     u->cur_ihdr = 0;
538     u->cur_ohdr = 0;
539     u->ihdrs = pa_xmalloc0(sizeof(WAVEHDR) * u->fragments);
540     assert(u->ihdrs);
541     u->ohdrs = pa_xmalloc0(sizeof(WAVEHDR) * u->fragments);
542     assert(u->ohdrs);
543     for (i = 0;i < u->fragments;i++) {
544         u->ihdrs[i].dwBufferLength = u->fragment_size;
545         u->ohdrs[i].dwBufferLength = u->fragment_size;
546         u->ihdrs[i].lpData = pa_xmalloc(u->fragment_size);
547         assert(u->ihdrs);
548         u->ohdrs[i].lpData = pa_xmalloc(u->fragment_size);
549         assert(u->ohdrs);
550     }
551     
552     u->silence.length = u->fragment_size;
553     u->silence.memblock = pa_memblock_new(u->silence.length, u->core->memblock_stat);
554     assert(u->silence.memblock);
555     pa_silence_memblock(u->silence.memblock, &ss);
556     u->silence.index = 0;
557
558     u->module = m;
559     m->userdata = u;
560
561     pa_modargs_free(ma);
562
563     /* Read mixer settings */
564     if (u->sink)
565         sink_get_hw_volume_cb(u->sink);
566
567     return 0;
568
569 fail:
570    if (hwi != INVALID_HANDLE_VALUE)
571         waveInClose(hwi);
572
573    if (hwo != INVALID_HANDLE_VALUE)
574         waveOutClose(hwo);
575
576     if (u)
577         pa_xfree(u);
578
579     if (ma)
580         pa_modargs_free(ma);
581     
582     return -1;
583 }
584
585 void pa__done(pa_core *c, pa_module*m) {
586     struct userdata *u;
587     unsigned int i;
588
589     assert(c && m);
590
591     if (!(u = m->userdata))
592         return;
593     
594     if (u->event)
595         c->mainloop->time_free(u->event);
596
597     if (u->defer)
598         c->mainloop->defer_free(u->defer);
599
600     if (u->sink) {
601         pa_sink_disconnect(u->sink);
602         pa_sink_unref(u->sink);
603     }
604     
605     if (u->source) {
606         pa_source_disconnect(u->source);
607         pa_source_unref(u->source);
608     }
609     
610     if (u->hwi != INVALID_HANDLE_VALUE) {
611         waveInReset(u->hwi);
612         waveInClose(u->hwi);
613     }
614
615     if (u->hwo != INVALID_HANDLE_VALUE) {
616         waveOutReset(u->hwo);
617         waveOutClose(u->hwo);
618     }
619
620     for (i = 0;i < u->fragments;i++) {
621         pa_xfree(u->ihdrs[i].lpData);
622         pa_xfree(u->ohdrs[i].lpData);
623     }
624
625     pa_xfree(u->ihdrs);
626     pa_xfree(u->ohdrs);
627
628     DeleteCriticalSection(&u->crit);
629     
630     pa_xfree(u);
631 }