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