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