Ticket #91: module-jack-sink.c

File module-jack-sink.c, 25.0 kB (added by tanuk, 1 year ago)

An improved version (a couple of bug fixes, numbered ports).

Line 
1 /* $Id: module-jack-sink.c 1426 2007-02-13 15:35:19Z ossman $ */
2
3 /***
4   This file is part of PulseAudio.
5
6   Copyright 2006, 2007 Lennart Poettering and Tanu Kaskinen
7
8   PulseAudio is free software; you can redistribute it and/or modify
9   it under the terms of the GNU Lesser General Public License as published
10   by the Free Software Foundation; either version 2 of the License,
11   or (at your option) any later version.
12
13   PulseAudio is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with PulseAudio; if not, write to the Free Software
20   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21   USA.
22 ***/
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <pthread.h>
29 #include <assert.h>
30 #include <errno.h>
31
32 #include <jack/jack.h>
33 #include <jack/ringbuffer.h>
34 #include <jack/types.h>
35
36 #include <pulse/mainloop-api.h>
37 #include <pulse/sample.h>
38 #include <pulse/channelmap.h>
39 #include <pulse/xmalloc.h>
40
41 #include <pulsecore/sink.h>
42 #include <pulsecore/module.h>
43 #include <pulsecore/core.h>
44 #include <pulsecore/log.h>
45 #include <pulsecore/core-util.h>
46 #include <pulsecore/core-error.h>
47 #include <pulsecore/pipe.h>
48 #include <pulsecore/modargs.h>
49 #include <pulsecore/strbuf.h>
50
51 #include "module-jack-sink-symdef.h"
52
53 PA_MODULE_AUTHOR("Lennart Poettering & Tanu Kaskinen")
54 PA_MODULE_DESCRIPTION("Jack Sink")
55 PA_MODULE_VERSION(PACKAGE_VERSION)
56 PA_MODULE_USAGE(
57         "sink_name=<name of sink> "
58         "server_name=<jack server name> "
59         "client_name=<jack client name> "
60         "channels=<number of channels> "
61         "connect=<connect ports automatically?> "
62         "buffersize=<intermediate buffering in frames> "
63         "channel_map=<channel map>")
64
65 #define DEFAULT_SINK_NAME "jack_out"
66 #define DEFAULT_CLIENT_NAME "PulseAudio(output)"
67 #define DEFAULT_RINGBUFFER_SIZE 4096
68
69
70 struct userdata {
71     pa_sink *sink;
72
73     unsigned channels;
74     unsigned frame_size;
75
76     jack_port_t* j_ports[PA_CHANNELS_MAX];
77     jack_client_t *j_client;
78
79     jack_nframes_t j_buffersize;
80
81     /* For avoiding j_buffersize changes at a wrong moment. */
82     pthread_mutex_t buffersize_mutex;
83
84     /* The intermediate store where the pulse side writes to and the jack side
85        reads from. */
86     jack_ringbuffer_t* ringbuffer;
87    
88     /* For signaling when there's room in the ringbuffer. */
89     pthread_mutex_t cond_mutex;
90     pthread_cond_t ringbuffer_cond;
91
92     pthread_t filler_thread; /* Keeps the ringbuffer filled. */
93
94     int ringbuffer_is_full;
95     int filler_thread_is_running;
96     int quit_requested;
97
98     int pipe_fd_type;
99     int pipe_fds[2];
100     pa_io_event *io_event;
101 };
102
103
104 struct options {
105     char* sink_name;
106     int sink_name_given;
107
108     char* server_name; /* May be NULL */
109     int server_name_given;
110
111     char* client_name;
112     int client_name_given;
113
114     unsigned channels;
115     int channels_given;
116
117     int connect;
118     int connect_given;
119
120     unsigned buffersize;
121     int buffersize_given;
122
123     pa_channel_map map;
124     int map_given;
125 };
126
127
128 static const char* const valid_modargs[] = {
129     "sink_name",
130     "server_name",
131     "client_name",
132     "channels",
133     "connect",
134     "buffersize",
135     "channel_map",
136     NULL
137 };
138
139
140 /* Initialization functions. */
141 static int parse_options(struct options* o, const char* argument);
142 static void set_default_channels(pa_module* self, struct options* o);
143 static int create_sink(pa_module* self, struct options *o);
144 static void connect_ports(pa_module* self);
145 static int start_filling_ringbuffer(pa_module* self);
146
147 /* Various callbacks. */
148 static void jack_error_func(const char* t);
149 static pa_usec_t sink_get_latency_cb(pa_sink* s);
150 static int jack_process(jack_nframes_t nframes, void* arg);
151 static int jack_blocksize_cb(jack_nframes_t nframes, void* arg);
152 static void jack_shutdown(void* arg);
153 static void io_event_cb(pa_mainloop_api* m, pa_io_event* e, int fd,
154                         pa_io_event_flags_t flags, void* userdata);
155
156 /* The ringbuffer filler thread runs in this function. */
157 static void* fill_ringbuffer(void* arg);
158
159 /* request_render asks asynchronously the mainloop to call io_event_cb. */
160 static void request_render(struct userdata* u);
161
162
163 int pa__init(pa_core* c, pa_module* self) {
164     struct userdata* u = NULL;
165     struct options o;
166     unsigned i;
167    
168     assert(c);
169     assert(self);
170
171     o.sink_name = NULL;
172     o.server_name = NULL;
173     o.client_name = NULL;
174    
175     self->userdata = pa_xnew0(struct userdata, 1);
176     u = self->userdata;
177    
178     u->pipe_fds[0] = u->pipe_fds[1] = -1;
179     u->pipe_fd_type = 0;
180     u->ringbuffer_is_full = 0;
181     u->filler_thread_is_running = 0;
182     u->quit_requested = 0;
183     pthread_mutex_init(&u->buffersize_mutex, NULL);
184     pthread_mutex_init(&u->cond_mutex, NULL);
185     pthread_cond_init(&u->ringbuffer_cond, NULL);
186    
187     if (parse_options(&o, self->argument) != 0)
188         goto fail;
189    
190     jack_set_error_function(jack_error_func);
191    
192     if (!(u->j_client = jack_client_open(
193                           o.client_name,
194                           o.server_name ? JackServerName : JackNullOption,
195                           NULL, o.server_name))) {
196         pa_log_error("jack_client_open() failed.");
197         goto fail;
198     }
199     pa_log_info("Successfully connected as '%s'",
200                 jack_get_client_name(u->j_client));
201    
202     if (!o.channels_given)
203         set_default_channels(self, &o);
204    
205     u->channels = o.channels;
206    
207     if (!o.map_given)
208         pa_channel_map_init_auto(&o.map, u->channels, PA_CHANNEL_MAP_ALSA);
209    
210     for (i = 0; i < u->channels; i++) {
211         char* port_name = pa_sprintf_malloc(
212                               "out_%i:%s", i+1,
213                               pa_channel_position_to_string(o.map.map[i]));
214        
215         if (!(u->j_ports[i] = jack_port_register(
216                                   u->j_client, port_name,
217                                   JACK_DEFAULT_AUDIO_TYPE,
218                                   JackPortIsOutput|JackPortIsTerminal, 0))) {
219             pa_log("jack_port_register() failed.");
220             goto fail;
221         }
222        
223         pa_xfree(port_name);
224     }
225    
226     if (pipe(u->pipe_fds) < 0) {
227         pa_log("pipe() failed: %s", pa_cstrerror(errno));
228         goto fail;
229     }
230     pa_make_nonblock_fd(u->pipe_fds[1]);
231    
232     if (create_sink(self, &o) != 0)
233         goto fail;
234
235     u->frame_size = pa_frame_size(&u->sink->sample_spec);
236     u->j_buffersize = jack_get_buffer_size(u->j_client);
237    
238     /* If the ringbuffer size were equal to the jack buffer size, a full block
239        would never fit in the ringbuffer, because the ringbuffer can never be
240        totally full: one slot is always wasted. */
241     if (o.buffersize <= u->j_buffersize) {
242         o.buffersize = u->j_buffersize + 1;
243     }
244     /* The actual ringbuffer size will be rounded up to the nearest power of
245        two. */
246     if (!(u->ringbuffer = jack_ringbuffer_create(
247                               o.buffersize * u->frame_size))) {
248         pa_log("jack_ringbuffer_create() failed.");
249         goto fail;
250     }
251     assert((u->ringbuffer->size % sizeof(float)) == 0);
252     pa_log_info("buffersize is %u frames.",
253                 u->ringbuffer->size / u->frame_size);
254    
255     jack_set_process_callback(u->j_client, jack_process, u);
256     jack_set_buffer_size_callback(u->j_client, jack_blocksize_cb, u);
257     jack_on_shutdown(u->j_client, jack_shutdown, u);
258    
259     if (jack_activate(u->j_client)) {
260         pa_log("jack_activate() failed.");
261         goto fail;
262     }
263
264     if (o.connect)
265         connect_ports(self);
266
267     u->io_event = c->mainloop->io_new(c->mainloop, u->pipe_fds[0],
268                                       PA_IO_EVENT_INPUT, io_event_cb, self);
269    
270     if (start_filling_ringbuffer(self) != 0)
271         goto fail;
272
273     pa_xfree(o.sink_name);
274     pa_xfree(o.server_name);
275     pa_xfree(o.client_name);
276    
277     return 0;
278
279 fail:
280     pa_xfree(o.sink_name);
281     pa_xfree(o.server_name);
282     pa_xfree(o.client_name);
283     pa__done(c, self);
284
285     return -1;
286 }
287
288
289 static int parse_options(struct options* o, const char* argument) {
290     pa_modargs *ma = NULL;
291     const char* arg_val;
292     pa_strbuf* strbuf;
293    
294     assert(o);
295
296     if (!(ma = pa_modargs_new(argument, valid_modargs))) {
297         pa_log_error("Failed to parse module arguments.");
298         goto fail;
299     }
300
301     strbuf = pa_strbuf_new();
302     if ((arg_val = pa_modargs_get_value(ma, "sink_name", NULL))) {
303         pa_strbuf_puts(strbuf, arg_val);
304         o->sink_name = pa_strbuf_tostring(strbuf);
305         o->sink_name_given = 1;
306     } else {
307         pa_strbuf_puts(strbuf, DEFAULT_SINK_NAME);
308         o->sink_name = pa_strbuf_tostring(strbuf);
309         o->sink_name_given = 0;
310     }
311     pa_strbuf_free(strbuf);
312
313     strbuf = pa_strbuf_new();
314     if ((arg_val = pa_modargs_get_value(ma, "server_name", NULL))) {
315         pa_strbuf_puts(strbuf, arg_val);
316         o->server_name = pa_strbuf_tostring(strbuf);
317         o->server_name_given = 1;
318     } else {
319         o->server_name = NULL;
320         o->server_name_given = 0;
321     }
322     pa_strbuf_free(strbuf);
323
324     strbuf = pa_strbuf_new();
325     if ((arg_val = pa_modargs_get_value(ma, "client_name", NULL))) {
326         pa_strbuf_puts(strbuf, arg_val);
327         o->client_name = pa_strbuf_tostring(strbuf);
328         o->client_name_given = 1;
329     } else {
330         pa_strbuf_puts(strbuf, DEFAULT_CLIENT_NAME);
331         o->client_name = pa_strbuf_tostring(strbuf);
332         o->client_name_given = 1;
333     }
334     pa_strbuf_free(strbuf);
335
336     if (pa_modargs_get_value(ma, "channels", NULL)) {
337         o->channels_given = 1;
338         if (pa_modargs_get_value_u32(ma, "channels", &o->channels) < 0 ||
339             o->channels == 0 ||
340             o->channels >= PA_CHANNELS_MAX) {
341             pa_log_error("Failed to parse the \"channels\" argument.");
342             goto fail;
343         }
344     } else {
345         o->channels = 0; /* The actual default value is the number of physical
346                             input ports in jack (unknown at the moment), or if
347                             that's zero, then the default_sample_spec.channels
348                             of the core. */
349         o->channels_given = 0;
350     }
351
352     if (pa_modargs_get_value(ma, "connect", NULL)) {
353         o->connect_given = 1;
354         if (pa_modargs_get_value_boolean(ma, "connect", &o->connect) < 0) {
355             pa_log_error("Failed to parse the \"connect\" argument.");
356             goto fail;
357         }
358     } else {
359         o->connect = 1;
360         o->connect_given = 0;
361     }
362
363     if (pa_modargs_get_value(ma, "buffersize", NULL)) {
364         o->buffersize_given = 1;
365         if (pa_modargs_get_value_u32(ma, "buffersize", &o->buffersize) < 0) {
366             pa_log_error("Failed to parse the \"buffersize\" argument.");
367             goto fail;
368         }
369     } else {
370         o->buffersize = DEFAULT_RINGBUFFER_SIZE;
371         o->buffersize_given = 0;
372     }
373
374     if (pa_modargs_get_value(ma, "channel_map", NULL)) {
375         o->map_given = 1;
376         if (pa_modargs_get_channel_map(ma, &o->map) < 0) {
377             pa_log_error("Failed to parse the \"channel_map\" argument.");
378             goto fail;
379         }
380
381         /* channel_map specifies the channel count too. */
382         if (o->channels_given && (o->channels != o->map.channels)) {
383             pa_log_error(
384                 "\"channels\" and \"channel_map\" arguments conficted. If you "
385                 "use the \"channel_map\" argument, you can omit the "
386                 "\"channels\" argument.");
387             goto fail;
388         } else {
389             o->channels = o->map.channels;
390             o->channels_given = 1;
391         }
392     } else {
393         /* The actual default value is the default alsa mappings, but that
394            can't be set until the channel count is known. Here we initialize
395            the map to some valid value, although the value won't be used. */
396         pa_channel_map_init_stereo(&o->map);
397         o->map_given = 0;
398     }
399
400     pa_modargs_free(ma);
401
402     return 0;
403
404 fail:
405     if (ma)
406       pa_modargs_free(ma);
407
408     return -1;
409 }
410
411
412 static void set_default_channels(pa_module* self, struct options* o) {
413     struct userdata* u;
414     const char **ports, **p;
415    
416     assert(self);
417     assert(o);
418     assert(self->userdata);
419
420     u = self->userdata;
421    
422     assert(u->j_client);
423     assert(self->core);
424    
425     o->channels = 0;
426    
427     ports = jack_get_ports(u->j_client, NULL, JACK_DEFAULT_AUDIO_TYPE,
428                            JackPortIsPhysical|JackPortIsInput);
429    
430     for (p = ports; *p; p++)
431         o->channels++;
432    
433     free(ports);
434    
435     if (o->channels >= PA_CHANNELS_MAX)
436         o->channels = PA_CHANNELS_MAX - 1;
437    
438     if (o->channels == 0)
439         o->channels = self->core->default_sample_spec.channels;
440 }
441
442
443 static int create_sink(pa_module* self, struct options* o) {
444     struct userdata* u;
445     pa_sample_spec ss;
446     char *t;
447    
448     assert(self);
449     assert(o);
450     assert(self->userdata);
451
452     u = self->userdata;
453    
454     assert(u->j_client);
455    
456     ss.channels = u->channels;
457     ss.rate = jack_get_sample_rate(u->j_client);
458     ss.format = PA_SAMPLE_FLOAT32NE;
459     assert(pa_sample_spec_valid(&ss));
460
461     if (!(u->sink = pa_sink_new(self->core, __FILE__, o->sink_name, 0, &ss,
462                                 &o->map))) {
463         pa_log("failed to create sink.");
464         return -1;
465     }
466    
467     u->sink->userdata = u;
468     pa_sink_set_owner(u->sink, self);
469    
470     pa_sink_set_description(
471         u->sink,
472         t = pa_sprintf_malloc("Jack sink (%s)",
473                               jack_get_client_name(u->j_client)));
474     pa_xfree(t);
475    
476     u->sink->get_latency = sink_get_latency_cb;
477    
478     return 0;
479 }
480
481
482 static void connect_ports(pa_module* self) {
483     struct userdata* u;
484     unsigned i;
485     const char **ports, **p;
486    
487     assert(self);
488     assert(self->userdata);
489
490     u = self->userdata;
491    
492     assert(u->j_client);
493    
494     ports = jack_get_ports(u->j_client, NULL, JACK_DEFAULT_AUDIO_TYPE,
495                            JackPortIsPhysical|JackPortIsInput);
496    
497     for (i = 0, p = ports; i < u->channels; i++, p++) {
498         assert(u->j_ports[i]);
499        
500         if (!*p) {
501             pa_log("Not enough physical output ports, leaving unconnected.");
502             break;
503         }
504        
505         pa_log_info("connecting %s to %s",
506                     jack_port_name(u->j_ports[i]), *p);
507        
508         if (jack_connect(u->j_client, jack_port_name(u->j_ports[i]), *p)) {
509             pa_log("Failed to connect %s to %s, leaving unconnected.",
510                    jack_port_name(u->j_ports[i]), *p);
511             break;
512         }
513     }
514    
515     free(ports);
516 }
517
518
519 static int start_filling_ringbuffer(pa_module* self) {
520     struct userdata* u;
521     pthread_attr_t thread_attributes;
522
523     assert(self);
524     assert(self->userdata);
525
526     u = self->userdata;
527    
528     pthread_attr_init(&thread_attributes);
529    
530     if (pthread_attr_setinheritsched(&thread_attributes,
531                                      PTHREAD_INHERIT_SCHED) != 0) {
532         pa_log("pthread_attr_setinheritsched() failed.");
533         goto fail;
534     }
535     else if (pthread_create(&u->filler_thread, &thread_attributes,
536                             fill_ringbuffer, u) != 0) {
537         pa_log("pthread_create() failed.");
538         goto fail;
539     }
540    
541     u->filler_thread_is_running = 1;
542    
543     pthread_attr_destroy(&thread_attributes);
544
545     return 0;
546    
547 fail:
548     pthread_attr_destroy(&thread_attributes);
549     return -1;
550 }
551
552
553 static void jack_error_func(const char* t) {
554     pa_log_warn("JACK error >%s<", t);
555 }
556
557
558 static pa_usec_t sink_get_latency_cb(pa_sink* s) {
559     /* The latency is approximately the sum of the first port's latency,
560        buffersize of jack and the ringbuffer size. Maybe instead of using just
561        the first port, the max of all ports' latencies should be used? */
562     struct userdata* u;
563     jack_nframes_t l;
564    
565     assert(s);
566     assert(s->userdata);
567
568     u = s->userdata;
569    
570     l = jack_port_get_total_latency(u->j_client, u->j_ports[0]) +
571         u->j_buffersize + u->ringbuffer->size / u->frame_size;
572    
573     return pa_bytes_to_usec(l * u->frame_size, &s->sample_spec);
574 }
575
576
577 static int jack_process(jack_nframes_t nframes, void* arg) {
578     struct userdata* u = arg;
579     float* j_buffers[PA_CHANNELS_MAX];
580     unsigned nsamples = u->channels * nframes;
581     unsigned sample_idx_part1, sample_idx_part2;
582     jack_nframes_t frame_idx;
583     jack_ringbuffer_data_t data[2]; /* In case the readable area in the
584                                        ringbuffer is non-continuous, the data
585                                        will be split in two parts. */
586     unsigned chan;
587     unsigned samples_left_over;
588    
589     for (chan = 0; chan < u->channels; chan++) {
590         j_buffers[chan] = jack_port_get_buffer(u->j_ports[chan], nframes);
591     }
592    
593     jack_ringbuffer_get_read_vector(u->ringbuffer, data);
594    
595     /* We assume that the possible discontinuity doesn't happen in the middle
596      * of a sample. Should be a safe assumption. */
597     assert(((data[0].len % sizeof(float)) == 0) ||
598            (data[1].len == 0));
599    
600     /* Copy from the first part of data until enough samples are copied or the
601        first part ends. */
602     sample_idx_part1 = 0;
603     chan = 0;
604     frame_idx = 0;
605     while (sample_idx_part1 < nsamples &&
606            ((sample_idx_part1 + 1) * sizeof(float)) <= data[0].len) {
607         float *s = ((float*) data[0].buf) + sample_idx_part1;
608         float *d = j_buffers[chan] + frame_idx;
609         *d = *s;
610
611         sample_idx_part1++;
612         chan = (chan + 1) % u->channels;
613         frame_idx = sample_idx_part1 / u->channels;
614     }
615    
616     samples_left_over = nsamples - sample_idx_part1;
617    
618     /* Copy from the second part of data until enough samples are copied or the
619        second part ends. */
620     sample_idx_part2 = 0;
621     while (sample_idx_part2 < samples_left_over &&
622            ((sample_idx_part2 + 1) * sizeof(float)) <= data[1].len) {
623         float *s = ((float*) data[1].buf) + sample_idx_part2;
624         float *d = j_buffers[chan] + frame_idx;
625         *d = *s;
626
627         sample_idx_part2++;
628         chan = (chan + 1) % u->channels;
629         frame_idx = (sample_idx_part1 + sample_idx_part2) / u->channels;
630     }
631    
632     samples_left_over -= sample_idx_part2;
633    
634     /* If there's still samples left, fill the buffers with zeros. */
635     while (samples_left_over > 0) {
636         float *d = j_buffers[chan] + frame_idx;
637         *d = 0.0;
638
639         samples_left_over--;
640         chan = (chan + 1) % u->channels;
641         frame_idx = (nsamples - samples_left_over) / u->channels;
642     }
643    
644     jack_ringbuffer_read_advance(
645         u->ringbuffer, (sample_idx_part1 + sample_idx_part2) * sizeof(float));
646    
647     /* Tell the rendering part that there is room in the ringbuffer. */
648     u->ringbuffer_is_full = 0;
649     pthread_cond_signal(&u->ringbuffer_cond);
650    
651     return 0;
652 }
653
654
655 static int jack_blocksize_cb(jack_nframes_t nframes, void* arg) {
656     /* This gets called in the processing thread, so do we have to be realtime
657        safe? No, we can do whatever we want. User gets silence while we do it.
658       
659        In addition to just updating the j_buffersize field in userdata, we have
660        to create a new ringbuffer, if the new buffer size is bigger or equal to
661        the old ringbuffer size. */
662     struct userdata* u = arg;
663    
664     assert(u);
665    
666     /* We don't want to change the blocksize and the ringbuffer while rendering
667        is going on. */
668     pthread_mutex_lock(&u->buffersize_mutex);
669    
670     u->j_buffersize = nframes;
671    
672     if ((u->ringbuffer->size / u->frame_size) <= nframes) {
673         /* We have to create a new ringbuffer. What are we going to do with the
674            old data in the old buffer? We throw it away, because we're lazy
675            coders. The listening experience is likely to get ruined anyway
676            during the blocksize change. */
677         jack_ringbuffer_free(u->ringbuffer);
678        
679         /* The actual ringbuffer size will be rounded up to the nearest power
680            of two. */
681         if (!(u->ringbuffer =
682                   jack_ringbuffer_create((nframes + 1) * u->frame_size))) {
683             pa_log_error(
684                 "jack_ringbuffer_create() failed while changing jack's buffer "
685                 "size, module exiting.");
686             jack_client_close(u->j_client);
687             u->quit_requested = 1;
688         }
689         assert((u->ringbuffer->size % sizeof(float)) == 0);
690         pa_log_info("buffersize is %u frames.",
691                     u->ringbuffer->size / u->frame_size);
692     }
693    
694     pthread_mutex_unlock(&u->buffersize_mutex);
695    
696     return 0;
697 }
698
699
700 static void jack_shutdown(void* arg) {
701     struct userdata* u = arg;
702     assert(u);
703
704     u->quit_requested = 1;
705     request_render(u);
706 }
707
708
709 static void io_event_cb(pa_mainloop_api* m, pa_io_event* e, int fd,
710                         pa_io_event_flags_t flags, void* userdata) {
711     pa_module* self = userdata;
712     struct userdata* u;
713     char x;
714     jack_ringbuffer_data_t buffer[2]; /* The write area in the ringbuffer may
715                                          be split in two parts. */
716     pa_memchunk chunk; /* This is the data source. */
717     unsigned part1_length, part2_length;
718     unsigned sample_idx_part1, sample_idx_part2;
719     unsigned chan;
720     unsigned frame_size;
721    
722     assert(m);
723     assert(e);
724     assert(flags == PA_IO_EVENT_INPUT);
725     assert(self);
726     assert(self->userdata);
727
728     u = self->userdata;
729    
730     assert(u->pipe_fds[0] == fd);
731
732     pa_read(fd, &x, 1, &u->pipe_fd_type);
733
734     if (u->quit_requested) {
735         pa_module_unload_request(self);
736         return;
737     }
738
739     frame_size = u->frame_size;
740    
741     /* No blocksize changes during rendering, please. */
742     pthread_mutex_lock(&u->buffersize_mutex);
743    
744     jack_ringbuffer_get_write_vector(u->ringbuffer, buffer);
745     assert(((buffer[0].len % sizeof(float)) == 0) || (buffer[1].len == 0));
746    
747     part1_length = buffer[0].len / sizeof(float);
748     part2_length = buffer[1].len / sizeof(float);
749    
750     /* pa_sink_render_full doesn't accept zero length, so we have do the
751        copying only if there's data to copy, which actually makes a kind of
752        sense. */
753     if (part1_length > 0 || part2_length > 0) {
754         pa_sink_render_full(u->sink,
755                             (part1_length + part2_length) * sizeof(float),
756                             &chunk);
757        
758         /* Write to the first part of the buffer. */
759         for (sample_idx_part1 = 0;
760              sample_idx_part1 < part1_length;
761              sample_idx_part1++) {
762             float *s =
763                 ((float*) ((uint8_t*) chunk.memblock->data + chunk.index)) +
764                 sample_idx_part1;
765             float *d = ((float*) buffer[0].buf) + sample_idx_part1;
766             *d = *s;
767         }
768        
769         /* Write to the second part of the buffer. */
770         for (sample_idx_part2 = 0;
771              sample_idx_part2 < part2_length;
772              sample_idx_part2++) {
773             float *s =
774                 ((float*) ((uint8_t*) chunk.memblock->data + chunk.index)) +
775                 sample_idx_part1 + sample_idx_part2;
776             float *d = ((float*) buffer[1].buf) + sample_idx_part2;
777             *d = *s;
778         }
779        
780         pa_memblock_unref(chunk.memblock);
781        
782         jack_ringbuffer_write_advance(
783             u->ringbuffer, (part1_length + part2_length) * sizeof(float));
784     }
785    
786     /* Blocksize can be changed again. */
787     pthread_mutex_unlock(&u->buffersize_mutex);
788 }
789
790
791 static void* fill_ringbuffer(void* arg) {
792     struct userdata* u = arg;
793    
794     assert(u);
795    
796     while (!u->quit_requested) {
797         if (u->ringbuffer_is_full) {
798             pthread_mutex_lock(&u->cond_mutex);
799             pthread_cond_wait(&u->ringbuffer_cond,
800                               &u->cond_mutex);
801             pthread_mutex_unlock(&u->cond_mutex);
802         }
803         /* No, it's not full yet, but this must be set to one as soon as
804            possible, because if the jack thread manages to process another
805            block before we set this to one, we may end up waiting without
806            a reason. */
807         u->ringbuffer_is_full = 1;
808
809         request_render(u);
810     }
811    
812     return NULL;
813 }
814
815
816 static void request_render(struct userdata* u) {
817     char c = 'x';
818    
819     assert(u);
820    
821     assert(u->pipe_fds[1] >= 0);
822     pa_write(u->pipe_fds[1], &c, 1, &u->pipe_fd_type);
823 }
824
825 void pa__done(pa_core* c, pa_module* self) {
826     struct userdata* u;
827    
828     assert(c);
829     assert(self);
830
831     if (!self->userdata)
832         return;
833
834     u = self->userdata;
835    
836     if (u->filler_thread_is_running) {
837         u->quit_requested = 1;
838         pthread_cond_signal(&u->ringbuffer_cond);
839         pthread_join(u->filler_thread, NULL);
840     }
841    
842     if (u->j_client)
843         jack_client_close(u->j_client);
844
845     if (u->io_event)
846         c->mainloop->io_free(u->io_event);
847
848     if (u->sink) {
849         pa_sink_disconnect(u->sink);
850         pa_sink_unref(u->sink);
851     }
852    
853     if (u->ringbuffer)
854         jack_ringbuffer_free(u->ringbuffer);
855
856     if (u->pipe_fds[0] >= 0)
857         pa_close(u->pipe_fds[0]);
858     if (u->pipe_fds[1] >= 0)
859         pa_close(u->pipe_fds[1]);
860    
861     pthread_mutex_destroy(&u->buffersize_mutex);
862     pthread_cond_destroy(&u->ringbuffer_cond);
863     pthread_mutex_destroy(&u->cond_mutex);
864     pa_xfree(self->userdata);
865     self->userdata = NULL;
866 }