cras_input.cc revision eb525c5499e34cc9c4b825d6d9e75bb07cc06ace
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/cras/cras_input.h"
6
7#include <math.h>
8
9#include "base/basictypes.h"
10#include "base/bind.h"
11#include "base/logging.h"
12#include "base/time/time.h"
13#include "media/audio/audio_manager.h"
14#include "media/audio/cras/audio_manager_cras.h"
15#include "media/audio/linux/alsa_util.h"
16
17namespace media {
18
19CrasInputStream::CrasInputStream(const AudioParameters& params,
20                                 AudioManagerCras* manager)
21    : audio_manager_(manager),
22      bytes_per_frame_(0),
23      callback_(NULL),
24      client_(NULL),
25      params_(params),
26      started_(false),
27      stream_id_(0) {
28  DCHECK(audio_manager_);
29}
30
31CrasInputStream::~CrasInputStream() {
32  DCHECK(!client_);
33}
34
35bool CrasInputStream::Open() {
36  if (client_) {
37    NOTREACHED() << "CrasInputStream already open";
38    return false;  // Already open.
39  }
40
41  // Sanity check input values.
42  if (params_.sample_rate() <= 0) {
43    DLOG(WARNING) << "Unsupported audio frequency.";
44    return false;
45  }
46
47  if (AudioParameters::AUDIO_PCM_LINEAR != params_.format() &&
48      AudioParameters::AUDIO_PCM_LOW_LATENCY != params_.format()) {
49    DLOG(WARNING) << "Unsupported audio format.";
50    return false;
51  }
52
53  snd_pcm_format_t pcm_format =
54      alsa_util::BitsToFormat(params_.bits_per_sample());
55  if (pcm_format == SND_PCM_FORMAT_UNKNOWN) {
56    DLOG(WARNING) << "Unsupported bits/sample: " << params_.bits_per_sample();
57    return false;
58  }
59
60  // Create the client and connect to the CRAS server.
61  if (cras_client_create(&client_) < 0) {
62    DLOG(WARNING) << "Couldn't create CRAS client.\n";
63    client_ = NULL;
64    return false;
65  }
66
67  if (cras_client_connect(client_)) {
68    DLOG(WARNING) << "Couldn't connect CRAS client.\n";
69    cras_client_destroy(client_);
70    client_ = NULL;
71    return false;
72  }
73
74  // Then start running the client.
75  if (cras_client_run_thread(client_)) {
76    DLOG(WARNING) << "Couldn't run CRAS client.\n";
77    cras_client_destroy(client_);
78    client_ = NULL;
79    return false;
80  }
81
82  return true;
83}
84
85void CrasInputStream::Close() {
86  if (client_) {
87    cras_client_stop(client_);
88    cras_client_destroy(client_);
89    client_ = NULL;
90  }
91
92  if (callback_) {
93    callback_->OnClose(this);
94    callback_ = NULL;
95  }
96
97  // Signal to the manager that we're closed and can be removed.
98  // Should be last call in the method as it deletes "this".
99  audio_manager_->ReleaseInputStream(this);
100}
101
102void CrasInputStream::Start(AudioInputCallback* callback) {
103  DCHECK(client_);
104  DCHECK(callback);
105
106  // If already playing, stop before re-starting.
107  if (started_)
108    return;
109
110  StartAgc();
111
112  callback_ = callback;
113  LOG(ERROR) << "Input Start";
114
115  // Prepare |audio_format| and |stream_params| for the stream we
116  // will create.
117  cras_audio_format* audio_format = cras_audio_format_create(
118      alsa_util::BitsToFormat(params_.bits_per_sample()),
119      params_.sample_rate(),
120      params_.channels());
121  if (!audio_format) {
122    DLOG(WARNING) << "Error setting up audio parameters.";
123    callback_->OnError(this);
124    callback_ = NULL;
125    return;
126  }
127
128  unsigned int frames_per_packet = params_.frames_per_buffer();
129  cras_stream_params* stream_params = cras_client_stream_params_create(
130      CRAS_STREAM_INPUT,
131      frames_per_packet,  // Total latency.
132      frames_per_packet,  // Call back when this many ready.
133      frames_per_packet,  // Minimum Callback level ignored for capture streams.
134      CRAS_STREAM_TYPE_DEFAULT,
135      0,  // Unused flags.
136      this,
137      CrasInputStream::SamplesReady,
138      CrasInputStream::StreamError,
139      audio_format);
140  if (!stream_params) {
141    DLOG(WARNING) << "Error setting up stream parameters.";
142    callback_->OnError(this);
143    callback_ = NULL;
144    cras_audio_format_destroy(audio_format);
145    return;
146  }
147
148  // Before starting the stream, save the number of bytes in a frame for use in
149  // the callback.
150  bytes_per_frame_ = cras_client_format_bytes_per_frame(audio_format);
151
152  // Adding the stream will start the audio callbacks.
153  if (cras_client_add_stream(client_, &stream_id_, stream_params)) {
154    DLOG(WARNING) << "Failed to add the stream.";
155    callback_->OnError(this);
156    callback_ = NULL;
157  }
158
159  // Done with config params.
160  cras_audio_format_destroy(audio_format);
161  cras_client_stream_params_destroy(stream_params);
162
163  started_ = true;
164}
165
166void CrasInputStream::Stop() {
167  DCHECK(client_);
168
169  if (!callback_ || !started_)
170    return;
171
172  StopAgc();
173
174  // Removing the stream from the client stops audio.
175  cras_client_rm_stream(client_, stream_id_);
176
177  started_ = false;
178}
179
180// Static callback asking for samples.  Run on high priority thread.
181int CrasInputStream::SamplesReady(cras_client* client,
182                                  cras_stream_id_t stream_id,
183                                  uint8* samples,
184                                  size_t frames,
185                                  const timespec* sample_ts,
186                                  void* arg) {
187  CrasInputStream* me = static_cast<CrasInputStream*>(arg);
188  me->ReadAudio(frames, samples, sample_ts);
189  return frames;
190}
191
192// Static callback for stream errors.
193int CrasInputStream::StreamError(cras_client* client,
194                                 cras_stream_id_t stream_id,
195                                 int err,
196                                 void* arg) {
197  CrasInputStream* me = static_cast<CrasInputStream*>(arg);
198  me->NotifyStreamError(err);
199  return 0;
200}
201
202void CrasInputStream::ReadAudio(size_t frames,
203                                uint8* buffer,
204                                const timespec* sample_ts) {
205  DCHECK(callback_);
206
207  timespec latency_ts = {0, 0};
208
209  // Determine latency and pass that on to the sink.  sample_ts is the wall time
210  // indicating when the first sample in the buffer was captured.  Convert that
211  // to latency in bytes.
212  cras_client_calc_capture_latency(sample_ts, &latency_ts);
213  double latency_usec =
214      latency_ts.tv_sec * base::Time::kMicrosecondsPerSecond +
215      latency_ts.tv_nsec / base::Time::kNanosecondsPerMicrosecond;
216  double frames_latency =
217      latency_usec * params_.sample_rate() / base::Time::kMicrosecondsPerSecond;
218  unsigned int bytes_latency =
219      static_cast<unsigned int>(frames_latency * bytes_per_frame_);
220
221  // Update the AGC volume level once every second. Note that, |volume| is
222  // also updated each time SetVolume() is called through IPC by the
223  // render-side AGC.
224  double normalized_volume = 0.0;
225  GetAgcVolume(&normalized_volume);
226
227  callback_->OnData(this,
228                    buffer,
229                    frames * bytes_per_frame_,
230                    bytes_latency,
231                    normalized_volume);
232}
233
234void CrasInputStream::NotifyStreamError(int err) {
235  if (callback_)
236    callback_->OnError(this);
237}
238
239double CrasInputStream::GetMaxVolume() {
240  DCHECK(client_);
241
242  // Capture gain is returned as dB * 100 (150 => 1.5dBFS).  Convert the dB
243  // value to a ratio before returning.
244  double dB = cras_client_get_system_max_capture_gain(client_) / 100.0;
245  return GetVolumeRatioFromDecibels(dB);
246}
247
248void CrasInputStream::SetVolume(double volume) {
249  DCHECK(client_);
250
251  // Convert from the passed volume ratio, to dB * 100.
252  double dB = GetDecibelsFromVolumeRatio(volume);
253  cras_client_set_system_capture_gain(client_, static_cast<long>(dB * 100.0));
254
255  // Update the AGC volume level based on the last setting above. Note that,
256  // the volume-level resolution is not infinite and it is therefore not
257  // possible to assume that the volume provided as input parameter can be
258  // used directly. Instead, a new query to the audio hardware is required.
259  // This method does nothing if AGC is disabled.
260  UpdateAgcVolume();
261}
262
263double CrasInputStream::GetVolume() {
264  if (!client_)
265    return 0.0;
266
267  long dB = cras_client_get_system_capture_gain(client_) / 100.0;
268  return GetVolumeRatioFromDecibels(dB);
269}
270
271double CrasInputStream::GetVolumeRatioFromDecibels(double dB) const {
272  return pow(10, dB / 20.0);
273}
274
275double CrasInputStream::GetDecibelsFromVolumeRatio(double volume_ratio) const {
276  return 20 * log10(volume_ratio);
277}
278
279}  // namespace media
280