shell_audio_controller_chromeos.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "extensions/shell/browser/shell_audio_controller_chromeos.h"
  5. #include <algorithm>
  6. #include "chromeos/ash/components/audio/audio_device.h"
  7. namespace extensions {
  8. namespace {
  9. using ::ash::AudioDevice;
  10. using ::ash::AudioDeviceList;
  11. using ::ash::CrasAudioHandler;
  12. // Returns a pointer to the device in |devices| with ID |node_id|, or NULL if it
  13. // isn't present.
  14. const AudioDevice* GetDevice(const AudioDeviceList& devices, uint64_t node_id) {
  15. for (AudioDeviceList::const_iterator it = devices.begin();
  16. it != devices.end(); ++it) {
  17. if (it->id == node_id)
  18. return &(*it);
  19. }
  20. return NULL;
  21. }
  22. } // namespace
  23. ShellAudioController::ShellAudioController() {
  24. CrasAudioHandler::Get()->AddAudioObserver(this);
  25. ActivateDevices();
  26. }
  27. ShellAudioController::~ShellAudioController() {
  28. CrasAudioHandler::Get()->RemoveAudioObserver(this);
  29. }
  30. void ShellAudioController::OnAudioNodesChanged() {
  31. VLOG(1) << "Audio nodes changed";
  32. ActivateDevices();
  33. }
  34. void ShellAudioController::ActivateDevices() {
  35. auto* handler = CrasAudioHandler::Get();
  36. AudioDeviceList devices;
  37. handler->GetAudioDevices(&devices);
  38. sort(devices.begin(), devices.end(), ash::AudioDeviceCompare());
  39. uint64_t best_input = 0, best_output = 0;
  40. for (AudioDeviceList::const_reverse_iterator it = devices.rbegin();
  41. it != devices.rend() && (!best_input || !best_output); ++it) {
  42. // TODO(derat): Need to check |plugged_time|?
  43. if (it->is_input && !best_input)
  44. best_input = it->id;
  45. else if (!it->is_input && !best_output)
  46. best_output = it->id;
  47. }
  48. if (best_input && best_input != handler->GetPrimaryActiveInputNode()) {
  49. const AudioDevice* device = GetDevice(devices, best_input);
  50. DCHECK(device);
  51. VLOG(1) << "Activating input device: " << device->ToString();
  52. handler->SwitchToDevice(*device, true, CrasAudioHandler::ACTIVATE_BY_USER);
  53. }
  54. if (best_output && best_output != handler->GetPrimaryActiveOutputNode()) {
  55. const AudioDevice* device = GetDevice(devices, best_output);
  56. DCHECK(device);
  57. VLOG(1) << "Activating output device: " << device->ToString();
  58. handler->SwitchToDevice(*device, true, CrasAudioHandler::ACTIVATE_BY_USER);
  59. }
  60. }
  61. } // namespace extensions