forked from kiwibrowser/src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcras_audio_handler.cc
1678 lines (1447 loc) · 56.5 KB
/
cras_audio_handler.cc
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
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/audio/cras_audio_handler.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <set>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
#include "base/sys_info.h"
#include "base/system_monitor/system_monitor.h"
#include "chromeos/audio/audio_devices_pref_handler_stub.h"
#include "chromeos/dbus/dbus_thread_manager.h"
using std::max;
using std::min;
namespace chromeos {
namespace {
// Default value for unmuting, as a percent in the range [0, 100].
// Used when sound is unmuted, but volume was less than kMuteThresholdPercent.
const int kDefaultUnmuteVolumePercent = 4;
// Default output buffer size in frames.
const int kDefaultOutputBufferSize = 512;
// Volume value which should be considered as muted in range [0, 100].
const int kMuteThresholdPercent = 1;
// The duration of HDMI output re-discover grace period in milliseconds.
const int kHDMIRediscoverGracePeriodDurationInMs = 2000;
// Mixer matrix, [0.5, 0.5; 0.5, 0.5]
const double kStereoToMono[] = {0.5, 0.5, 0.5, 0.5};
// Mixer matrix, [1, 0; 0, 1]
const double kStereoToStereo[] = {1, 0, 0, 1};
CrasAudioHandler* g_cras_audio_handler = nullptr;
bool IsSameAudioDevice(const AudioDevice& a, const AudioDevice& b) {
return a.stable_device_id == b.stable_device_id && a.is_input == b.is_input &&
a.type == b.type && a.device_name == b.device_name;
}
bool IsDeviceInList(const AudioDevice& device, const AudioNodeList& node_list) {
for (const AudioNode& node : node_list) {
if (device.stable_device_id == node.StableDeviceId())
return true;
}
return false;
}
CrasAudioClient* GetCrasAudioClient() {
return DBusThreadManager::Get()->GetCrasAudioClient();
}
bool HasCrasAudioClient() {
return DBusThreadManager::IsInitialized() && DBusThreadManager::Get() &&
DBusThreadManager::Get()->GetCrasAudioClient();
}
} // namespace
CrasAudioHandler::AudioObserver::AudioObserver() = default;
CrasAudioHandler::AudioObserver::~AudioObserver() = default;
void CrasAudioHandler::AudioObserver::OnOutputNodeVolumeChanged(
uint64_t /* node_id */,
int /* volume */) {
}
void CrasAudioHandler::AudioObserver::OnInputNodeGainChanged(
uint64_t /* node_id */,
int /* gain */) {
}
void CrasAudioHandler::AudioObserver::OnOutputMuteChanged(
bool /* mute_on */,
bool /* system_adjust */) {}
void CrasAudioHandler::AudioObserver::OnInputMuteChanged(bool /* mute_on */) {
}
void CrasAudioHandler::AudioObserver::OnAudioNodesChanged() {
}
void CrasAudioHandler::AudioObserver::OnActiveOutputNodeChanged() {
}
void CrasAudioHandler::AudioObserver::OnActiveInputNodeChanged() {
}
void CrasAudioHandler::AudioObserver::OnOutputChannelRemixingChanged(
bool /* mono_on */) {}
void CrasAudioHandler::AudioObserver::OnHotwordTriggered(
uint64_t /* tv_sec */,
uint64_t /* tv_nsec */) {}
void CrasAudioHandler::AudioObserver::OnOutputStarted() {}
void CrasAudioHandler::AudioObserver::OnOutputStopped() {}
// static
void CrasAudioHandler::Initialize(
scoped_refptr<AudioDevicesPrefHandler> audio_pref_handler) {
CHECK(!g_cras_audio_handler);
g_cras_audio_handler = new CrasAudioHandler(audio_pref_handler);
}
// static
void CrasAudioHandler::InitializeForTesting() {
CHECK(!g_cras_audio_handler);
CrasAudioHandler::Initialize(new AudioDevicesPrefHandlerStub());
}
// static
void CrasAudioHandler::Shutdown() {
CHECK(g_cras_audio_handler);
delete g_cras_audio_handler;
g_cras_audio_handler = nullptr;
}
// static
bool CrasAudioHandler::IsInitialized() {
return g_cras_audio_handler != nullptr;
}
// static
CrasAudioHandler* CrasAudioHandler::Get() {
CHECK(g_cras_audio_handler)
<< "CrasAudioHandler::Get() called before Initialize().";
return g_cras_audio_handler;
}
void CrasAudioHandler::OnVideoCaptureStarted(media::VideoFacingMode facing) {
DCHECK(main_task_runner_);
if (!main_task_runner_->BelongsToCurrentThread()) {
main_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&CrasAudioHandler::OnVideoCaptureStartedOnMainThread,
weak_ptr_factory_.GetWeakPtr(), facing));
return;
}
// Unittest may call this from the main thread.
OnVideoCaptureStartedOnMainThread(facing);
}
void CrasAudioHandler::OnVideoCaptureStopped(media::VideoFacingMode facing) {
DCHECK(main_task_runner_);
if (!main_task_runner_->BelongsToCurrentThread()) {
main_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&CrasAudioHandler::OnVideoCaptureStoppedOnMainThread,
weak_ptr_factory_.GetWeakPtr(), facing));
return;
}
// Unittest may call this from the main thread.
OnVideoCaptureStoppedOnMainThread(facing);
}
void CrasAudioHandler::OnVideoCaptureStartedOnMainThread(
media::VideoFacingMode facing) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
// Do nothing if the device doesn't have both front and rear microphones.
if (!HasDualInternalMic())
return;
bool camera_is_already_on = IsCameraOn();
switch (facing) {
case media::MEDIA_VIDEO_FACING_USER:
front_camera_on_ = true;
break;
case media::MEDIA_VIDEO_FACING_ENVIRONMENT:
rear_camera_on_ = true;
break;
default:
LOG_IF(WARNING, facing == media::NUM_MEDIA_VIDEO_FACING_MODES)
<< "On the device with dual microphone, got video capture "
<< "notification with invalid camera facing mode value";
return;
}
// If the camera is already on before this notification, don't change active
// input. In the case that both cameras are turned on at the same time, we
// won't change the active input after the first camera is turned on. We only
// support the use case of one camera on at a time. The third party
// developer can turn on/off both microphones with extension api if they like
// to.
if (camera_is_already_on)
return;
// If the current active input is an external device, keep it.
const AudioDevice* active_input = GetDeviceFromId(active_input_node_id_);
if (active_input && active_input->IsExternalDevice())
return;
// Activate the correct mic for the current active camera.
ActivateMicForCamera(facing);
}
void CrasAudioHandler::OnVideoCaptureStoppedOnMainThread(
media::VideoFacingMode facing) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
// Do nothing if the device doesn't have both front and rear microphones.
if (!HasDualInternalMic())
return;
switch (facing) {
case media::MEDIA_VIDEO_FACING_USER:
front_camera_on_ = false;
break;
case media::MEDIA_VIDEO_FACING_ENVIRONMENT:
rear_camera_on_ = false;
break;
default:
LOG_IF(WARNING, facing == media::NUM_MEDIA_VIDEO_FACING_MODES)
<< "On the device with dual microphone, got video capture "
<< "notification with invalid camera facing mode value";
return;
}
// If not all cameras are turned off, don't change active input. In the case
// that both cameras are turned on at the same time before one of them is
// stopped, we won't change active input until all of them are stopped.
// We only support the use case of one camera on at a time. The third party
// developer can turn on/off both microphones with extension api if they like
// to.
if (IsCameraOn())
return;
// If the current active input is an external device, keep it.
const AudioDevice* active_input = GetDeviceFromId(active_input_node_id_);
if (active_input && active_input->IsExternalDevice())
return;
// Switch to front mic properly.
DeviceActivateType activated_by =
HasExternalDevice(true) ? ACTIVATE_BY_USER : ACTIVATE_BY_PRIORITY;
SwitchToDevice(*GetDeviceByType(AUDIO_TYPE_FRONT_MIC), true, activated_by);
}
void CrasAudioHandler::AddAudioObserver(AudioObserver* observer) {
observers_.AddObserver(observer);
}
void CrasAudioHandler::RemoveAudioObserver(AudioObserver* observer) {
observers_.RemoveObserver(observer);
}
bool CrasAudioHandler::HasKeyboardMic() {
return GetKeyboardMic() != nullptr;
}
bool CrasAudioHandler::IsOutputMuted() {
return output_mute_on_;
}
bool CrasAudioHandler::IsOutputMutedForDevice(uint64_t device_id) {
const AudioDevice* device = GetDeviceFromId(device_id);
if (!device)
return false;
DCHECK(!device->is_input);
return audio_pref_handler_->GetMuteValue(*device);
}
bool CrasAudioHandler::IsOutputVolumeBelowDefaultMuteLevel() {
return output_volume_ <= kMuteThresholdPercent;
}
bool CrasAudioHandler::IsInputMuted() {
return input_mute_on_;
}
bool CrasAudioHandler::IsInputMutedForDevice(uint64_t device_id) {
const AudioDevice* device = GetDeviceFromId(device_id);
if (!device)
return false;
DCHECK(device->is_input);
// We don't record input mute state for each device in the prefs,
// for any non-active input device, we assume mute is off.
if (device->id == active_input_node_id_)
return input_mute_on_;
return false;
}
int CrasAudioHandler::GetOutputDefaultVolumeMuteThreshold() {
return kMuteThresholdPercent;
}
int CrasAudioHandler::GetOutputVolumePercent() {
return output_volume_;
}
int CrasAudioHandler::GetOutputVolumePercentForDevice(uint64_t device_id) {
if (device_id == active_output_node_id_)
return output_volume_;
const AudioDevice* device = GetDeviceFromId(device_id);
return static_cast<int>(audio_pref_handler_->GetOutputVolumeValue(device));
}
int CrasAudioHandler::GetInputGainPercent() {
return input_gain_;
}
int CrasAudioHandler::GetInputGainPercentForDevice(uint64_t device_id) {
if (device_id == active_input_node_id_)
return input_gain_;
const AudioDevice* device = GetDeviceFromId(device_id);
return static_cast<int>(audio_pref_handler_->GetInputGainValue(device));
}
uint64_t CrasAudioHandler::GetPrimaryActiveOutputNode() const {
return active_output_node_id_;
}
uint64_t CrasAudioHandler::GetPrimaryActiveInputNode() const {
return active_input_node_id_;
}
void CrasAudioHandler::GetAudioDevices(AudioDeviceList* device_list) const {
device_list->clear();
for (const auto& item : audio_devices_) {
const AudioDevice& device = item.second;
device_list->push_back(device);
}
}
bool CrasAudioHandler::GetPrimaryActiveOutputDevice(AudioDevice* device) const {
const AudioDevice* active_device = GetDeviceFromId(active_output_node_id_);
if (!active_device || !device)
return false;
*device = *active_device;
return true;
}
const AudioDevice* CrasAudioHandler::GetDeviceByType(AudioDeviceType type) {
for (const auto& item : audio_devices_) {
const AudioDevice& device = item.second;
if (device.type == type)
return &device;
}
return nullptr;
}
void CrasAudioHandler::GetDefaultOutputBufferSize(int32_t* buffer_size) const {
*buffer_size = default_output_buffer_size_;
}
void CrasAudioHandler::SetKeyboardMicActive(bool active) {
const AudioDevice* keyboard_mic = GetKeyboardMic();
if (!keyboard_mic)
return;
// Keyboard mic is invisible to chromeos users. It is always added or removed
// as additional active node.
DCHECK(active_input_node_id_ && active_input_node_id_ != keyboard_mic->id);
if (active)
AddActiveNode(keyboard_mic->id, true);
else
RemoveActiveNodeInternal(keyboard_mic->id, true);
}
void CrasAudioHandler::AddActiveNode(uint64_t node_id, bool notify) {
const AudioDevice* device = GetDeviceFromId(node_id);
if (!device) {
VLOG(1) << "AddActiveInputNode: Cannot find device id="
<< "0x" << std::hex << node_id;
return;
}
// If there is no primary active device, set |node_id| to primary active node.
if ((device->is_input && !active_input_node_id_) ||
(!device->is_input && !active_output_node_id_)) {
SwitchToDevice(*device, notify, ACTIVATE_BY_USER);
return;
}
AddAdditionalActiveNode(node_id, notify);
}
void CrasAudioHandler::ChangeActiveNodes(const NodeIdList& new_active_ids) {
AudioDeviceList input_devices;
AudioDeviceList output_devices;
for (uint64_t id : new_active_ids) {
const AudioDevice* device = GetDeviceFromId(id);
if (!device)
continue;
if (device->is_input)
input_devices.push_back(*device);
else
output_devices.push_back(*device);
}
if (!input_devices.empty())
SetActiveDevices(input_devices, true /* is_input */);
if (!output_devices.empty())
SetActiveDevices(output_devices, false /* is_input */);
}
bool CrasAudioHandler::SetActiveInputNodes(const NodeIdList& node_ids) {
return SetActiveNodes(node_ids, true /* is_input */);
}
bool CrasAudioHandler::SetActiveOutputNodes(const NodeIdList& node_ids) {
return SetActiveNodes(node_ids, false /* is_input */);
}
bool CrasAudioHandler::SetActiveNodes(const NodeIdList& node_ids,
bool is_input) {
AudioDeviceList devices;
for (uint64_t id : node_ids) {
const AudioDevice* device = GetDeviceFromId(id);
if (!device || device->is_input != is_input)
return false;
devices.push_back(*device);
}
SetActiveDevices(devices, is_input);
return true;
}
void CrasAudioHandler::SetActiveDevices(const AudioDeviceList& devices,
bool is_input) {
std::set<uint64_t> new_active_ids;
for (const auto& active_device : devices) {
CHECK_EQ(is_input, active_device.is_input);
new_active_ids.insert(active_device.id);
}
bool active_devices_changed = false;
// If primary active node has to be switched, do that before adding or
// removing any other active devices. Switching to a device can change
// activity state of other devices - final device activity may end up being
// unintended if it is set before active device switches.
uint64_t primary_active =
is_input ? active_input_node_id_ : active_output_node_id_;
if (!new_active_ids.count(primary_active) && !devices.empty()) {
active_devices_changed = true;
SwitchToDevice(devices[0], false /* notify */, ACTIVATE_BY_USER);
}
AudioDeviceList existing_devices;
GetAudioDevices(&existing_devices);
for (const auto& existing_device : existing_devices) {
if (existing_device.is_input != is_input)
continue;
bool should_be_active = new_active_ids.count(existing_device.id);
if (existing_device.active == should_be_active)
continue;
active_devices_changed = true;
if (should_be_active)
AddActiveNode(existing_device.id, false /* notify */);
else
RemoveActiveNodeInternal(existing_device.id, false /* notify */);
}
if (active_devices_changed)
NotifyActiveNodeChanged(is_input);
}
void CrasAudioHandler::SwapInternalSpeakerLeftRightChannel(bool swap) {
for (const auto& item : audio_devices_) {
const AudioDevice& device = item.second;
if (!device.is_input && device.type == AUDIO_TYPE_INTERNAL_SPEAKER) {
GetCrasAudioClient()->SwapLeftRight(device.id, swap);
break;
}
}
}
void CrasAudioHandler::SetOutputMonoEnabled(bool enabled) {
if (output_mono_enabled_ == enabled)
return;
output_mono_enabled_ = enabled;
if (enabled) {
GetCrasAudioClient()->SetGlobalOutputChannelRemix(
output_channels_,
std::vector<double>(kStereoToMono, std::end(kStereoToMono)));
} else {
GetCrasAudioClient()->SetGlobalOutputChannelRemix(
output_channels_,
std::vector<double>(kStereoToStereo, std::end(kStereoToStereo)));
}
for (auto& observer : observers_)
observer.OnOutputChannelRemixingChanged(enabled);
}
bool CrasAudioHandler::has_alternative_input() const {
return has_alternative_input_;
}
bool CrasAudioHandler::has_alternative_output() const {
return has_alternative_output_;
}
void CrasAudioHandler::SetOutputVolumePercent(int volume_percent) {
// Set all active devices to the same volume.
for (const auto& item : audio_devices_) {
const AudioDevice& device = item.second;
if (!device.is_input && device.active)
SetOutputNodeVolumePercent(device.id, volume_percent);
}
}
// TODO: Rename the 'Percent' to something more meaningful.
void CrasAudioHandler::SetInputGainPercent(int gain_percent) {
// TODO(jennyz): Should we set all input devices' gain to the same level?
for (const auto& item : audio_devices_) {
const AudioDevice& device = item.second;
if (device.is_input && device.active)
SetInputNodeGainPercent(active_input_node_id_, gain_percent);
}
}
void CrasAudioHandler::AdjustOutputVolumeByPercent(int adjust_by_percent) {
SetOutputVolumePercent(output_volume_ + adjust_by_percent);
}
void CrasAudioHandler::SetOutputMute(bool mute_on) {
if (!SetOutputMuteInternal(mute_on))
return;
// Save the mute state for all active output audio devices.
for (const auto& item : audio_devices_) {
const AudioDevice& device = item.second;
if (!device.is_input && device.active) {
audio_pref_handler_->SetMuteValue(device, output_mute_on_);
}
}
for (auto& observer : observers_)
observer.OnOutputMuteChanged(output_mute_on_, false /* system_adjust */);
}
void CrasAudioHandler::AdjustOutputVolumeToAudibleLevel() {
if (output_volume_ <= kMuteThresholdPercent) {
// Avoid the situation when sound has been unmuted, but the volume
// is set to a very low value, so user still can't hear any sound.
SetOutputVolumePercent(kDefaultUnmuteVolumePercent);
}
}
void CrasAudioHandler::SetInputMute(bool mute_on) {
SetInputMuteInternal(mute_on);
for (auto& observer : observers_)
observer.OnInputMuteChanged(input_mute_on_);
}
void CrasAudioHandler::SetActiveDevice(const AudioDevice& active_device,
bool notify,
DeviceActivateType activate_by) {
if (active_device.is_input)
GetCrasAudioClient()->SetActiveInputNode(active_device.id);
else
GetCrasAudioClient()->SetActiveOutputNode(active_device.id);
if (notify)
NotifyActiveNodeChanged(active_device.is_input);
// Save active state for the nodes.
for (const auto& item : audio_devices_) {
const AudioDevice& device = item.second;
if (device.is_input != active_device.is_input)
continue;
SaveDeviceState(device, device.active, activate_by);
}
}
void CrasAudioHandler::SaveDeviceState(const AudioDevice& device,
bool active,
DeviceActivateType activate_by) {
// Don't save the active state for non-simple usage device, which is invisible
// to end users.
if (!device.is_for_simple_usage())
return;
if (!active) {
audio_pref_handler_->SetDeviceActive(device, false, false);
} else {
switch (activate_by) {
case ACTIVATE_BY_USER:
audio_pref_handler_->SetDeviceActive(device, true, true);
break;
case ACTIVATE_BY_PRIORITY:
audio_pref_handler_->SetDeviceActive(device, true, false);
break;
default:
// The device is made active due to its previous active state in prefs,
// don't change its active state settings in prefs.
break;
}
}
}
void CrasAudioHandler::SetVolumeGainPercentForDevice(uint64_t device_id,
int value) {
const AudioDevice* device = GetDeviceFromId(device_id);
if (!device)
return;
if (device->is_input)
SetInputNodeGainPercent(device_id, value);
else
SetOutputNodeVolumePercent(device_id, value);
}
void CrasAudioHandler::SetMuteForDevice(uint64_t device_id, bool mute_on) {
if (device_id == active_output_node_id_) {
SetOutputMute(mute_on);
return;
}
if (device_id == active_input_node_id_) {
VLOG(1) << "SetMuteForDevice sets active input device id="
<< "0x" << std::hex << device_id << " mute=" << mute_on;
SetInputMute(mute_on);
return;
}
const AudioDevice* device = GetDeviceFromId(device_id);
// Input device's mute state is not recorded in the pref. crbug.com/365050.
if (device && !device->is_input)
audio_pref_handler_->SetMuteValue(*device, mute_on);
}
// If the HDMI device is the active output device, when the device enters/exits
// docking mode, or HDMI display changes resolution, or chromeos device
// suspends/resumes, cras will lose the HDMI output node for a short period of
// time, then rediscover it. This hotplug behavior will cause the audio output
// be leaked to the alternatvie active audio output during HDMI re-discovering
// period. See crbug.com/503667.
void CrasAudioHandler::SetActiveHDMIOutoutRediscoveringIfNecessary(
bool force_rediscovering) {
if (!GetDeviceFromId(active_output_node_id_))
return;
// Marks the start of the HDMI re-discovering grace period, during which we
// will mute the audio output to prevent it to be be leaked to the
// alternative output device.
if ((hdmi_rediscovering_ && force_rediscovering) ||
(!hdmi_rediscovering_ && IsHDMIPrimaryOutputDevice())) {
StartHDMIRediscoverGracePeriod();
}
}
CrasAudioHandler::CrasAudioHandler(
scoped_refptr<AudioDevicesPrefHandler> audio_pref_handler)
: audio_pref_handler_(audio_pref_handler),
output_mute_on_(false),
input_mute_on_(false),
output_volume_(0),
input_gain_(0),
active_output_node_id_(0),
active_input_node_id_(0),
has_alternative_input_(false),
has_alternative_output_(false),
output_mute_locked_(false),
output_channels_(2),
output_mono_enabled_(false),
hdmi_rediscover_grace_period_duration_in_ms_(
kHDMIRediscoverGracePeriodDurationInMs),
hdmi_rediscovering_(false),
default_output_buffer_size_(kDefaultOutputBufferSize),
weak_ptr_factory_(this) {
if (!audio_pref_handler.get())
return;
// If the DBusThreadManager or the CrasAudioClient aren't available, there
// isn't much we can do. This should only happen when running tests.
if (!HasCrasAudioClient())
return;
GetCrasAudioClient()->AddObserver(this);
audio_pref_handler_->AddAudioPrefObserver(this);
InitializeAudioState();
// Unittest may not have the task runner for the current thread.
if (base::ThreadTaskRunnerHandle::IsSet())
main_task_runner_ = base::ThreadTaskRunnerHandle::Get();
}
CrasAudioHandler::~CrasAudioHandler() {
hdmi_rediscover_timer_.Stop();
if (!HasCrasAudioClient())
return;
GetCrasAudioClient()->RemoveObserver(this);
if (audio_pref_handler_.get())
audio_pref_handler_->RemoveAudioPrefObserver(this);
audio_pref_handler_ = nullptr;
}
void CrasAudioHandler::AudioClientRestarted() {
InitializeAudioState();
}
void CrasAudioHandler::NodesChanged() {
if (cras_service_available_)
GetNodes();
}
void CrasAudioHandler::OutputNodeVolumeChanged(uint64_t node_id, int volume) {
const AudioDevice* device = this->GetDeviceFromId(node_id);
// If this is not an active output node, ignore this event. Because when this
// node set to active, it will be applied with the volume value stored in
// preference.
if (!device || !device->active || device->is_input) {
LOG(ERROR) << "Unexpexted OutputNodeVolumeChanged received on node: 0x"
<< std::hex << node_id;
return;
}
// Sync internal volume state and notify UI for the change. We trust cras
// signal to report the volume state of the device, no matter which source
// set the volume, i.e., volume could be set from non-chrome source, like
// Bluetooth headset, etc. Assume all active output devices share a single
// volume.
output_volume_ = volume;
audio_pref_handler_->SetVolumeGainValue(*device, volume);
if (initializing_audio_state_) {
// Do not notify the observers for volume changed event if CrasAudioHandler
// is initializing its state, i.e., the volume change event is in responding
// to SetOutputNodeVolume request from intializaing audio state, not
// from user action, no need to notify UI to pop uo the volume slider bar.
if (init_node_id_ == node_id && init_volume_ == volume) {
--init_volume_count_;
if (!init_volume_count_)
initializing_audio_state_ = false;
return;
} else {
// Reset the initializing_audio_state_ in case SetOutputNodeVolume request
// is lost by cras due to cras is not ready when CrasAudioHandler is being
// initialized.
initializing_audio_state_ = false;
init_volume_count_ = 0;
}
}
for (auto& observer : observers_)
observer.OnOutputNodeVolumeChanged(node_id, volume);
}
void CrasAudioHandler::ActiveOutputNodeChanged(uint64_t node_id) {
if (active_output_node_id_ == node_id)
return;
// Active audio output device should always be changed by chrome.
// During system boot, cras may change active input to unknown device 0x1,
// we don't need to log it, since it is not an valid device.
if (GetDeviceFromId(node_id)) {
LOG(WARNING) << "Active output node changed unexpectedly by system node_id="
<< "0x" << std::hex << node_id;
}
}
void CrasAudioHandler::ActiveInputNodeChanged(uint64_t node_id) {
if (active_input_node_id_ == node_id)
return;
// Active audio input device should always be changed by chrome.
// During system boot, cras may change active input to unknown device 0x2,
// we don't need to log it, since it is not an valid device.
if (GetDeviceFromId(node_id)) {
LOG(WARNING) << "Active input node changed unexpectedly by system node_id="
<< "0x" << std::hex << node_id;
}
}
void CrasAudioHandler::HotwordTriggered(uint64_t tv_sec, uint64_t tv_nsec) {
for (auto& observer : observers_)
observer.OnHotwordTriggered(tv_sec, tv_nsec);
}
void CrasAudioHandler::NumberOfActiveStreamsChanged() {
GetNumberOfOutputStreams();
}
void CrasAudioHandler::OnAudioPolicyPrefChanged() {
ApplyAudioPolicy();
}
const AudioDevice* CrasAudioHandler::GetDeviceFromId(uint64_t device_id) const {
AudioDeviceMap::const_iterator it = audio_devices_.find(device_id);
if (it == audio_devices_.end())
return nullptr;
return &it->second;
}
const AudioDevice* CrasAudioHandler::GetDeviceFromStableDeviceId(
uint64_t stable_device_id) const {
for (const auto& item : audio_devices_) {
const AudioDevice& device = item.second;
if (device.stable_device_id == stable_device_id)
return &device;
}
return nullptr;
}
const AudioDevice* CrasAudioHandler::GetKeyboardMic() const {
for (const auto& item : audio_devices_) {
const AudioDevice& device = item.second;
if (device.is_input && device.type == AUDIO_TYPE_KEYBOARD_MIC)
return &device;
}
return nullptr;
}
void CrasAudioHandler::SetupAudioInputState() {
// Set the initial audio state to the ones read from audio prefs.
const AudioDevice* device = GetDeviceFromId(active_input_node_id_);
if (!device) {
LOG(ERROR) << "Can't set up audio state for unknown input device id ="
<< "0x" << std::hex << active_input_node_id_;
return;
}
input_gain_ = audio_pref_handler_->GetInputGainValue(device);
VLOG(1) << "SetupAudioInputState for active device id="
<< "0x" << std::hex << device->id << " mute=" << input_mute_on_;
SetInputMuteInternal(input_mute_on_);
// TODO(rkc,jennyz): Set input gain once we decide on how to store
// the gain values since the range and step are both device specific.
}
void CrasAudioHandler::SetupAudioOutputState() {
const AudioDevice* device = GetDeviceFromId(active_output_node_id_);
if (!device) {
LOG(ERROR) << "Can't set up audio state for unknown output device id ="
<< "0x" << std::hex << active_output_node_id_;
return;
}
DCHECK(!device->is_input);
// Mute the output during HDMI re-discovering grace period.
if (hdmi_rediscovering_ && !IsHDMIPrimaryOutputDevice()) {
VLOG(1) << "Mute the output during HDMI re-discovering grace period";
output_mute_on_ = true;
} else {
output_mute_on_ = audio_pref_handler_->GetMuteValue(*device);
}
output_volume_ = audio_pref_handler_->GetOutputVolumeValue(device);
SetOutputMuteInternal(output_mute_on_);
if (initializing_audio_state_) {
// During power up, InitializeAudioState() could be called twice, first
// by CrasAudioHandler constructor, then by cras server restarting signal,
// both sending SetOutputNodeVolume requests, and could lead to two
// OutputNodeVolumeChanged signals.
++init_volume_count_;
init_node_id_ = active_output_node_id_;
init_volume_ = output_volume_;
}
SetOutputNodeVolume(active_output_node_id_, output_volume_);
}
// This sets up the state of an additional active node.
void CrasAudioHandler::SetupAdditionalActiveAudioNodeState(uint64_t node_id) {
const AudioDevice* device = GetDeviceFromId(node_id);
if (!device) {
VLOG(1) << "Can't set up audio state for unknown device id ="
<< "0x" << std::hex << node_id;
return;
}
DCHECK(node_id != active_output_node_id_ && node_id != active_input_node_id_);
// Note: The mute state is a system wide state, we don't set mute per device,
// but just keep the mute state consistent for the active node in prefs.
// The output volume should be set to the same value for all active output
// devices. For input devices, we don't restore their gain value so far.
// TODO(jennyz): crbug.com/417418, track the status for the decison if
// we should persist input gain value in prefs.
if (!device->is_input) {
audio_pref_handler_->SetMuteValue(*device, IsOutputMuted());
SetOutputNodeVolumePercent(node_id, GetOutputVolumePercent());
}
}
void CrasAudioHandler::InitializeAudioState() {
initializing_audio_state_ = true;
ApplyAudioPolicy();
// Defer querying cras for GetNodes until cras service becomes available.
cras_service_available_ = false;
GetCrasAudioClient()->WaitForServiceToBeAvailable(base::BindOnce(
&CrasAudioHandler::InitializeAudioAfterCrasServiceAvailable,
weak_ptr_factory_.GetWeakPtr()));
}
void CrasAudioHandler::InitializeAudioAfterCrasServiceAvailable(
bool service_is_available) {
if (!service_is_available) {
LOG(ERROR) << "Cras service is not available";
cras_service_available_ = false;
return;
}
cras_service_available_ = true;
GetDefaultOutputBufferSizeInternal();
GetNodes();
GetNumberOfOutputStreams();
}
void CrasAudioHandler::ApplyAudioPolicy() {
output_mute_locked_ = false;
if (!audio_pref_handler_->GetAudioOutputAllowedValue()) {
// Mute the device, but do not update the preference.
SetOutputMuteInternal(true);
output_mute_locked_ = true;
} else {
// Restore the mute state.
const AudioDevice* device = GetDeviceFromId(active_output_node_id_);
if (device)
SetOutputMuteInternal(audio_pref_handler_->GetMuteValue(*device));
}
// Policy for audio input is handled by kAudioCaptureAllowed in the Chrome
// media system.
}
void CrasAudioHandler::SetOutputNodeVolume(uint64_t node_id, int volume) {
GetCrasAudioClient()->SetOutputNodeVolume(node_id, volume);
}
void CrasAudioHandler::SetOutputNodeVolumePercent(uint64_t node_id,
int volume_percent) {
const AudioDevice* device = GetDeviceFromId(node_id);
if (!device || device->is_input)
return;
volume_percent = min(max(volume_percent, 0), 100);
if (volume_percent <= kMuteThresholdPercent)
volume_percent = 0;
// Save the volume setting in pref in case this is called on non-active
// node for configuration.
audio_pref_handler_->SetVolumeGainValue(*device, volume_percent);
if (device->active)
SetOutputNodeVolume(node_id, volume_percent);
}
bool CrasAudioHandler::SetOutputMuteInternal(bool mute_on) {
if (output_mute_locked_)
return false;
output_mute_on_ = mute_on;
GetCrasAudioClient()->SetOutputUserMute(mute_on);
return true;
}
void CrasAudioHandler::SetInputNodeGain(uint64_t node_id, int gain) {
GetCrasAudioClient()->SetInputNodeGain(node_id, gain);
}
void CrasAudioHandler::SetInputNodeGainPercent(uint64_t node_id,
int gain_percent) {
const AudioDevice* device = GetDeviceFromId(node_id);
if (!device || !device->is_input)
return;
// NOTE: We do not sanitize input gain values since the range is completely
// dependent on the device.
if (active_input_node_id_ == node_id)
input_gain_ = gain_percent;
audio_pref_handler_->SetVolumeGainValue(*device, gain_percent);
if (device->active) {
SetInputNodeGain(node_id, gain_percent);
for (auto& observer : observers_)
observer.OnInputNodeGainChanged(node_id, gain_percent);
}
}
void CrasAudioHandler::SetInputMuteInternal(bool mute_on) {
input_mute_on_ = mute_on;
GetCrasAudioClient()->SetInputMute(mute_on);
}
void CrasAudioHandler::GetNodes() {
GetCrasAudioClient()->GetNodes(base::BindOnce(
&CrasAudioHandler::HandleGetNodes, weak_ptr_factory_.GetWeakPtr()));
}
void CrasAudioHandler::GetNumberOfOutputStreams() {
GetCrasAudioClient()->GetNumberOfActiveOutputStreams(