1 // Copyright (c) 2012 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 5 #include "remoting/host/audio_capturer_linux.h" 6 7 #include "base/files/file_path.h" 8 #include "base/lazy_instance.h" 9 #include "base/logging.h" 10 #include "remoting/proto/audio.pb.h" 11 12 namespace remoting { 13 14 namespace { 15 16 // PulseAudio's module-pipe-sink must be configured to use the following 17 // parameters for the sink we read from. 18 const AudioPacket_SamplingRate kSamplingRate = AudioPacket::SAMPLING_RATE_48000; 19 20 base::LazyInstance<scoped_refptr<AudioPipeReader> >::Leaky 21 g_pulseaudio_pipe_sink_reader = LAZY_INSTANCE_INITIALIZER; 22 23 } // namespace 24 25 // TODO(wez): Remove this and have the DesktopEnvironmentFactory own the 26 // AudioPipeReader rather than having it process-global. 27 // See crbug.com/161373 and crbug.com/104544. 28 void AudioCapturerLinux::InitializePipeReader( 29 scoped_refptr<base::SingleThreadTaskRunner> task_runner, 30 const base::FilePath& pipe_name) { 31 scoped_refptr<AudioPipeReader> pipe_reader; 32 if (!pipe_name.empty()) 33 pipe_reader = AudioPipeReader::Create(task_runner, pipe_name); 34 g_pulseaudio_pipe_sink_reader.Get() = pipe_reader; 35 } 36 37 AudioCapturerLinux::AudioCapturerLinux( 38 scoped_refptr<AudioPipeReader> pipe_reader) 39 : pipe_reader_(pipe_reader), 40 silence_detector_(0) { 41 } 42 43 AudioCapturerLinux::~AudioCapturerLinux() { 44 } 45 46 bool AudioCapturerLinux::Start(const PacketCapturedCallback& callback) { 47 callback_ = callback; 48 silence_detector_.Reset(kSamplingRate, AudioPacket::CHANNELS_STEREO); 49 pipe_reader_->AddObserver(this); 50 return true; 51 } 52 53 void AudioCapturerLinux::Stop() { 54 pipe_reader_->RemoveObserver(this); 55 callback_.Reset(); 56 } 57 58 bool AudioCapturerLinux::IsStarted() { 59 return !callback_.is_null(); 60 } 61 62 void AudioCapturerLinux::OnDataRead( 63 scoped_refptr<base::RefCountedString> data) { 64 DCHECK(!callback_.is_null()); 65 66 if (silence_detector_.IsSilence( 67 reinterpret_cast<const int16*>(data->data().data()), 68 data->data().size() / sizeof(int16))) { 69 return; 70 } 71 72 scoped_ptr<AudioPacket> packet(new AudioPacket()); 73 packet->add_data(data->data()); 74 packet->set_encoding(AudioPacket::ENCODING_RAW); 75 packet->set_sampling_rate(kSamplingRate); 76 packet->set_bytes_per_sample(AudioPacket::BYTES_PER_SAMPLE_2); 77 packet->set_channels(AudioPacket::CHANNELS_STEREO); 78 callback_.Run(packet.Pass()); 79 } 80 81 bool AudioCapturer::IsSupported() { 82 return g_pulseaudio_pipe_sink_reader.Get().get() != NULL; 83 } 84 85 scoped_ptr<AudioCapturer> AudioCapturer::Create() { 86 scoped_refptr<AudioPipeReader> reader = 87 g_pulseaudio_pipe_sink_reader.Get(); 88 if (!reader.get()) 89 return scoped_ptr<AudioCapturer>(); 90 return scoped_ptr<AudioCapturer>(new AudioCapturerLinux(reader)); 91 } 92 93 } // namespace remoting 94