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