1/***
2  This file is part of PulseAudio.
3
4  Copyright 2004-2006 Lennart Poettering
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.1 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, see <http://www.gnu.org/licenses/>.
18***/
19
20#ifdef HAVE_CONFIG_H
21#include <config.h>
22#endif
23
24#include <stdlib.h>
25#include <sys/stat.h>
26#include <stdio.h>
27#include <errno.h>
28#include <fcntl.h>
29#include <unistd.h>
30#include <sys/ioctl.h>
31
32#ifdef HAVE_SYS_FILIO_H
33#include <sys/filio.h>
34#endif
35
36#include <pulse/xmalloc.h>
37#include <pulse/timeval.h>
38#include <pulse/util.h>
39#include <pulse/rtclock.h>
40
41#include <pulsecore/core-error.h>
42#include <pulsecore/sink.h>
43#include <pulsecore/module.h>
44#include <pulsecore/core-util.h>
45#include <pulsecore/modargs.h>
46#include <pulsecore/log.h>
47#include <pulsecore/thread.h>
48#include <pulsecore/thread-mq.h>
49#include <pulsecore/rtpoll.h>
50#include <pulsecore/poll.h>
51
52PA_MODULE_AUTHOR("Lennart Poettering");
53PA_MODULE_DESCRIPTION("UNIX pipe sink");
54PA_MODULE_VERSION(PACKAGE_VERSION);
55PA_MODULE_LOAD_ONCE(false);
56PA_MODULE_USAGE(
57        "sink_name=<name for the sink> "
58        "sink_properties=<properties for the sink> "
59        "file=<path of the FIFO> "
60        "format=<sample format> "
61        "rate=<sample rate> "
62        "channels=<number of channels> "
63        "channel_map=<channel map> "
64        "use_system_clock_for_timing=<yes or no> "
65);
66
67#define DEFAULT_FILE_NAME "fifo_output"
68#define DEFAULT_SINK_NAME "fifo_output"
69
70struct userdata {
71    pa_core *core;
72    pa_module *module;
73    pa_sink *sink;
74
75    pa_thread *thread;
76    pa_thread_mq thread_mq;
77    pa_rtpoll *rtpoll;
78
79    char *filename;
80    int fd;
81    bool do_unlink_fifo;
82    size_t buffer_size;
83    size_t bytes_dropped;
84    bool fifo_error;
85
86    pa_memchunk memchunk;
87
88    pa_rtpoll_item *rtpoll_item;
89
90    int write_type;
91    pa_usec_t block_usec;
92    pa_usec_t timestamp;
93
94    bool use_system_clock_for_timing;
95};
96
97static const char* const valid_modargs[] = {
98    "sink_name",
99    "sink_properties",
100    "file",
101    "format",
102    "rate",
103    "channels",
104    "channel_map",
105    "use_system_clock_for_timing",
106    NULL
107};
108
109static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
110    struct userdata *u = PA_SINK(o)->userdata;
111
112    switch (code) {
113        case PA_SINK_MESSAGE_GET_LATENCY:
114            if (u->use_system_clock_for_timing) {
115                pa_usec_t now;
116                now = pa_rtclock_now();
117                *((int64_t*) data) = (int64_t)u->timestamp - (int64_t)now;
118            } else {
119                size_t n = 0;
120
121#ifdef FIONREAD
122                int l;
123
124                if (ioctl(u->fd, FIONREAD, &l) >= 0 && l > 0)
125                    n = (size_t) l;
126#endif
127
128                n += u->memchunk.length;
129
130                *((int64_t*) data) = pa_bytes_to_usec(n, &u->sink->sample_spec);
131            }
132            return 0;
133    }
134
135    return pa_sink_process_msg(o, code, data, offset, chunk);
136}
137
138/* Called from the IO thread. */
139static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
140    struct userdata *u;
141
142    pa_assert(s);
143    pa_assert_se(u = s->userdata);
144
145    if (s->thread_info.state == PA_SINK_SUSPENDED || s->thread_info.state == PA_SINK_INIT) {
146        if (PA_SINK_IS_OPENED(new_state))
147            u->timestamp = pa_rtclock_now();
148    } else if (PA_SINK_IS_OPENED(s->thread_info.state)) {
149        if (new_state == PA_SINK_SUSPENDED) {
150            /* Clear potential FIFO error flag */
151            u->fifo_error = false;
152
153            /* Continuously dropping data (clear counter on entering suspended state. */
154            if (u->bytes_dropped != 0) {
155                pa_log_debug("Pipe-sink continuously dropping data - clear statistics (%zu -> 0 bytes dropped)", u->bytes_dropped);
156                u->bytes_dropped = 0;
157            }
158        }
159    }
160
161    return 0;
162}
163
164static void sink_update_requested_latency_cb(pa_sink *s) {
165    struct userdata *u;
166    size_t nbytes;
167
168    pa_sink_assert_ref(s);
169    pa_assert_se(u = s->userdata);
170
171    u->block_usec = pa_sink_get_requested_latency_within_thread(s);
172
173    if (u->block_usec == (pa_usec_t) -1)
174        u->block_usec = s->thread_info.max_latency;
175
176    nbytes = pa_usec_to_bytes(u->block_usec, &s->sample_spec);
177    pa_sink_set_max_request_within_thread(s, nbytes);
178}
179
180static ssize_t pipe_sink_write(struct userdata *u, pa_memchunk *pchunk) {
181    size_t index, length;
182    ssize_t count = 0;
183    void *p;
184
185    pa_assert(u);
186    pa_assert(pchunk);
187
188    index = pchunk->index;
189    length = pchunk->length;
190    p = pa_memblock_acquire(pchunk->memblock);
191
192    for (;;) {
193        ssize_t l;
194
195        l = pa_write(u->fd, (uint8_t*) p + index, length, &u->write_type);
196
197        pa_assert(l != 0);
198
199        if (l < 0) {
200            if (errno == EAGAIN)
201                break;
202
203            if (!u->fifo_error) {
204                pa_log("Failed to write data to FIFO: %s", pa_cstrerror(errno));
205                u->fifo_error = true;
206            }
207            count = -1 - count;
208            break;
209        } else {
210            if (u->fifo_error) {
211                pa_log_debug("Recovered from FIFO error");
212                u->fifo_error = false;
213            }
214            count += l;
215            index += l;
216            length -= l;
217
218            if (length <= 0) {
219                break;
220            }
221        }
222    }
223
224    pa_memblock_release(pchunk->memblock);
225
226    return count;
227}
228
229static void process_render_use_timing(struct userdata *u, pa_usec_t now) {
230    size_t dropped = 0;
231    size_t consumed = 0;
232
233    pa_assert(u);
234
235    /* Fill the buffer up the latency size */
236    while (u->timestamp < now + u->block_usec) {
237        ssize_t written = 0;
238        pa_memchunk chunk;
239
240        pa_sink_render(u->sink, u->sink->thread_info.max_request, &chunk);
241
242        pa_assert(chunk.length > 0);
243
244        if ((written = pipe_sink_write(u, &chunk)) < 0)
245            written = -1 - written;
246
247        pa_memblock_unref(chunk.memblock);
248
249        u->timestamp += pa_bytes_to_usec(chunk.length, &u->sink->sample_spec);
250
251        dropped = chunk.length - written;
252
253        if (u->bytes_dropped != 0 && dropped != chunk.length) {
254            pa_log_debug("Pipe-sink continuously dropped %zu bytes", u->bytes_dropped);
255            u->bytes_dropped = 0;
256        }
257
258        if (u->bytes_dropped == 0 && dropped != 0)
259            pa_log_debug("Pipe-sink just dropped %zu bytes", dropped);
260
261        u->bytes_dropped += dropped;
262
263        consumed += chunk.length;
264
265        if (consumed >= u->sink->thread_info.max_request)
266            break;
267    }
268}
269
270static int process_render(struct userdata *u) {
271    pa_assert(u);
272
273    if (u->memchunk.length <= 0)
274        pa_sink_render(u->sink, u->buffer_size, &u->memchunk);
275
276    pa_assert(u->memchunk.length > 0);
277
278    for (;;) {
279        ssize_t l;
280        void *p;
281
282        p = pa_memblock_acquire(u->memchunk.memblock);
283        l = pa_write(u->fd, (uint8_t*) p + u->memchunk.index, u->memchunk.length, &u->write_type);
284        pa_memblock_release(u->memchunk.memblock);
285
286        pa_assert(l != 0);
287
288        if (l < 0) {
289
290            if (errno == EAGAIN)
291                return 0;
292            else {
293                pa_log("Failed to write data to FIFO: %s", pa_cstrerror(errno));
294                return -1;
295            }
296
297        } else {
298
299            u->memchunk.index += (size_t) l;
300            u->memchunk.length -= (size_t) l;
301
302            if (u->memchunk.length <= 0) {
303                pa_memblock_unref(u->memchunk.memblock);
304                pa_memchunk_reset(&u->memchunk);
305            }
306        }
307
308        return 0;
309    }
310}
311
312static void thread_func_use_timing(void *userdata) {
313    struct userdata *u = userdata;
314
315    pa_assert(u);
316
317    pa_log_debug("Thread (use timing) starting up");
318
319    pa_thread_mq_install(&u->thread_mq);
320
321    u->timestamp = pa_rtclock_now();
322
323    for (;;) {
324        pa_usec_t now = 0;
325        int ret;
326
327        if (PA_SINK_IS_OPENED(u->sink->thread_info.state))
328            now = pa_rtclock_now();
329
330        if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
331            pa_sink_process_rewind(u->sink, 0);
332
333        /* Render some data and write it to the fifo */
334        if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
335            if (u->timestamp <= now)
336                process_render_use_timing(u, now);
337
338            pa_rtpoll_set_timer_absolute(u->rtpoll, u->timestamp);
339        } else
340            pa_rtpoll_set_timer_disabled(u->rtpoll);
341
342        /* Hmm, nothing to do. Let's sleep */
343        if ((ret = pa_rtpoll_run(u->rtpoll)) < 0)
344            goto fail;
345
346        if (ret == 0)
347            goto finish;
348    }
349
350fail:
351    /* If this was no regular exit from the loop we have to continue
352     * processing messages until we received PA_MESSAGE_SHUTDOWN */
353    pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
354    pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
355
356finish:
357    pa_log_debug("Thread (use timing) shutting down");
358}
359
360static void thread_func(void *userdata) {
361    struct userdata *u = userdata;
362
363    pa_assert(u);
364
365    pa_log_debug("Thread starting up");
366
367    pa_thread_mq_install(&u->thread_mq);
368
369    for (;;) {
370        struct pollfd *pollfd;
371        int ret;
372
373        pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
374
375        if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
376            pa_sink_process_rewind(u->sink, 0);
377
378        /* Render some data and write it to the fifo */
379        if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
380            if (pollfd->revents) {
381                if (process_render(u) < 0)
382                    goto fail;
383
384                pollfd->revents = 0;
385            }
386        }
387
388        /* Hmm, nothing to do. Let's sleep */
389        pollfd->events = (short) (u->sink->thread_info.state == PA_SINK_RUNNING ? POLLOUT : 0);
390
391        if ((ret = pa_rtpoll_run(u->rtpoll)) < 0)
392            goto fail;
393
394        if (ret == 0)
395            goto finish;
396
397        pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
398
399        if (pollfd->revents & ~POLLOUT) {
400            pa_log("FIFO shutdown.");
401            goto fail;
402        }
403    }
404
405fail:
406    /* If this was no regular exit from the loop we have to continue
407     * processing messages until we received PA_MESSAGE_SHUTDOWN */
408    pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
409    pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
410
411finish:
412    pa_log_debug("Thread shutting down");
413}
414
415int pa__init(pa_module *m) {
416    struct userdata *u;
417    struct stat st;
418    pa_sample_spec ss;
419    pa_channel_map map;
420    pa_modargs *ma;
421    struct pollfd *pollfd;
422    pa_sink_new_data data;
423    pa_thread_func_t thread_routine;
424
425    pa_assert(m);
426
427    if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
428        pa_log("Failed to parse module arguments.");
429        goto fail;
430    }
431
432    ss = m->core->default_sample_spec;
433    map = m->core->default_channel_map;
434    if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_DEFAULT) < 0) {
435        pa_log("Invalid sample format specification or channel map");
436        goto fail;
437    }
438
439    u = pa_xnew0(struct userdata, 1);
440    u->core = m->core;
441    u->module = m;
442    m->userdata = u;
443    pa_memchunk_reset(&u->memchunk);
444    u->rtpoll = pa_rtpoll_new();
445
446    if (pa_modargs_get_value_boolean(ma, "use_system_clock_for_timing", &u->use_system_clock_for_timing) < 0) {
447        pa_log("Failed to parse use_system_clock_for_timing argument.");
448        goto fail;
449    }
450
451    if (pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll) < 0) {
452        pa_log("pa_thread_mq_init() failed.");
453        goto fail;
454    }
455
456    u->write_type = 0;
457
458    u->filename = pa_runtime_path(pa_modargs_get_value(ma, "file", DEFAULT_FILE_NAME));
459    u->do_unlink_fifo = false;
460
461    if (mkfifo(u->filename, 0666) < 0) {
462        if (errno != EEXIST) {
463            pa_log("mkfifo('%s'): %s", u->filename, pa_cstrerror(errno));
464            goto fail;
465        }
466    } else {
467        u->do_unlink_fifo = true;
468
469        /* Our umask is 077, so the pipe won't be created with the requested
470         * permissions. Let's fix the permissions with chmod(). */
471        if (chmod(u->filename, 0666) < 0)
472            pa_log_warn("chomd('%s'): %s", u->filename, pa_cstrerror(errno));
473    }
474
475    if ((u->fd = pa_open_cloexec(u->filename, O_RDWR, 0)) < 0) {
476        pa_log("open('%s'): %s", u->filename, pa_cstrerror(errno));
477        goto fail;
478    }
479
480    pa_make_fd_nonblock(u->fd);
481
482    if (fstat(u->fd, &st) < 0) {
483        pa_log("fstat('%s'): %s", u->filename, pa_cstrerror(errno));
484        goto fail;
485    }
486
487    if (!S_ISFIFO(st.st_mode)) {
488        pa_log("'%s' is not a FIFO.", u->filename);
489        goto fail;
490    }
491
492    pa_sink_new_data_init(&data);
493    data.driver = __FILE__;
494    data.module = m;
495    pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
496    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, u->filename);
497    pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Unix FIFO sink %s", u->filename);
498    pa_sink_new_data_set_sample_spec(&data, &ss);
499    pa_sink_new_data_set_channel_map(&data, &map);
500
501    if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
502        pa_log("Invalid properties");
503        pa_sink_new_data_done(&data);
504        goto fail;
505    }
506
507    if (u->use_system_clock_for_timing)
508        u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY|PA_SINK_DYNAMIC_LATENCY);
509    else
510        u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
511    pa_sink_new_data_done(&data);
512
513    if (!u->sink) {
514        pa_log("Failed to create sink.");
515        goto fail;
516    }
517
518    u->sink->parent.process_msg = sink_process_msg;
519    u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
520    if (u->use_system_clock_for_timing)
521        u->sink->update_requested_latency = sink_update_requested_latency_cb;
522    u->sink->userdata = u;
523
524    pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
525    pa_sink_set_rtpoll(u->sink, u->rtpoll);
526
527    u->bytes_dropped = 0;
528    u->fifo_error = false;
529    u->buffer_size = pa_frame_align(pa_pipe_buf(u->fd), &u->sink->sample_spec);
530    if (u->use_system_clock_for_timing) {
531        u->block_usec = pa_bytes_to_usec(u->buffer_size, &u->sink->sample_spec);
532        pa_sink_set_latency_range(u->sink, 0, u->block_usec);
533        thread_routine = thread_func_use_timing;
534    } else {
535        pa_sink_set_fixed_latency(u->sink, pa_bytes_to_usec(u->buffer_size, &u->sink->sample_spec));
536        thread_routine = thread_func;
537    }
538    pa_sink_set_max_request(u->sink, u->buffer_size);
539
540    u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
541    pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
542    pollfd->fd = u->fd;
543    pollfd->events = pollfd->revents = 0;
544
545    if (!(u->thread = pa_thread_new("pipe-sink", thread_routine, u))) {
546        pa_log("Failed to create thread.");
547        goto fail;
548    }
549
550    pa_sink_put(u->sink);
551
552    pa_modargs_free(ma);
553
554    return 0;
555
556fail:
557    if (ma)
558        pa_modargs_free(ma);
559
560    pa__done(m);
561
562    return -1;
563}
564
565int pa__get_n_used(pa_module *m) {
566    struct userdata *u;
567
568    pa_assert(m);
569    pa_assert_se(u = m->userdata);
570
571    return pa_sink_linked_by(u->sink);
572}
573
574void pa__done(pa_module *m) {
575    struct userdata *u;
576
577    pa_assert(m);
578
579    if (!(u = m->userdata))
580        return;
581
582    if (u->sink)
583        pa_sink_unlink(u->sink);
584
585    if (u->thread) {
586        pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
587        pa_thread_free(u->thread);
588    }
589
590    pa_thread_mq_done(&u->thread_mq);
591
592    if (u->sink)
593        pa_sink_unref(u->sink);
594
595    if (u->memchunk.memblock)
596        pa_memblock_unref(u->memchunk.memblock);
597
598    if (u->rtpoll_item)
599        pa_rtpoll_item_free(u->rtpoll_item);
600
601    if (u->rtpoll)
602        pa_rtpoll_free(u->rtpoll);
603
604    if (u->filename) {
605        if (u->do_unlink_fifo)
606            unlink(u->filename);
607        pa_xfree(u->filename);
608    }
609
610    if (u->fd >= 0)
611        pa_assert_se(pa_close(u->fd) == 0);
612
613    pa_xfree(u);
614}
615