This repository has been archived by the owner on Jan 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmodule-echo-cancel.c
2277 lines (1774 loc) · 74.5 KB
/
module-echo-cancel.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
/***
This file is part of PulseAudio.
Copyright 2010 Wim Taymans <wim.taymans@gmail.com>
Based on module-virtual-sink.c
module-virtual-source.c
module-loopback.c
Copyright 2010 Intel Corporation
Contributor: Pierre-Louis Bossart <pierre-louis.bossart@intel.com>
PulseAudio is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License,
or (at your option) any later version.
PulseAudio 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 Lesser General Public License
along with PulseAudio; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA.
***/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <math.h>
#include "echo-cancel.h"
#include <pulse/xmalloc.h>
#include <pulse/timeval.h>
#include <pulse/rtclock.h>
#include <pulsecore/i18n.h>
#include <pulsecore/atomic.h>
#include <pulsecore/macro.h>
#include <pulsecore/namereg.h>
#include <pulsecore/sink.h>
#include <pulsecore/module.h>
#include <pulsecore/core-rtclock.h>
#include <pulsecore/core-util.h>
#include <pulsecore/modargs.h>
#include <pulsecore/log.h>
#include <pulsecore/rtpoll.h>
#include <pulsecore/sample-util.h>
#include <pulsecore/ltdl-helper.h>
#include "module-echo-cancel-symdef.h"
PA_MODULE_AUTHOR("Wim Taymans");
PA_MODULE_DESCRIPTION("Echo Cancellation");
PA_MODULE_VERSION(PACKAGE_VERSION);
PA_MODULE_LOAD_ONCE(false);
PA_MODULE_USAGE(
_("source_name=<name for the source> "
"source_properties=<properties for the source> "
"source_master=<name of source to filter> "
"sink_name=<name for the sink> "
"sink_properties=<properties for the sink> "
"sink_master=<name of sink to filter> "
"adjust_time=<how often to readjust rates in s> "
"adjust_threshold=<how much drift to readjust after in ms> "
"format=<sample format> "
"rate=<sample rate> "
"channels=<number of channels> "
"channel_map=<channel map> "
"aec_method=<implementation to use> "
"aec_args=<parameters for the AEC engine> "
"save_aec=<save AEC data in /tmp> "
"autoloaded=<set if this module is being loaded automatically> "
"use_volume_sharing=<yes or no> "
));
/* NOTE: Make sure the enum and ec_table are maintained in the correct order */
typedef enum {
PA_ECHO_CANCELLER_INVALID = -1,
PA_ECHO_CANCELLER_NULL,
#ifdef HAVE_SPEEX
PA_ECHO_CANCELLER_SPEEX,
#endif
#ifdef HAVE_ADRIAN_EC
PA_ECHO_CANCELLER_ADRIAN,
#endif
#ifdef HAVE_WEBRTC
PA_ECHO_CANCELLER_WEBRTC,
#endif
} pa_echo_canceller_method_t;
#ifdef HAVE_WEBRTC
#define DEFAULT_ECHO_CANCELLER "webrtc"
#else
#define DEFAULT_ECHO_CANCELLER "speex"
#endif
static const pa_echo_canceller ec_table[] = {
{
/* Null, Dummy echo canceller (just copies data) */
.init = pa_null_ec_init,
.run = pa_null_ec_run,
.done = pa_null_ec_done,
},
#ifdef HAVE_SPEEX
{
/* Speex */
.init = pa_speex_ec_init,
.run = pa_speex_ec_run,
.done = pa_speex_ec_done,
},
#endif
#ifdef HAVE_ADRIAN_EC
{
/* Adrian Andre's NLMS implementation */
.init = pa_adrian_ec_init,
.run = pa_adrian_ec_run,
.done = pa_adrian_ec_done,
},
#endif
#ifdef HAVE_WEBRTC
{
/* WebRTC's audio processing engine */
.init = pa_webrtc_ec_init,
.play = pa_webrtc_ec_play,
.record = pa_webrtc_ec_record,
.set_drift = pa_webrtc_ec_set_drift,
.run = pa_webrtc_ec_run,
.done = pa_webrtc_ec_done,
},
#endif
};
#define DEFAULT_RATE 32000
#define DEFAULT_CHANNELS 1
#define DEFAULT_ADJUST_TIME_USEC (1*PA_USEC_PER_SEC)
#define DEFAULT_ADJUST_TOLERANCE (5*PA_USEC_PER_MSEC)
#define DEFAULT_SAVE_AEC false
#define DEFAULT_AUTOLOADED false
#define MEMBLOCKQ_MAXLENGTH (16*1024*1024)
/* Can only be used in main context */
#define IS_ACTIVE(u) ((pa_source_get_state((u)->source) == PA_SOURCE_RUNNING) && \
(pa_sink_get_state((u)->sink) == PA_SINK_RUNNING))
/* This module creates a new (virtual) source and sink.
*
* The data sent to the new sink is kept in a memblockq before being
* forwarded to the real sink_master.
*
* Data read from source_master is matched against the saved sink data and
* echo canceled data is then pushed onto the new source.
*
* Both source and sink masters have their own threads to push/pull data
* respectively. We however perform all our actions in the source IO thread.
* To do this we send all played samples to the source IO thread where they
* are then pushed into the memblockq.
*
* Alignment is performed in two steps:
*
* 1) when something happens that requires quick adjustment of the alignment of
* capture and playback samples, we perform a resync. This adjusts the
* position in the playback memblock to the requested sample. Quick
* adjustments include moving the playback samples before the capture
* samples (because else the echo canceler does not work) or when the
* playback pointer drifts too far away.
*
* 2) periodically check the difference between capture and playback. We use a
* low and high watermark for adjusting the alignment. Playback should always
* be before capture and the difference should not be bigger than one frame
* size. We would ideally like to resample the sink_input but most driver
* don't give enough accuracy to be able to do that right now.
*/
struct userdata;
struct pa_echo_canceller_msg {
pa_msgobject parent;
struct userdata *userdata;
};
PA_DEFINE_PRIVATE_CLASS(pa_echo_canceller_msg, pa_msgobject);
#define PA_ECHO_CANCELLER_MSG(o) (pa_echo_canceller_msg_cast(o))
struct snapshot {
pa_usec_t sink_now;
pa_usec_t sink_latency;
size_t sink_delay;
int64_t send_counter;
pa_usec_t source_now;
pa_usec_t source_latency;
size_t source_delay;
int64_t recv_counter;
size_t rlen;
size_t plen;
};
struct userdata {
pa_core *core;
pa_module *module;
bool autoloaded;
bool dead;
bool save_aec;
pa_echo_canceller *ec;
uint32_t source_output_blocksize;
uint32_t source_blocksize;
uint32_t sink_blocksize;
bool need_realign;
/* to wakeup the source I/O thread */
pa_asyncmsgq *asyncmsgq;
pa_rtpoll_item *rtpoll_item_read, *rtpoll_item_write;
pa_source *source;
bool source_auto_desc;
pa_source_output *source_output;
pa_memblockq *source_memblockq; /* echo canceler needs fixed sized chunks */
size_t source_skip;
pa_sink *sink;
bool sink_auto_desc;
pa_sink_input *sink_input;
pa_memblockq *sink_memblockq;
int64_t send_counter; /* updated in sink IO thread */
int64_t recv_counter;
size_t sink_skip;
/* Bytes left over from previous iteration */
size_t sink_rem;
size_t source_rem;
pa_atomic_t request_resync;
pa_time_event *time_event;
pa_usec_t adjust_time;
int adjust_threshold;
FILE *captured_file;
FILE *played_file;
FILE *canceled_file;
FILE *drift_file;
bool use_volume_sharing;
struct {
pa_cvolume current_volume;
} thread_info;
};
static void source_output_snapshot_within_thread(struct userdata *u, struct snapshot *snapshot);
static const char* const valid_modargs[] = {
"source_name",
"source_properties",
"source_master",
"sink_name",
"sink_properties",
"sink_master",
"adjust_time",
"adjust_threshold",
"format",
"rate",
"channels",
"channel_map",
"aec_method",
"aec_args",
"save_aec",
"autoloaded",
"use_volume_sharing",
NULL
};
enum {
SOURCE_OUTPUT_MESSAGE_POST = PA_SOURCE_OUTPUT_MESSAGE_MAX,
SOURCE_OUTPUT_MESSAGE_REWIND,
SOURCE_OUTPUT_MESSAGE_LATENCY_SNAPSHOT,
SOURCE_OUTPUT_MESSAGE_APPLY_DIFF_TIME
};
enum {
SINK_INPUT_MESSAGE_LATENCY_SNAPSHOT
};
enum {
ECHO_CANCELLER_MESSAGE_SET_VOLUME,
};
static int64_t calc_diff(struct userdata *u, struct snapshot *snapshot) {
int64_t diff_time, buffer_latency;
pa_usec_t plen, rlen, source_delay, sink_delay, recv_counter, send_counter;
/* get latency difference between playback and record */
plen = pa_bytes_to_usec(snapshot->plen, &u->sink_input->sample_spec);
rlen = pa_bytes_to_usec(snapshot->rlen, &u->source_output->sample_spec);
if (plen > rlen)
buffer_latency = plen - rlen;
else
buffer_latency = 0;
source_delay = pa_bytes_to_usec(snapshot->source_delay, &u->source_output->sample_spec);
sink_delay = pa_bytes_to_usec(snapshot->sink_delay, &u->sink_input->sample_spec);
buffer_latency += source_delay + sink_delay;
/* add the latency difference due to samples not yet transferred */
send_counter = pa_bytes_to_usec(snapshot->send_counter, &u->sink->sample_spec);
recv_counter = pa_bytes_to_usec(snapshot->recv_counter, &u->sink->sample_spec);
if (recv_counter <= send_counter)
buffer_latency += (int64_t) (send_counter - recv_counter);
else
buffer_latency += PA_CLIP_SUB(buffer_latency, (int64_t) (recv_counter - send_counter));
/* capture and playback are perfectly aligned when diff_time is 0 */
diff_time = (snapshot->sink_now + snapshot->sink_latency - buffer_latency) -
(snapshot->source_now - snapshot->source_latency);
pa_log_debug("Diff %lld (%lld - %lld + %lld) %lld %lld %lld %lld", (long long) diff_time,
(long long) snapshot->sink_latency,
(long long) buffer_latency, (long long) snapshot->source_latency,
(long long) source_delay, (long long) sink_delay,
(long long) (send_counter - recv_counter),
(long long) (snapshot->sink_now - snapshot->source_now));
return diff_time;
}
/* Called from main context */
static void time_callback(pa_mainloop_api *a, pa_time_event *e, const struct timeval *t, void *userdata) {
struct userdata *u = userdata;
uint32_t old_rate, base_rate, new_rate;
int64_t diff_time;
/*size_t fs*/
struct snapshot latency_snapshot;
pa_assert(u);
pa_assert(a);
pa_assert(u->time_event == e);
pa_assert_ctl_context();
if (!IS_ACTIVE(u))
return;
/* update our snapshots */
pa_asyncmsgq_send(u->source_output->source->asyncmsgq, PA_MSGOBJECT(u->source_output), SOURCE_OUTPUT_MESSAGE_LATENCY_SNAPSHOT, &latency_snapshot, 0, NULL);
pa_asyncmsgq_send(u->sink_input->sink->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_LATENCY_SNAPSHOT, &latency_snapshot, 0, NULL);
/* calculate drift between capture and playback */
diff_time = calc_diff(u, &latency_snapshot);
/*fs = pa_frame_size(&u->source_output->sample_spec);*/
old_rate = u->sink_input->sample_spec.rate;
base_rate = u->source_output->sample_spec.rate;
if (diff_time < 0) {
/* recording before playback, we need to adjust quickly. The echo
* canceler does not work in this case. */
pa_asyncmsgq_post(u->asyncmsgq, PA_MSGOBJECT(u->source_output), SOURCE_OUTPUT_MESSAGE_APPLY_DIFF_TIME,
NULL, diff_time, NULL, NULL);
/*new_rate = base_rate - ((pa_usec_to_bytes(-diff_time, &u->source_output->sample_spec) / fs) * PA_USEC_PER_SEC) / u->adjust_time;*/
new_rate = base_rate;
}
else {
if (diff_time > u->adjust_threshold) {
/* diff too big, quickly adjust */
pa_asyncmsgq_post(u->asyncmsgq, PA_MSGOBJECT(u->source_output), SOURCE_OUTPUT_MESSAGE_APPLY_DIFF_TIME,
NULL, diff_time, NULL, NULL);
}
/* recording behind playback, we need to slowly adjust the rate to match */
/*new_rate = base_rate + ((pa_usec_to_bytes(diff_time, &u->source_output->sample_spec) / fs) * PA_USEC_PER_SEC) / u->adjust_time;*/
/* assume equal samplerates for now */
new_rate = base_rate;
}
/* make sure we don't make too big adjustments because that sounds horrible */
if (new_rate > base_rate * 1.1 || new_rate < base_rate * 0.9)
new_rate = base_rate;
if (new_rate != old_rate) {
pa_log_info("Old rate %lu Hz, new rate %lu Hz", (unsigned long) old_rate, (unsigned long) new_rate);
pa_sink_input_set_rate(u->sink_input, new_rate);
}
pa_core_rttime_restart(u->core, u->time_event, pa_rtclock_now() + u->adjust_time);
}
/* Called from source I/O thread context */
static int source_process_msg_cb(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
struct userdata *u = PA_SOURCE(o)->userdata;
switch (code) {
case PA_SOURCE_MESSAGE_GET_LATENCY:
/* The source is _put() before the source output is, so let's
* make sure we don't access it in that time. Also, the
* source output is first shut down, the source second. */
if (!PA_SOURCE_IS_LINKED(u->source->thread_info.state) ||
!PA_SOURCE_OUTPUT_IS_LINKED(u->source_output->thread_info.state)) {
*((pa_usec_t*) data) = 0;
return 0;
}
*((pa_usec_t*) data) =
/* Get the latency of the master source */
pa_source_get_latency_within_thread(u->source_output->source) +
/* Add the latency internal to our source output on top */
pa_bytes_to_usec(pa_memblockq_get_length(u->source_output->thread_info.delay_memblockq), &u->source_output->source->sample_spec) +
/* and the buffering we do on the source */
pa_bytes_to_usec(u->source_output_blocksize, &u->source_output->source->sample_spec);
return 0;
case PA_SOURCE_MESSAGE_SET_VOLUME_SYNCED:
u->thread_info.current_volume = u->source->reference_volume;
break;
}
return pa_source_process_msg(o, code, data, offset, chunk);
}
/* Called from sink I/O thread context */
static int sink_process_msg_cb(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
struct userdata *u = PA_SINK(o)->userdata;
switch (code) {
case PA_SINK_MESSAGE_GET_LATENCY:
/* The sink is _put() before the sink input is, so let's
* make sure we don't access it in that time. Also, the
* sink input is first shut down, the sink second. */
if (!PA_SINK_IS_LINKED(u->sink->thread_info.state) ||
!PA_SINK_INPUT_IS_LINKED(u->sink_input->thread_info.state)) {
*((pa_usec_t*) data) = 0;
return 0;
}
*((pa_usec_t*) data) =
/* Get the latency of the master sink */
pa_sink_get_latency_within_thread(u->sink_input->sink) +
/* Add the latency internal to our sink input on top */
pa_bytes_to_usec(pa_memblockq_get_length(u->sink_input->thread_info.render_memblockq), &u->sink_input->sink->sample_spec);
return 0;
}
return pa_sink_process_msg(o, code, data, offset, chunk);
}
/* Called from main context */
static int source_set_state_cb(pa_source *s, pa_source_state_t state) {
struct userdata *u;
pa_source_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SOURCE_IS_LINKED(state) ||
!PA_SOURCE_OUTPUT_IS_LINKED(pa_source_output_get_state(u->source_output)))
return 0;
if (state == PA_SOURCE_RUNNING) {
/* restart timer when both sink and source are active */
if (IS_ACTIVE(u) && u->adjust_time)
pa_core_rttime_restart(u->core, u->time_event, pa_rtclock_now() + u->adjust_time);
pa_atomic_store(&u->request_resync, 1);
pa_source_output_cork(u->source_output, false);
} else if (state == PA_SOURCE_SUSPENDED) {
pa_source_output_cork(u->source_output, true);
}
return 0;
}
/* Called from main context */
static int sink_set_state_cb(pa_sink *s, pa_sink_state_t state) {
struct userdata *u;
pa_sink_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SINK_IS_LINKED(state) ||
!PA_SINK_INPUT_IS_LINKED(pa_sink_input_get_state(u->sink_input)))
return 0;
if (state == PA_SINK_RUNNING) {
/* restart timer when both sink and source are active */
if (IS_ACTIVE(u) && u->adjust_time)
pa_core_rttime_restart(u->core, u->time_event, pa_rtclock_now() + u->adjust_time);
pa_atomic_store(&u->request_resync, 1);
pa_sink_input_cork(u->sink_input, false);
} else if (state == PA_SINK_SUSPENDED) {
pa_sink_input_cork(u->sink_input, true);
}
return 0;
}
/* Called from source I/O thread context */
static void source_update_requested_latency_cb(pa_source *s) {
struct userdata *u;
pa_source_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SOURCE_IS_LINKED(u->source->thread_info.state) ||
!PA_SOURCE_OUTPUT_IS_LINKED(u->source_output->thread_info.state))
return;
pa_log_debug("Source update requested latency");
/* Just hand this one over to the master source */
pa_source_output_set_requested_latency_within_thread(
u->source_output,
pa_source_get_requested_latency_within_thread(s));
}
/* Called from sink I/O thread context */
static void sink_update_requested_latency_cb(pa_sink *s) {
struct userdata *u;
pa_sink_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SINK_IS_LINKED(u->sink->thread_info.state) ||
!PA_SINK_INPUT_IS_LINKED(u->sink_input->thread_info.state))
return;
pa_log_debug("Sink update requested latency");
/* Just hand this one over to the master sink */
pa_sink_input_set_requested_latency_within_thread(
u->sink_input,
pa_sink_get_requested_latency_within_thread(s));
}
/* Called from sink I/O thread context */
static void sink_request_rewind_cb(pa_sink *s) {
struct userdata *u;
pa_sink_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SINK_IS_LINKED(u->sink->thread_info.state) ||
!PA_SINK_INPUT_IS_LINKED(u->sink_input->thread_info.state))
return;
pa_log_debug("Sink request rewind %lld", (long long) s->thread_info.rewind_nbytes);
/* Just hand this one over to the master sink */
pa_sink_input_request_rewind(u->sink_input,
s->thread_info.rewind_nbytes, true, false, false);
}
/* Called from main context */
static void source_set_volume_cb(pa_source *s) {
struct userdata *u;
pa_source_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SOURCE_IS_LINKED(pa_source_get_state(s)) ||
!PA_SOURCE_OUTPUT_IS_LINKED(pa_source_output_get_state(u->source_output)))
return;
pa_source_output_set_volume(u->source_output, &s->real_volume, s->save_volume, true);
}
/* Called from main context */
static void sink_set_volume_cb(pa_sink *s) {
struct userdata *u;
pa_sink_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SINK_IS_LINKED(pa_sink_get_state(s)) ||
!PA_SINK_INPUT_IS_LINKED(pa_sink_input_get_state(u->sink_input)))
return;
pa_sink_input_set_volume(u->sink_input, &s->real_volume, s->save_volume, true);
}
/* Called from main context. */
static void source_get_volume_cb(pa_source *s) {
struct userdata *u;
pa_cvolume v;
pa_source_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SOURCE_IS_LINKED(pa_source_get_state(s)) ||
!PA_SOURCE_OUTPUT_IS_LINKED(pa_source_output_get_state(u->source_output)))
return;
pa_source_output_get_volume(u->source_output, &v, true);
if (pa_cvolume_equal(&s->real_volume, &v))
/* no change */
return;
s->real_volume = v;
pa_source_set_soft_volume(s, NULL);
}
/* Called from main context */
static void source_set_mute_cb(pa_source *s) {
struct userdata *u;
pa_source_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SOURCE_IS_LINKED(pa_source_get_state(s)) ||
!PA_SOURCE_OUTPUT_IS_LINKED(pa_source_output_get_state(u->source_output)))
return;
pa_source_output_set_mute(u->source_output, s->muted, s->save_muted);
}
/* Called from main context */
static void sink_set_mute_cb(pa_sink *s) {
struct userdata *u;
pa_sink_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SINK_IS_LINKED(pa_sink_get_state(s)) ||
!PA_SINK_INPUT_IS_LINKED(pa_sink_input_get_state(u->sink_input)))
return;
pa_sink_input_set_mute(u->sink_input, s->muted, s->save_muted);
}
/* Called from main context */
static void source_get_mute_cb(pa_source *s) {
struct userdata *u;
pa_source_assert_ref(s);
pa_assert_se(u = s->userdata);
if (!PA_SOURCE_IS_LINKED(pa_source_get_state(s)) ||
!PA_SOURCE_OUTPUT_IS_LINKED(pa_source_output_get_state(u->source_output)))
return;
pa_source_output_get_mute(u->source_output);
}
/* Called from source I/O thread context. */
static void apply_diff_time(struct userdata *u, int64_t diff_time) {
int64_t diff;
if (diff_time < 0) {
diff = pa_usec_to_bytes(-diff_time, &u->sink_input->sample_spec);
if (diff > 0) {
/* add some extra safety samples to compensate for jitter in the
* timings */
diff += 10 * pa_frame_size (&u->sink_input->sample_spec);
pa_log("Playback after capture (%lld), drop sink %lld", (long long) diff_time, (long long) diff);
u->sink_skip = diff;
u->source_skip = 0;
}
} else if (diff_time > 0) {
diff = pa_usec_to_bytes(diff_time, &u->source_output->sample_spec);
if (diff > 0) {
pa_log("Playback too far ahead (%lld), drop source %lld", (long long) diff_time, (long long) diff);
u->source_skip = diff;
u->sink_skip = 0;
}
}
}
/* Called from source I/O thread context. */
static void do_resync(struct userdata *u) {
int64_t diff_time;
struct snapshot latency_snapshot;
pa_log("Doing resync");
/* update our snapshot */
source_output_snapshot_within_thread(u, &latency_snapshot);
pa_asyncmsgq_send(u->sink_input->sink->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_LATENCY_SNAPSHOT, &latency_snapshot, 0, NULL);
/* calculate drift between capture and playback */
diff_time = calc_diff(u, &latency_snapshot);
/* and adjust for the drift */
apply_diff_time(u, diff_time);
}
/* 1. Calculate drift at this point, pass to canceller
* 2. Push out playback samples in blocksize chunks
* 3. Push out capture samples in blocksize chunks
* 4. ???
* 5. Profit
*
* Called from source I/O thread context.
*/
static void do_push_drift_comp(struct userdata *u) {
size_t rlen, plen;
pa_memchunk rchunk, pchunk, cchunk;
uint8_t *rdata, *pdata, *cdata;
float drift;
int unused PA_GCC_UNUSED;
rlen = pa_memblockq_get_length(u->source_memblockq);
plen = pa_memblockq_get_length(u->sink_memblockq);
/* Estimate snapshot drift as follows:
* pd: amount of data consumed since last time
* rd: amount of data consumed since last time
*
* drift = (pd - rd) / rd;
*
* We calculate pd and rd as the memblockq length less the number of
* samples left from the last iteration (to avoid double counting
* those remainder samples.
*/
drift = ((float)(plen - u->sink_rem) - (rlen - u->source_rem)) / ((float)(rlen - u->source_rem));
u->sink_rem = plen % u->sink_blocksize;
u->source_rem = rlen % u->source_output_blocksize;
/* Now let the canceller work its drift compensation magic */
u->ec->set_drift(u->ec, drift);
if (u->save_aec) {
if (u->drift_file)
fprintf(u->drift_file, "d %a\n", drift);
}
/* Send in the playback samples first */
while (plen >= u->sink_blocksize) {
pa_memblockq_peek_fixed_size(u->sink_memblockq, u->sink_blocksize, &pchunk);
pdata = pa_memblock_acquire(pchunk.memblock);
pdata += pchunk.index;
u->ec->play(u->ec, pdata);
if (u->save_aec) {
if (u->drift_file)
fprintf(u->drift_file, "p %d\n", u->sink_blocksize);
if (u->played_file)
unused = fwrite(pdata, 1, u->sink_blocksize, u->played_file);
}
pa_memblock_release(pchunk.memblock);
pa_memblockq_drop(u->sink_memblockq, u->sink_blocksize);
pa_memblock_unref(pchunk.memblock);
plen -= u->sink_blocksize;
}
/* And now the capture samples */
while (rlen >= u->source_output_blocksize) {
pa_memblockq_peek_fixed_size(u->source_memblockq, u->source_output_blocksize, &rchunk);
rdata = pa_memblock_acquire(rchunk.memblock);
rdata += rchunk.index;
cchunk.index = 0;
cchunk.length = u->source_output_blocksize;
cchunk.memblock = pa_memblock_new(u->source->core->mempool, cchunk.length);
cdata = pa_memblock_acquire(cchunk.memblock);
u->ec->record(u->ec, rdata, cdata);
if (u->save_aec) {
if (u->drift_file)
fprintf(u->drift_file, "c %d\n", u->source_output_blocksize);
if (u->captured_file)
unused = fwrite(rdata, 1, u->source_output_blocksize, u->captured_file);
if (u->canceled_file)
unused = fwrite(cdata, 1, u->source_output_blocksize, u->canceled_file);
}
pa_memblock_release(cchunk.memblock);
pa_memblock_release(rchunk.memblock);
pa_memblock_unref(rchunk.memblock);
pa_source_post(u->source, &cchunk);
pa_memblock_unref(cchunk.memblock);
pa_memblockq_drop(u->source_memblockq, u->source_output_blocksize);
rlen -= u->source_output_blocksize;
}
}
/* This one's simpler than the drift compensation case -- we just iterate over
* the capture buffer, and pass the canceller blocksize bytes of playback and
* capture data.
*
* Called from source I/O thread context. */
static void do_push(struct userdata *u) {
size_t rlen, plen;
pa_memchunk rchunk, pchunk, cchunk;
uint8_t *rdata, *pdata, *cdata;
int unused PA_GCC_UNUSED;
rlen = pa_memblockq_get_length(u->source_memblockq);
plen = pa_memblockq_get_length(u->sink_memblockq);
while (rlen >= u->source_output_blocksize) {
/* take fixed blocks from recorded and played samples */
pa_memblockq_peek_fixed_size(u->source_memblockq, u->source_output_blocksize, &rchunk);
pa_memblockq_peek_fixed_size(u->sink_memblockq, u->sink_blocksize, &pchunk);
/* we ran out of played data and pchunk has been filled with silence bytes */
if (plen < u->sink_blocksize)
pa_memblockq_seek(u->sink_memblockq, u->sink_blocksize - plen, PA_SEEK_RELATIVE, true);
rdata = pa_memblock_acquire(rchunk.memblock);
rdata += rchunk.index;
pdata = pa_memblock_acquire(pchunk.memblock);
pdata += pchunk.index;
cchunk.index = 0;
cchunk.length = u->source_blocksize;
cchunk.memblock = pa_memblock_new(u->source->core->mempool, cchunk.length);
cdata = pa_memblock_acquire(cchunk.memblock);
if (u->save_aec) {
if (u->captured_file)
unused = fwrite(rdata, 1, u->source_output_blocksize, u->captured_file);
if (u->played_file)
unused = fwrite(pdata, 1, u->sink_blocksize, u->played_file);
}
/* perform echo cancellation */
u->ec->run(u->ec, rdata, pdata, cdata);
if (u->save_aec) {
if (u->canceled_file)
unused = fwrite(cdata, 1, u->source_blocksize, u->canceled_file);
}
pa_memblock_release(cchunk.memblock);
pa_memblock_release(pchunk.memblock);
pa_memblock_release(rchunk.memblock);
/* drop consumed source samples */
pa_memblockq_drop(u->source_memblockq, u->source_output_blocksize);
pa_memblock_unref(rchunk.memblock);
rlen -= u->source_output_blocksize;
/* drop consumed sink samples */
pa_memblockq_drop(u->sink_memblockq, u->sink_blocksize);
pa_memblock_unref(pchunk.memblock);
if (plen >= u->sink_blocksize)
plen -= u->sink_blocksize;
else
plen = 0;
/* forward the (echo-canceled) data to the virtual source */
pa_source_post(u->source, &cchunk);
pa_memblock_unref(cchunk.memblock);
}
}
/* Called from source I/O thread context. */
static void source_output_push_cb(pa_source_output *o, const pa_memchunk *chunk) {
struct userdata *u;
size_t rlen, plen, to_skip;
pa_memchunk rchunk;
pa_source_output_assert_ref(o);
pa_source_output_assert_io_context(o);
pa_assert_se(u = o->userdata);
if (!PA_SOURCE_OUTPUT_IS_LINKED(pa_source_output_get_state(u->source_output))) {
pa_log("Push when no link?");
return;
}
if (PA_UNLIKELY(u->source->thread_info.state != PA_SOURCE_RUNNING ||
u->sink->thread_info.state != PA_SINK_RUNNING)) {
pa_source_post(u->source, chunk);
return;
}
/* handle queued messages, do any message sending of our own */
while (pa_asyncmsgq_process_one(u->asyncmsgq) > 0)
;
pa_memblockq_push_align(u->source_memblockq, chunk);
rlen = pa_memblockq_get_length(u->source_memblockq);
plen = pa_memblockq_get_length(u->sink_memblockq);
/* Let's not do anything else till we have enough data to process */
if (rlen < u->source_output_blocksize)
return;
/* See if we need to drop samples in order to sync */
if (pa_atomic_cmpxchg (&u->request_resync, 1, 0)) {
do_resync(u);
}
/* Okay, skip cancellation for skipped source samples if needed. */
if (PA_UNLIKELY(u->source_skip)) {
/* The slightly tricky bit here is that we drop all but modulo
* blocksize bytes and then adjust for that last bit on the sink side.
* We do this because the source data is coming at a fixed rate, which
* means the only way to try to catch up is drop sink samples and let
* the canceller cope up with this. */
to_skip = rlen >= u->source_skip ? u->source_skip : rlen;
to_skip -= to_skip % u->source_output_blocksize;
if (to_skip) {
pa_memblockq_peek_fixed_size(u->source_memblockq, to_skip, &rchunk);
pa_source_post(u->source, &rchunk);
pa_memblock_unref(rchunk.memblock);
pa_memblockq_drop(u->source_memblockq, to_skip);
rlen -= to_skip;
u->source_skip -= to_skip;
}
if (rlen && u->source_skip % u->source_output_blocksize) {
u->sink_skip += (uint64_t) (u->source_output_blocksize - (u->source_skip % u->source_output_blocksize)) * u->sink_blocksize / u->source_output_blocksize;
u->source_skip -= (u->source_skip % u->source_output_blocksize);
}
}
/* And for the sink, these samples have been played back already, so we can
* just drop them and get on with it. */
if (PA_UNLIKELY(u->sink_skip)) {
to_skip = plen >= u->sink_skip ? u->sink_skip : plen;
pa_memblockq_drop(u->sink_memblockq, to_skip);
plen -= to_skip;
u->sink_skip -= to_skip;
}
/* process and push out samples */
if (u->ec->params.drift_compensation)
do_push_drift_comp(u);
else
do_push(u);
}
/* Called from sink I/O thread context. */
static int sink_input_pop_cb(pa_sink_input *i, size_t nbytes, pa_memchunk *chunk) {
struct userdata *u;
pa_sink_input_assert_ref(i);
pa_assert(chunk);
pa_assert_se(u = i->userdata);
if (u->sink->thread_info.rewind_requested)
pa_sink_process_rewind(u->sink, 0);
pa_sink_render_full(u->sink, nbytes, chunk);
if (i->thread_info.underrun_for > 0) {
pa_log_debug("Handling end of underrun.");
pa_atomic_store(&u->request_resync, 1);
}
/* let source thread handle the chunk. pass the sample count as well so that
* the source IO thread can update the right variables. */
pa_asyncmsgq_post(u->asyncmsgq, PA_MSGOBJECT(u->source_output), SOURCE_OUTPUT_MESSAGE_POST,
NULL, 0, chunk, NULL);
u->send_counter += chunk->length;
return 0;
}
/* Called from source I/O thread context. */
static void source_output_process_rewind_cb(pa_source_output *o, size_t nbytes) {
struct userdata *u;
pa_source_output_assert_ref(o);
pa_source_output_assert_io_context(o);
pa_assert_se(u = o->userdata);
pa_source_process_rewind(u->source, nbytes);