pulse_input.cc revision 90dce4d38c5ff5333bea97d859d4e484e27edf0c
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 "media/audio/pulse/pulse_input.h"
6
7#include <pulse/pulseaudio.h>
8
9#include "base/logging.h"
10#include "media/audio/pulse/audio_manager_pulse.h"
11#include "media/audio/pulse/pulse_util.h"
12#include "media/base/seekable_buffer.h"
13
14namespace media {
15
16using pulse::AutoPulseLock;
17using pulse::WaitForOperationCompletion;
18
19PulseAudioInputStream::PulseAudioInputStream(AudioManagerPulse* audio_manager,
20                                             const std::string& device_name,
21                                             const AudioParameters& params,
22                                             pa_threaded_mainloop* mainloop,
23                                             pa_context* context)
24    : audio_manager_(audio_manager),
25      callback_(NULL),
26      device_name_(device_name),
27      params_(params),
28      channels_(0),
29      volume_(0.0),
30      stream_started_(false),
31      pa_mainloop_(mainloop),
32      pa_context_(context),
33      handle_(NULL),
34      context_state_changed_(false) {
35  DCHECK(mainloop);
36  DCHECK(context);
37}
38
39PulseAudioInputStream::~PulseAudioInputStream() {
40  // All internal structures should already have been freed in Close(),
41  // which calls AudioManagerPulse::Release which deletes this object.
42  DCHECK(!handle_);
43}
44
45bool PulseAudioInputStream::Open() {
46  DCHECK(thread_checker_.CalledOnValidThread());
47  AutoPulseLock auto_lock(pa_mainloop_);
48  if (!pulse::CreateInputStream(pa_mainloop_, pa_context_, &handle_, params_,
49                                device_name_, &StreamNotifyCallback, this)) {
50    return false;
51  }
52
53  DCHECK(handle_);
54
55  buffer_.reset(new media::SeekableBuffer(0, 2 * params_.GetBytesPerBuffer()));
56  audio_data_buffer_.reset(new uint8[params_.GetBytesPerBuffer()]);
57  return true;
58}
59
60void PulseAudioInputStream::Start(AudioInputCallback* callback) {
61  DCHECK(thread_checker_.CalledOnValidThread());
62  DCHECK(callback);
63  DCHECK(handle_);
64  AutoPulseLock auto_lock(pa_mainloop_);
65
66  if (stream_started_)
67    return;
68
69  StartAgc();
70
71  // Clean up the old buffer.
72  pa_stream_drop(handle_);
73  buffer_->Clear();
74
75  // Start the streaming.
76  callback_ = callback;
77  pa_stream_set_read_callback(handle_, &ReadCallback, this);
78  pa_stream_readable_size(handle_);
79  stream_started_ = true;
80
81  pa_operation* operation = pa_stream_cork(handle_, 0, NULL, NULL);
82  WaitForOperationCompletion(pa_mainloop_, operation);
83}
84
85void PulseAudioInputStream::Stop() {
86  DCHECK(thread_checker_.CalledOnValidThread());
87  AutoPulseLock auto_lock(pa_mainloop_);
88  if (!stream_started_)
89    return;
90
91  StopAgc();
92
93  // Set the flag to false to stop filling new data to soundcard.
94  stream_started_ = false;
95
96  pa_operation* operation = pa_stream_flush(handle_,
97                                            &pulse::StreamSuccessCallback,
98                                            pa_mainloop_);
99  WaitForOperationCompletion(pa_mainloop_, operation);
100
101  // Stop the stream.
102  pa_stream_set_read_callback(handle_, NULL, NULL);
103  operation = pa_stream_cork(handle_, 1, &pulse::StreamSuccessCallback,
104                             pa_mainloop_);
105  WaitForOperationCompletion(pa_mainloop_, operation);
106}
107
108void PulseAudioInputStream::Close() {
109  DCHECK(thread_checker_.CalledOnValidThread());
110  {
111    AutoPulseLock auto_lock(pa_mainloop_);
112    if (handle_) {
113      // Disable all the callbacks before disconnecting.
114      pa_stream_set_state_callback(handle_, NULL, NULL);
115      pa_stream_flush(handle_, NULL, NULL);
116
117      if (pa_stream_get_state(handle_) != PA_STREAM_UNCONNECTED)
118        pa_stream_disconnect(handle_);
119
120      // Release PulseAudio structures.
121      pa_stream_unref(handle_);
122      handle_ = NULL;
123    }
124  }
125
126  if (callback_)
127    callback_->OnClose(this);
128
129  // Signal to the manager that we're closed and can be removed.
130  // This should be the last call in the function as it deletes "this".
131  audio_manager_->ReleaseInputStream(this);
132}
133
134double PulseAudioInputStream::GetMaxVolume() {
135  return static_cast<double>(PA_VOLUME_NORM);
136}
137
138void PulseAudioInputStream::SetVolume(double volume) {
139  AutoPulseLock auto_lock(pa_mainloop_);
140  if (!handle_)
141    return;
142
143  size_t index = pa_stream_get_device_index(handle_);
144  pa_operation* operation = NULL;
145  if (!channels_) {
146    // Get the number of channels for the source only when the |channels_| is 0.
147    // We are assuming the stream source is not changed on the fly here.
148    operation = pa_context_get_source_info_by_index(
149        pa_context_, index, &VolumeCallback, this);
150    WaitForOperationCompletion(pa_mainloop_, operation);
151    if (!channels_) {
152      DLOG(WARNING) << "Failed to get the number of channels for the source";
153      return;
154    }
155  }
156
157  pa_cvolume pa_volume;
158  pa_cvolume_set(&pa_volume, channels_, volume);
159  operation = pa_context_set_source_volume_by_index(
160      pa_context_, index, &pa_volume, NULL, NULL);
161
162  // Don't need to wait for this task to complete.
163  pa_operation_unref(operation);
164}
165
166double PulseAudioInputStream::GetVolume() {
167  if (pa_threaded_mainloop_in_thread(pa_mainloop_)) {
168    // When being called by the pulse thread, GetVolume() is asynchronous and
169    // called under AutoPulseLock.
170    if (!handle_)
171      return 0.0;
172
173    size_t index = pa_stream_get_device_index(handle_);
174    pa_operation* operation = pa_context_get_source_info_by_index(
175        pa_context_, index, &VolumeCallback, this);
176    // Do not wait for the operation since we can't block the pulse thread.
177    pa_operation_unref(operation);
178
179    // Return zero and the callback will asynchronously update the |volume_|.
180    return 0.0;
181  } else {
182    // Called by other thread, put an AutoPulseLock and wait for the operation.
183    AutoPulseLock auto_lock(pa_mainloop_);
184    if (!handle_)
185      return 0.0;
186
187    size_t index = pa_stream_get_device_index(handle_);
188    pa_operation* operation = pa_context_get_source_info_by_index(
189        pa_context_, index, &VolumeCallback, this);
190    WaitForOperationCompletion(pa_mainloop_, operation);
191
192    return volume_;
193  }
194}
195
196// static, used by pa_stream_set_read_callback.
197void PulseAudioInputStream::ReadCallback(pa_stream* handle,
198                                         size_t length,
199                                         void* user_data) {
200  PulseAudioInputStream* stream =
201      reinterpret_cast<PulseAudioInputStream*>(user_data);
202
203  stream->ReadData();
204}
205
206// static, used by pa_context_get_source_info_by_index.
207void PulseAudioInputStream::VolumeCallback(pa_context* context,
208                                           const pa_source_info* info,
209                                           int error, void* user_data) {
210  PulseAudioInputStream* stream =
211      reinterpret_cast<PulseAudioInputStream*>(user_data);
212
213  if (error) {
214    pa_threaded_mainloop_signal(stream->pa_mainloop_, 0);
215    return;
216  }
217
218  if (stream->channels_ != info->channel_map.channels)
219    stream->channels_ = info->channel_map.channels;
220
221  pa_volume_t volume = PA_VOLUME_MUTED;  // Minimum possible value.
222  // Use the max volume of any channel as the volume.
223  for (int i = 0; i < stream->channels_; ++i) {
224    if (volume < info->volume.values[i])
225      volume = info->volume.values[i];
226  }
227
228  // It is safe to access |volume_| here since VolumeCallback() is running
229  // under PulseLock.
230  stream->volume_ = static_cast<double>(volume);
231}
232
233// static, used by pa_stream_set_state_callback.
234void PulseAudioInputStream::StreamNotifyCallback(pa_stream* s,
235                                                 void* user_data) {
236  PulseAudioInputStream* stream =
237      reinterpret_cast<PulseAudioInputStream*>(user_data);
238  if (s && stream->callback_ &&
239      pa_stream_get_state(s) == PA_STREAM_FAILED) {
240    stream->callback_->OnError(stream);
241  }
242
243  pa_threaded_mainloop_signal(stream->pa_mainloop_, 0);
244}
245
246void PulseAudioInputStream::ReadData() {
247  uint32 hardware_delay = pulse::GetHardwareLatencyInBytes(
248      handle_, params_.sample_rate(), params_.GetBytesPerFrame());
249
250  // Update the AGC volume level once every second. Note that,
251  // |volume| is also updated each time SetVolume() is called
252  // through IPC by the render-side AGC.
253  // We disregard the |normalized_volume| from GetAgcVolume()
254  // and use the value calculated by |volume_|.
255  double normalized_volume = 0.0;
256  GetAgcVolume(&normalized_volume);
257  normalized_volume = volume_ / GetMaxVolume();
258
259  do {
260    size_t length = 0;
261    const void* data = NULL;
262    pa_stream_peek(handle_, &data, &length);
263    if (!data || length == 0)
264      break;
265
266    buffer_->Append(reinterpret_cast<const uint8*>(data), length);
267
268    // Checks if we still have data.
269    pa_stream_drop(handle_);
270  } while (pa_stream_readable_size(handle_) > 0);
271
272  int packet_size = params_.GetBytesPerBuffer();
273  while (buffer_->forward_bytes() >= packet_size) {
274    buffer_->Read(audio_data_buffer_.get(), packet_size);
275    callback_->OnData(this, audio_data_buffer_.get(), packet_size,
276                      hardware_delay, normalized_volume);
277
278    if (buffer_->forward_bytes() < packet_size)
279      break;
280
281    // TODO(xians): improve the code by implementing a WaitTillDataReady on the
282    // input side.
283    DVLOG(1) << "OnData is being called consecutively, sleep 5ms to "
284             << "wait until render consumes the data";
285    base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(5));
286  }
287
288  pa_threaded_mainloop_signal(pa_mainloop_, 0);
289}
290
291}  // namespace media
292