/
qubes-pw-module.c
1497 lines (1305 loc) · 48.3 KB
/
qubes-pw-module.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The Qubes OS Project, http://www.qubes-os.org
*
* Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
* Copyright © 2022 Demi Marie Obenour <demi@invisiblethingslab.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
/* PipeWire */
/* SPDX-FileCopyrightText: Copyright © 2021 Sanchayan Maity <sanchayan@asymptotic.io> */
/* SPDX-FileCopyrightText: Copyright © 2021-2023 Wim Taymans */
/* SPDX-License-Identifier: MIT */
/* Driving:
*
* When the module is driving, the loop is triggered under the following conditions:
*
* - If neither stream is running, the graph is triggered when the timeout expires.
* - If the playback stream is running and the capture stream is not, the graph is
* triggered when the playback vchan is 1/4 full.
* - If the capture stream is running and the playback stream is not, the graph is
* triggered:when the capture stream is 3/4 full.
* - If both vchans are running, both con
*/
#define QUBES_PA_SINK_VCHAN_PORT 4713
#define QUBES_PA_SOURCE_VCHAN_PORT 4714
#define QUBES_PA_SOURCE_START_CMD 0x00010001
#define QUBES_PA_SOURCE_STOP_CMD 0x00010000
#define QUBES_PA_SINK_CORK_CMD 0x00020000
#define QUBES_PA_SINK_UNCORK_CMD 0x00020001
#define QUBES_AUDIOVM_QUBESDB_ENTRY "/qubes-audio-domain-xid"
#define QUBES_AUDIOVM_PW_KEY "org.qubes-os.audio-domain-xid"
#define QUBES_PW_KEY_BUFFER_SPACE "org.qubes-os.vchan-buffer-size"
#define QUBES_PW_KEY_RECORD_BUFFER_SPACE "org.qubes-os.record-buffer-size"
#define QUBES_PW_KEY_PLAYBACK_BUFFER_SPACE "org.qubes-os.playback-buffer-size"
#define QUBES_PW_CAN_DRIVE PW_CHECK_VERSION(0, 3, 56)
#define QUBES_PW_HAS_TARGET PW_CHECK_VERSION(0, 3, 68)
/* C11 headers */
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdalign.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* POSIX headers */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <spa/utils/result.h>
#include <spa/utils/ringbuffer.h>
#include <spa/debug/pod.h>
#include <spa/pod/builder.h>
#include <spa/param/audio/format-utils.h>
#include <spa/param/audio/raw.h>
#include <pipewire/data-loop.h>
#include <pipewire/impl.h>
#include <pipewire/log.h>
#include <libvchan.h>
#include <qubesdb-client.h>
/** \page page_module_example_sink PipeWire Module: Example Sink
*/
#define NAME "qubes-audio"
#ifdef PW_LOG_TOPIC_STATIC
PW_LOG_TOPIC_STATIC(mod_topic, "mod." NAME);
#define PW_LOG_TOPIC_DEFAULT mod_topic
#elif defined PW_LOG_TOPIC_INIT
#error bad PipeWire includes?
#endif
#if PW_CHECK_VERSION(0, 3, 30)
#define MODULE_EXTRA_USAGE "[ stream.sink.props=<properties> ] " \
"[ stream.source.props=<properties> ] "
#else
#define MODULE_EXTRA_USAGE ""
#endif
#define MODULE_USAGE "[ node.latency=<latency as fraction> ] " \
"[ node.name=<name of the nodes> ] " \
"[ node.description=<description of the nodes> ] " \
"[ " QUBES_AUDIOVM_PW_KEY "=<AudioVM XID (default: use the one from QubesDB)> ] " \
"[ " QUBES_PW_KEY_BUFFER_SPACE "=<default vchan buffer space (headroom)> ] " \
"[ " QUBES_PW_KEY_RECORD_BUFFER_SPACE "=<recording headroom> ]" \
"[ " QUBES_PW_KEY_PLAYBACK_BUFFER_SPACE "=<playback headroom> ]" \
MODULE_EXTRA_USAGE
static const struct spa_dict_item module_props[] = {
{ PW_KEY_MODULE_AUTHOR, "Wim Taymans <wim.taymans@gmail.com>, "
"Demi Marie Obenour <demi@invisiblethingslab.com>" },
{ PW_KEY_MODULE_DESCRIPTION, "Qubes OS audio device" },
{ PW_KEY_MODULE_USAGE, MODULE_USAGE },
{ PW_KEY_MODULE_VERSION, "4.1.0" },
};
struct impl;
struct qubes_stream {
// Stream properties. Immutable after init.
struct pw_properties *stream_props;
// Pointer to stream. Immutable after init.
struct pw_stream *stream;
// Stream event listener. Accessed on main thread only.
struct spa_hook stream_listener;
// Rate match control. Pointer is immutable after being set.
// Pointee accessed on realtime thread only.
struct spa_io_rate_match *rate_match;
// Position control. Pointer is immutable after being set.
// Pointee accessed on realtime thread only.
struct spa_io_position *position;
// Audio format info. Accessed only on main thread.
struct spa_audio_info_raw info;
// Vchans, explicitly synchronized using message passing.
struct libvchan *vchan, *closed_vchan;
// Pointer to the implementation.
struct impl *impl;
atomic_size_t current_state, last_state;
struct spa_source source;
// Set at creation, immutable afterwards
size_t buffer_size;
// Whether the stream is open. Only accessed on RT thread.
bool is_open;
// 1 for capture, 0 for playback
// Set at creation, immutable afterwards
bool direction;
// Implicitly serialized by PipeWire, in theory at least (so atomic, just in case)
atomic_bool driving;
atomic_bool dead, in_use;
// Time information
uint64_t next_time;
};
static inline bool
qubes_stream_is_capture(struct qubes_stream *stream)
{
return stream->direction;
}
struct impl {
struct pw_context *context;
struct pw_properties *props;
struct pw_impl_module *module;
struct spa_hook module_listener;
struct pw_core *core;
struct spa_loop *data_loop, *main_loop;
struct spa_loop_utils *loop_utils;
#if QUBES_PW_CAN_DRIVE
struct spa_system *data_system;
struct pw_data_loop *pw_data_loop;
struct spa_loop_utils *data_loop_utils;
#endif
struct spa_hook core_proxy_listener;
struct spa_hook core_listener;
struct spa_source *timer;
struct qubes_stream stream[2];
uint32_t frame_size, domid;
bool do_disconnect, unloading;
};
static void unload_module(struct impl *impl)
{
if (!impl->unloading) {
impl->unloading = true;
pw_impl_module_destroy(impl->module);
}
}
static_assert(ATOMIC_BOOL_LOCK_FREE, "PipeWire agent requires lock-free atomic booleans");
static_assert(PW_DIRECTION_INPUT == 0, "wrong PW_DIRECTION_INPUT");
static_assert(PW_DIRECTION_OUTPUT == 1, "wrong PW_DIRECTION_OUTPUT");
static int vchan_error_callback(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data);
/**
* Disconnect a stream from its event loop. Must be called on the realtime
* thread.
*/
static void stop_watching_vchan(struct qubes_stream *stream)
{
if (stream->vchan) {
// Must do this first, so that EPOLL_CTL_DEL is called before the
// file descriptor is closed.
if (stream->impl)
spa_loop_remove_source(stream->impl->data_loop, &stream->source);
stream->closed_vchan = stream->vchan;
stream->vchan = NULL;
}
stream->is_open = false;
// Update the main-thread state asynchronously.
if (stream->impl)
spa_loop_invoke(stream->impl->main_loop,
vchan_error_callback, 0, NULL, 0, false,
stream);
}
#if QUBES_PW_CAN_DRIVE
/* Set the timer. Must be called on the realtime thread. */
static void set_timeout(struct impl *impl, uint64_t time)
{
struct timespec timeout, interval;
timeout.tv_sec = time / SPA_NSEC_PER_SEC;
timeout.tv_nsec = time % SPA_NSEC_PER_SEC;
interval.tv_sec = 0;
interval.tv_nsec = 0;
spa_loop_utils_update_timer(impl->data_loop_utils,
impl->timer, &timeout, &interval, true);
}
#ifndef SPA_SCALE32_UP
#define SPA_SCALE32_UP(val,num,denom) \
({ \
uint64_t _val = (val); \
uint64_t _denom = (denom); \
(uint32_t)(((_val) * (num) + (_denom)-1) / (_denom)); \
})
#endif
static void on_timeout(void *d, uint64_t expirations)
{
struct impl *impl = d;
uint64_t duration, current_time;
uint32_t rate;
int32_t avail;
for (int i = 0; i < 2; ++i) {
struct qubes_stream *stream = impl->stream + i;
if (!stream->driving)
continue;
struct spa_io_position *pos = stream->position;
libvchan_t *vchan = stream->vchan;
if (SPA_LIKELY(pos)) {
#if QUBES_PW_HAS_TARGET
duration = pos->clock.target_duration;
rate = pos->clock.target_rate.denom;
#else
duration = pos->clock.duration;
rate = pos->clock.rate.denom;
#endif
} else {
duration = 1024;
rate = 44100;
}
pw_log_trace("timeout %"PRIu64, duration);
current_time = impl->stream[i].next_time;
impl->stream[i].next_time += duration * 1e9 / rate;
switch (i) {
case PW_DIRECTION_OUTPUT: // capture
avail = vchan ? SPA_MAX(libvchan_data_ready(vchan), 0) : 0;
break;
case PW_DIRECTION_INPUT: // playback
avail = vchan ? SPA_MAX(libvchan_buffer_space(vchan), 0) - (int32_t)impl->stream[i].buffer_size : 0;
break;
default:
abort();
}
if (SPA_LIKELY(pos)) {
pos->clock.nsec = current_time;
pos->clock.position += pos->clock.duration;
#if QUBES_PW_HAS_TARGET
pos->clock.rate = pos->clock.target_rate;
pos->clock.duration = pos->clock.target_duration;
#endif
pos->clock.delay = SPA_SCALE32_UP(avail, rate, 44100);
pos->clock.rate_diff = 1;
pos->clock.next_nsec = impl->stream[i].next_time;
}
set_timeout(impl, impl->stream[i].next_time);
pw_stream_trigger_process(impl->stream[i].stream);
}
}
static int add_timeout_cb(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data)
{
struct impl *impl = user_data;
impl->timer = spa_loop_utils_add_timer(impl->data_loop_utils, on_timeout, impl);
if (impl->timer == NULL)
return -errno;
return 0;
}
#endif
static int remove_stream_cb(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data)
{
stop_watching_vchan(user_data);
return 0;
}
static void vchan_ready(struct spa_source *source);
/**
* Called on the realtime thread after creating a vchan. The main
* thread is suspended.
*
* @param loop The event loop to use.
* @param async Was this called synchronously or asynchronously?
* @param seq a 32-bit sequence number.
* @param data The data argument to spa_loop_invoke(). Not used by this
* function.
* @param size The size of that data.
* @param user_data The user data passed to spa_loop_invoke().
*/
static int add_stream(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data)
{
struct qubes_stream *stream = user_data;
if (stream->dead)
return -ESHUTDOWN;
spa_assert(stream->closed_vchan);
spa_assert(!stream->vchan);
stream->vchan = stream->closed_vchan;
stream->closed_vchan = NULL;
stream->source.loop = stream->impl->data_loop;
stream->source.func = vchan_ready;
stream->source.data = stream;
stream->source.fd = libvchan_fd_for_select(stream->vchan);
stream->source.mask = SPA_IO_IN;
return spa_loop_add_source(loop, &stream->source);
}
/**
* Connect a Qubes stream. Must be called on the main thread.
*
* @param stream The stream to connect.
*/
static void connect_stream(struct qubes_stream *stream)
{
const char *msg = qubes_stream_is_capture(stream) ? "capture" : "playback";
uint16_t domid = stream->impl->domid;
spa_assert(stream->vchan == NULL);
spa_assert(stream->closed_vchan == NULL);
if (qubes_stream_is_capture(stream)) { // capture
stream->closed_vchan = libvchan_server_init((int)domid, QUBES_PA_SOURCE_VCHAN_PORT, stream->buffer_size, 128);
} else { // playback
stream->closed_vchan = libvchan_server_init((int)domid, QUBES_PA_SINK_VCHAN_PORT, 128, stream->buffer_size);
if (stream->closed_vchan != NULL) {
int ready = libvchan_buffer_space(stream->closed_vchan);
if (ready >= 0)
stream->buffer_size = (uint32_t)ready;
}
}
if (stream->closed_vchan == NULL) {
pw_log_error("can't create %s vchan, audio will not work", msg);
}
if (spa_loop_invoke(stream->impl->data_loop, add_stream, 0, NULL, 0, true, stream))
pw_log_error("spa_loop_add_source() failed, audio will not work");
return;
}
/**
* Called on the main thread to shut down a stream.
*
* \param stream The stream to shut down.
*/
static void stream_shutdown(struct qubes_stream *stream)
{
if (stream->stream)
pw_stream_disconnect(stream->stream);
pw_log_info("Closing stale vchan");
if (stream->closed_vchan)
libvchan_close(stream->closed_vchan);
stream->closed_vchan = NULL;
}
/**
* Called on the main thread to destroy a stream.
*/
static void stream_destroy(struct impl *impl, enum spa_direction direction)
{
struct qubes_stream *stream = impl->stream + direction;
if (stream->dead)
return;
stream->dead = true;
spa_loop_invoke(impl->data_loop, remove_stream_cb, 0, NULL, 0, true, stream);
/* after this point the realtime thread is definitely aware of the shutdown */
stream_shutdown(stream);
spa_hook_remove(&stream->stream_listener);
stream->stream = NULL;
if (stream->stream_props)
pw_properties_free(stream->stream_props);
}
/**
* Called on the main thread to destroy the capture stream.
*/
static void capture_stream_destroy(void *d)
{
stream_destroy(d, PW_DIRECTION_INPUT);
}
/**
* Called on the main thread to destroy the playback stream.
*/
static void playback_stream_destroy(void *d)
{
stream_destroy(d, PW_DIRECTION_OUTPUT);
}
/** Called on the main thread to set the stream state */
static void set_stream_state(struct qubes_stream *stream, bool state)
{
static_assert(atomic_is_lock_free(&stream->current_state),
"PipeWire agent requires lock-free atomic size_t");
static_assert(atomic_is_lock_free(&stream->driving),
"PipeWire agent requires lock-free atomic bool");
stream->current_state = state;
}
static const struct pw_stream_events capture_stream_events, playback_stream_events;
/**
* Called on the main thread when a vchan has been disconnected.
*/
static int vchan_error_callback(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data)
{
struct qubes_stream *stream = user_data;
spa_assert(!stream->vchan);
stream_shutdown(stream);
if (!stream->dead)
connect_stream(stream);
return 0;
}
static void discard_unwanted_recorded_data(struct qubes_stream *stream);
/* Called on the main thread by spa_loop_invoke() from vchan_ready() */
static int main_thread_connect(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data)
{
struct qubes_stream *stream;
uint32_t n_params = 0;
const struct spa_pod *params[1];
uint8_t buffer[1024];
struct spa_pod_builder b = { 0 };
if ((stream = user_data)->dead)
return 0;
spa_pod_builder_init(&b, buffer, sizeof(buffer));
params[n_params++] = spa_format_audio_raw_build(&b,
SPA_PARAM_EnumFormat, &stream->info);
if (pw_stream_connect(stream->stream,
stream->direction,
PW_ID_ANY,
PW_STREAM_FLAG_AUTOCONNECT |
PW_STREAM_FLAG_MAP_BUFFERS |
PW_STREAM_FLAG_RT_PROCESS |
0,
params, n_params) < 0)
pw_log_error("Could not connect stream: %m");
return 0;
}
static int process_control_commands(struct impl *impl);
static int process_control_commands_cb(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data)
{
return process_control_commands(user_data);
}
static const struct spa_audio_info_raw qubes_audio_format = {
.format = SPA_AUDIO_FORMAT_S16_LE,
.flags = 0,
.rate = 44100,
.channels = 2,
.position = { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR },
};
/**
* Called on the realtime thread when a vchan's event channel
* is signaled. Must not be called on any other thread.
*
* @param source The spa_source that triggered the event.
*/
static void vchan_ready(struct spa_source *source)
{
struct qubes_stream *stream = source->data;
struct qubes_stream *playback_stream = stream->impl->stream;
// 0: Check if the vchan exists
if (!stream->vchan) {
spa_assert(!stream->is_open && "no vchan on open stream?");
pw_log_error("vchan_ready() called with vchan closed???");
return;
}
// 1: Acknowledge vchan event
pw_log_debug("Waiting for vchan");
libvchan_wait(stream->vchan);
pw_log_debug("Vchan awaited");
// 2: Figure out if stream is open
bool is_open = libvchan_is_open(stream->vchan);
if (is_open != stream->is_open) {
if (is_open) {
// vchan connected
spa_loop_invoke(stream->impl->main_loop,
main_thread_connect, 0, NULL, 0, false, stream);
if (qubes_stream_is_capture(stream)) {
// vchan just opened, no need to check for buffer space
const uint32_t control_commands[2] = {
(stream->last_state = stream->current_state) ?
QUBES_PA_SOURCE_START_CMD : QUBES_PA_SOURCE_STOP_CMD,
(playback_stream->last_state = playback_stream->current_state) ?
QUBES_PA_SINK_UNCORK_CMD : QUBES_PA_SINK_CORK_CMD,
};
if (libvchan_write(stream->vchan, control_commands, sizeof control_commands) !=
sizeof control_commands)
pw_log_error("Cannot write stream initial states to vchan");
}
stream->is_open = true;
} else {
// vchan disconnected. Stop watching for events on it.
stop_watching_vchan(stream);
}
}
if (!is_open)
return; /* vchan closed */
if (qubes_stream_is_capture(stream)) {
discard_unwanted_recorded_data(stream);
process_control_commands(stream->impl);
}
}
/**
* Called on the realtime thread to discard unwanted data from the daemon.
*/
static void discard_unwanted_recorded_data(struct qubes_stream *stream)
{
if (stream->last_state)
return; // Nothing to do, capture_stream_process() will deal with it
if (!stream->vchan)
return; // No vchan
if (!libvchan_is_open(stream->vchan))
return; // vchan closed
// Discard unexpected data
char buf[512];
int ready = libvchan_data_ready(stream->vchan);
if (ready <= 0)
return;
size_t to_read = (size_t)ready;
pw_log_trace("Discarding %d bytes of unwanted data", ready);
while (to_read > 0) {
int res = libvchan_read(stream->vchan, buf, to_read > sizeof buf ? sizeof buf : to_read);
if (res <= 0)
break;
to_read -= (size_t)res;
}
}
#if QUBES_PW_CAN_DRIVE
static uint64_t get_time_ns(struct impl *impl)
{
struct timespec now;
if (spa_system_clock_gettime(impl->data_system, CLOCK_MONOTONIC, &now) < 0)
return 0;
return SPA_TIMESPEC_TO_NSEC(&now);
}
#endif
static void rt_set_stream_state(struct qubes_stream *stream, bool active)
{
#if QUBES_PW_CAN_DRIVE
if (active) {
bool driving = pw_stream_is_driving(stream->stream);
if (driving && !stream->driving) {
stream->next_time = get_time_ns(stream->impl);
set_timeout(stream->impl, stream->next_time);
}
stream->driving = driving;
} else {
stream->next_time = 0;
stream->driving = false;
set_timeout(stream->impl, 0);
}
#endif
stream->last_state = active;
}
/**
* Called on the realtime thread to process control commands.
*/
static int process_control_commands(struct impl *impl)
{
struct qubes_stream *capture_stream = impl->stream + PW_DIRECTION_OUTPUT,
*playback_stream = impl->stream + PW_DIRECTION_INPUT;
bool new_state = playback_stream->current_state;
struct libvchan *control_vchan = capture_stream->vchan;
if (!control_vchan) {
pw_log_error("Control vchan closed, cannot issue control command");
return -EPIPE;
}
if (new_state != playback_stream->last_state) {
uint32_t cmd = new_state ? QUBES_PA_SINK_UNCORK_CMD : QUBES_PA_SINK_CORK_CMD;
if (libvchan_buffer_space(control_vchan) < (int)sizeof(cmd)) {
pw_log_error("cannot write command to control vchan: no buffer space");
return -ENOBUFS;
}
if (libvchan_send(control_vchan, &cmd, sizeof(cmd)) != sizeof(cmd)) {
pw_log_error("error writing command to control vchan");
return -EPROTO;
}
pw_log_info("Audio playback %s", new_state ? "started" : "stopped");
#if QUBES_PW_CAN_DRIVE
if (new_state && pw_stream_is_driving(playback_stream->stream)) {
// If *either* stream is driving, use the playback vchan to drive
// the graph. Specifically, drive the graph when there is enough
// space in the playback vchan for a cycle.
pw_log_trace("Qubes OS playback node is driving");
}
#endif
rt_set_stream_state(playback_stream, new_state);
}
new_state = capture_stream->current_state;
if (new_state != capture_stream->last_state) {
uint32_t cmd = new_state ? QUBES_PA_SOURCE_START_CMD : QUBES_PA_SOURCE_STOP_CMD;
if (libvchan_buffer_space(control_vchan) < (int)sizeof(cmd)) {
pw_log_error("cannot write command to control vchan: no buffer space");
return -ENOSPC;
}
if (libvchan_send(control_vchan, &cmd, sizeof(cmd)) != sizeof(cmd)) {
pw_log_error("error writing command to control vchan");
return -ENOSPC;
}
pw_log_trace("Audio capturing %s", new_state ? "started" : "stopped");
#if QUBES_PW_CAN_DRIVE
if (new_state && pw_stream_is_driving(capture_stream->stream)) {
pw_log_trace("Qubes OS capture node is driving");
}
#endif
rt_set_stream_state(capture_stream, new_state);
}
return 0;
}
static int rt_set_io(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data)
{
struct qubes_stream *stream = user_data;
void *io_obj = *(void *const *)data;
switch (seq) {
case SPA_IO_RateMatch:
if (io_obj != NULL && (size < sizeof *stream->rate_match || !SPA_IS_ALIGNED(io_obj, alignof(*stream->rate_match))))
return -EINVAL;
*(volatile struct spa_io_rate_match *)io_obj;
stream->rate_match = io_obj;
break;
case SPA_IO_Position:
if (io_obj != NULL && (size < sizeof *stream->position || !SPA_IS_ALIGNED(io_obj, alignof(*stream->position))))
return -EINVAL;
*(volatile struct spa_io_position *)io_obj;
stream->position = io_obj;
break;
}
return 0;
}
static void capture_stream_io_changed(void *data, uint32_t id, void *area, uint32_t size)
{
struct impl *impl = data;
int status;
do {
status = spa_loop_invoke(impl->data_loop, rt_set_io,
id, &area, size, true,
&impl->stream[PW_DIRECTION_OUTPUT]);
} while (status == -EPIPE);
}
static void playback_stream_io_changed(void *data, uint32_t id, void *area, uint32_t size)
{
struct impl *impl = data;
int status;
do {
status = spa_loop_invoke(impl->data_loop, rt_set_io,
id, &area, size, true,
&impl->stream[PW_DIRECTION_INPUT]);
} while (status == -EPIPE);
}
static void stream_state_changed_common(void *d, enum pw_stream_state old,
enum pw_stream_state state, const char *error, bool playback)
{
struct impl *impl = d;
const char *const name = playback ? "playback" : "capture";
switch (state) {
case PW_STREAM_STATE_ERROR:
pw_log_error("%s error: %s", name, error ? error : "(null)");
set_stream_state(&impl->stream[playback ? PW_DIRECTION_INPUT : PW_DIRECTION_OUTPUT], false);
break;
case PW_STREAM_STATE_UNCONNECTED:
pw_log_debug("%s unconnected", name);
set_stream_state(&impl->stream[playback ? PW_DIRECTION_INPUT : PW_DIRECTION_OUTPUT], false);
break;
case PW_STREAM_STATE_CONNECTING:
pw_log_debug("%s connected", name);
return;
case PW_STREAM_STATE_PAUSED:
pw_log_debug("%s paused", name);
set_stream_state(&impl->stream[playback ? PW_DIRECTION_INPUT : PW_DIRECTION_OUTPUT], false);
break;
case PW_STREAM_STATE_STREAMING:
pw_log_debug("%s streaming", name);
set_stream_state(&impl->stream[playback ? PW_DIRECTION_INPUT : PW_DIRECTION_OUTPUT], true);
break;
default:
pw_log_error("unknown %s stream state %d", name, state);
return;
}
spa_loop_invoke(impl->data_loop, process_control_commands_cb, 0, NULL, 0, true, impl);
pw_log_debug("Successfully queued message");
}
static void playback_stream_state_changed(void *d, enum pw_stream_state old,
enum pw_stream_state state, const char *error)
{
return stream_state_changed_common(d, old, state, error, true);
}
static void capture_stream_state_changed(void *d, enum pw_stream_state old,
enum pw_stream_state state, const char *error)
{
return stream_state_changed_common(d, old, state, error, false);
}
static void capture_stream_process(void *d)
{
struct impl *impl = d;
struct pw_buffer *b;
struct qubes_stream *stream = impl->stream + PW_DIRECTION_OUTPUT;
uint8_t *dst;
uint32_t bytes_ready = 0, size;
if ((b = pw_stream_dequeue_buffer(stream->stream)) == NULL) {
pw_log_warn("out of capture buffers: %m");
return;
}
if (!stream->vchan || !libvchan_is_open(stream->vchan))
pw_log_error("vchan not open yet!");
else {
int ready = libvchan_data_ready(stream->vchan);
if (ready < 0)
pw_log_error("vchan problem!");
else
bytes_ready = (uint32_t)ready;
}
struct spa_buffer *buf = b->buffer;
if (buf->n_datas < 1 || (dst = buf->datas[0].data) == NULL)
goto done;
buf->datas[0].chunk->offset = 0;
buf->datas[0].chunk->stride = 4;
buf->datas[0].chunk->size = 0;
spa_assert(buf->n_datas == 1 && "wrong number of datas");
// TODO: handle more data
#if PW_CHECK_VERSION(0, 3, 49)
if (__builtin_mul_overflow(b->requested ? b->requested : 2048, impl->frame_size, &size)) {
pw_log_error("Overflow calculating amount of data there is room for????");
goto done;
}
size = SPA_MIN(size, buf->datas[0].maxsize);
#else
size = buf->datas[0].maxsize;
#endif
buf->datas[0].chunk->size = size;
if (size > bytes_ready) {
pw_log_warn("Underrun: asked to read %" PRIu32 " bytes, but only %d available", size, (int)bytes_ready);
memset(dst + bytes_ready, 0, size - bytes_ready);
size = bytes_ready;
}
pw_log_trace("reading %" PRIu32 " bytes from vchan", size);
if (size && libvchan_read(stream->vchan, dst, size) != (int)size) {
pw_log_error("vchan error: %m");
// avoid recording uninitialized memory
memset(dst, 0, size);
}
done:
pw_stream_queue_buffer(stream->stream, b);
}
static void playback_stream_process(void *d)
{
struct impl *impl = d;
struct pw_buffer *buf;
struct qubes_stream *stream = impl->stream + PW_DIRECTION_INPUT;
struct qubes_stream *capture_stream = impl->stream + PW_DIRECTION_OUTPUT;
struct spa_data *bd;
uint8_t *data;
uint32_t size;
if (!stream->vchan || !libvchan_is_open(stream->vchan)) {
pw_log_error("Cannot read data, vchan not functional");
return;
}
int ready = libvchan_buffer_space(stream->vchan);
discard_unwanted_recorded_data(capture_stream);
pw_log_trace("%d bytes ready for writing", ready);
if ((buf = pw_stream_dequeue_buffer(stream->stream)) == NULL) {
pw_log_error("out of buffers: %m");
return;
}
spa_assert(buf->buffer->n_datas == 1 && "wrong number of datas");
bd = &buf->buffer->datas[0];
spa_assert(bd->chunk->offset == 0);
data = bd->data + bd->chunk->offset;
size = bd->chunk->size;
if (ready <= 0 || size > (uint32_t)ready) {
pw_log_warn("Overrun: asked to write %" PRIu32 " bytes, but can only write %d", size, ready);
if (stream->last_state) {
// Force process_control_commands() to send QUBES_PA_SINK_UNCORK_CMD
stream->last_state = 2;
}
process_control_commands(stream->impl);
size = ready;
}
pw_log_trace("writing %" PRIu32 " bytes to vchan", size);
if (size > 0 && libvchan_write(stream->vchan, data, size) != (int)size) {
pw_log_error("vchan error: %m");
return;
}
pw_stream_queue_buffer(stream->stream, buf);
}
static void stream_param_changed(void *data, uint32_t id,
const struct spa_pod *param, enum spa_direction direction)
{
struct impl *impl = data;
uint32_t media_type = UINT32_MAX, media_subtype = UINT32_MAX;
struct spa_audio_info_raw info = { 0 };
uint64_t params_buffer[64];
int res;
struct spa_pod_builder b = SPA_POD_BUILDER_INIT(params_buffer, sizeof(params_buffer));
const struct spa_pod *params[5];
switch (id) {
case SPA_PARAM_Format:
break;
case SPA_PARAM_Props:
/* TODO: reconfigure the stream according to the new properties */
return;
#if PW_CHECK_VERSION(0, 3, 29)
case SPA_PARAM_Latency:
/* TODO: latency reporting */
break;
#endif
#if PW_CHECK_VERSION(0, 3, 79)
case SPA_PARAM_Tag:
/* TODO: tag reporting */
break;
#endif
default:
pw_log_info("Unknown param ID %" PRIu32, id);
return;
}
spa_assert(direction >= 0 && direction <= 1);
if (param == NULL)
goto doit;
if ((res = spa_format_parse(param, &media_type, &media_subtype)) < 0) {
errno = -res;
pw_log_error("spa_format_parse() failed: %m");
errno = -res;
return;
}
if (media_type != SPA_MEDIA_TYPE_audio ||
media_subtype != SPA_MEDIA_SUBTYPE_raw) {
pw_log_error("Ignoring format info that isn't for raw audio");
errno = ENOTSUP;
return;
}
if (spa_format_audio_raw_parse(param, &info) < 0) {
pw_log_error("Could not parse raw audio format info");
errno = ENOTSUP;
return;
}
if (info.format != SPA_AUDIO_FORMAT_S16_LE) {
pw_log_error("Unsupported audio format %d", info.format);
errno = ENOTSUP;
return;
}
if (info.rate != qubes_audio_format.rate) {
pw_log_error("Unsupported audio rate %" PRIu32, info.rate);