summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/audio_mixer_alsa.cc
blob: 28e51147a8fe98bb2007aaae8979da2f22fba9fd (plain)
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
// Copyright (c) 2010 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 "chrome/browser/chromeos/audio_mixer_alsa.h"

#include <alsa/asoundlib.h>

#include "base/logging.h"
#include "base/task.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/pref_names.h"

namespace chromeos {

// Connect to the ALSA mixer using their simple element API.  Init is performed
// asynchronously on the worker thread.
//
// To get a wider range and finer control over volume levels, first the Master
// level is set, then if the PCM element exists, the total level is refined by
// adjusting that as well.  If the PCM element has more volume steps, it allows
// for finer granularity in the total volume.

typedef long alsa_long_t;  // 'long' is required for ALSA API calls.

namespace {

const char* kMasterVolume = "Master";
const char* kPCMVolume = "PCM";
const double kDefaultMinVolume = -90.0;
const double kDefaultMaxVolume = 0.0;
const double kPrefVolumeInvalid = -999.0;
const int kPrefMuteOff = 0;
const int kPrefMuteOn = 1;
const int kPrefMuteInvalid = 2;

}  // namespace

AudioMixerAlsa::AudioMixerAlsa()
    : min_volume_(kDefaultMinVolume),
      max_volume_(kDefaultMaxVolume),
      save_volume_(0),
      mixer_state_(UNINITIALIZED),
      alsa_mixer_(NULL),
      elem_master_(NULL),
      elem_pcm_(NULL) {
}

AudioMixerAlsa::~AudioMixerAlsa() {
  FreeAlsaMixer();
  if (thread_ != NULL) {
    thread_->Stop();
    thread_.reset();
  }
}

void AudioMixerAlsa::Init(InitDoneCallback* callback) {
  DCHECK(callback);
  if (!InitThread()) {
    callback->Run(false);
    delete callback;
    return;
  }
  InitPrefs();

  // Post the task of starting up, which may block on the order of ms,
  // so best not to do it on the caller's thread.
  thread_->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(this, &AudioMixerAlsa::DoInit, callback));
}

bool AudioMixerAlsa::InitSync() {
  if (!InitThread())
    return false;
  InitPrefs();
  return InitializeAlsaMixer();
}

double AudioMixerAlsa::GetVolumeDb() const {
  base::AutoLock lock(mixer_state_lock_);
  if (mixer_state_ != READY)
    return kSilenceDb;

  return DoGetVolumeDb_Locked();
}

bool AudioMixerAlsa::GetVolumeLimits(double* vol_min, double* vol_max) {
  base::AutoLock lock(mixer_state_lock_);
  if (mixer_state_ != READY)
    return false;
  if (vol_min)
    *vol_min = min_volume_;
  if (vol_max)
    *vol_max = max_volume_;
  return true;
}

void AudioMixerAlsa::SetVolumeDb(double vol_db) {
  base::AutoLock lock(mixer_state_lock_);
  if (mixer_state_ != READY)
    return;
  if (vol_db < kSilenceDb)
    vol_db = kSilenceDb;
  DoSetVolumeDb_Locked(vol_db);
  volume_pref_.SetValue(vol_db);
}

bool AudioMixerAlsa::IsMute() const {
  base::AutoLock lock(mixer_state_lock_);
  if (mixer_state_ != READY)
    return false;
  return GetElementMuted_Locked(elem_master_);
}

// To indicate the volume is not valid yet, a very low volume value is stored.
// We compare against a slightly higher value in case of rounding errors.
static bool PrefVolumeValid(double volume) {
  return (volume > kPrefVolumeInvalid + 0.1);
}

void AudioMixerAlsa::SetMute(bool mute) {
  base::AutoLock lock(mixer_state_lock_);
  if (mixer_state_ != READY)
    return;

  // Set volume to minimum on mute, since switching the element off does not
  // always mute as it should.

  // TODO(davej): Remove save_volume_ and setting volume to minimum if
  // switching the element off can be guaranteed to mute it.  Currently mute
  // is done by setting the volume to min_volume_.

  bool old_value = GetElementMuted_Locked(elem_master_);

  if (old_value != mute) {
    if (mute) {
      save_volume_ = DoGetVolumeDb_Locked();
      DoSetVolumeDb_Locked(min_volume_);
    } else {
      DoSetVolumeDb_Locked(save_volume_);
    }
  }

  SetElementMuted_Locked(elem_master_, mute);
  if (elem_pcm_)
    SetElementMuted_Locked(elem_pcm_, mute);
  mute_pref_.SetValue(mute ? kPrefMuteOn : kPrefMuteOff);
}

AudioMixer::State AudioMixerAlsa::GetState() const {
  base::AutoLock lock(mixer_state_lock_);
  // If we think it's ready, verify it is actually so.
  if ((mixer_state_ == READY) && (alsa_mixer_ == NULL))
    mixer_state_ = IN_ERROR;
  return mixer_state_;
}

// static
void AudioMixerAlsa::RegisterPrefs(PrefService* local_state) {
  if (!local_state->FindPreference(prefs::kAudioVolume))
    local_state->RegisterRealPref(prefs::kAudioVolume, kPrefVolumeInvalid);
  if (!local_state->FindPreference(prefs::kAudioMute))
    local_state->RegisterIntegerPref(prefs::kAudioMute, kPrefMuteInvalid);
}

////////////////////////////////////////////////////////////////////////////////
// Private functions follow

void AudioMixerAlsa::DoInit(InitDoneCallback* callback) {
  bool success = InitializeAlsaMixer();

  if (success) {
    BrowserThread::PostTask(
        BrowserThread::UI, FROM_HERE,
        NewRunnableMethod(this, &AudioMixerAlsa::RestoreVolumeMuteOnUIThread));
  }

  if (callback) {
    callback->Run(success);
    delete callback;
  }
}

bool AudioMixerAlsa::InitThread() {
  base::AutoLock lock(mixer_state_lock_);

  if (mixer_state_ != UNINITIALIZED)
    return false;

  if (thread_ == NULL) {
    thread_.reset(new base::Thread("AudioMixerAlsa"));
    if (!thread_->Start()) {
      thread_.reset();
      return false;
    }
  }

  mixer_state_ = INITIALIZING;
  return true;
}

void AudioMixerAlsa::InitPrefs() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  PrefService* prefs = g_browser_process->local_state();
  volume_pref_.Init(prefs::kAudioVolume, prefs, NULL);
  mute_pref_.Init(prefs::kAudioMute, prefs, NULL);
}

bool AudioMixerAlsa::InitializeAlsaMixer() {
  base::AutoLock lock(mixer_state_lock_);
  if (mixer_state_ != INITIALIZING)
    return false;

  int err;
  snd_mixer_t* handle = NULL;
  const char* card = "default";

  if ((err = snd_mixer_open(&handle, 0)) < 0) {
    LOG(ERROR) << "ALSA mixer " << card << " open error: " << snd_strerror(err);
    return false;
  }

  if ((err = snd_mixer_attach(handle, card)) < 0) {
    LOG(ERROR) << "ALSA Attach to card " << card << " failed: "
               << snd_strerror(err);
    snd_mixer_close(handle);
    return false;
  }

  if ((err = snd_mixer_selem_register(handle, NULL, NULL)) < 0) {
    LOG(ERROR) << "ALSA mixer register error: " << snd_strerror(err);
    snd_mixer_close(handle);
    return false;
  }

  if ((err = snd_mixer_load(handle)) < 0) {
    LOG(ERROR) << "ALSA mixer " << card << " load error: %s"
               << snd_strerror(err);
    snd_mixer_close(handle);
    return false;
  }

  VLOG(1) << "Opened ALSA mixer " << card << " OK";

  elem_master_ = FindElementWithName_Locked(handle, kMasterVolume);
  if (elem_master_) {
    alsa_long_t long_lo, long_hi;
    snd_mixer_selem_get_playback_dB_range(elem_master_, &long_lo, &long_hi);
    min_volume_ = static_cast<double>(long_lo) / 100.0;
    max_volume_ = static_cast<double>(long_hi) / 100.0;
  } else {
    LOG(ERROR) << "Cannot find 'Master' ALSA mixer element on " << card;
    snd_mixer_close(handle);
    return false;
  }

  elem_pcm_ = FindElementWithName_Locked(handle, kPCMVolume);
  if (elem_pcm_) {
    alsa_long_t long_lo, long_hi;
    snd_mixer_selem_get_playback_dB_range(elem_pcm_, &long_lo, &long_hi);
    min_volume_ += static_cast<double>(long_lo) / 100.0;
    max_volume_ += static_cast<double>(long_hi) / 100.0;
  }

  VLOG(1) << "ALSA volume range is " << min_volume_ << " dB to "
          << max_volume_ << " dB";

  alsa_mixer_ = handle;
  mixer_state_ = READY;
  return true;
}

void AudioMixerAlsa::FreeAlsaMixer() {
  base::AutoLock lock(mixer_state_lock_);
  mixer_state_ = SHUTTING_DOWN;
  if (alsa_mixer_) {
    snd_mixer_close(alsa_mixer_);
    alsa_mixer_ = NULL;
  }
}

void AudioMixerAlsa::DoSetVolumeMute(double pref_volume, int pref_mute) {
  base::AutoLock lock(mixer_state_lock_);
  if (mixer_state_ != READY)
    return;

  // If volume or mute are invalid, set them now to the current actual values.
  if (!PrefVolumeValid(pref_volume))
    pref_volume = DoGetVolumeDb_Locked();
  bool mute;
  if (pref_mute == kPrefMuteInvalid)
    mute = GetElementMuted_Locked(elem_master_);
  else
    mute = (pref_mute == kPrefMuteOn) ? true : false;

  VLOG(1) << "Setting volume to " << pref_volume << " and mute to " << mute;

  if (mute) {
    save_volume_ = pref_volume;
    DoSetVolumeDb_Locked(min_volume_);
  } else if (pref_mute == kPrefMuteOff) {
      DoSetVolumeDb_Locked(pref_volume);
  }

  SetElementMuted_Locked(elem_master_, mute);
  if (elem_pcm_)
    SetElementMuted_Locked(elem_pcm_, mute);
}

void AudioMixerAlsa::RestoreVolumeMuteOnUIThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // This happens during init, so set the volume off the UI thread.
  thread_->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(this, &AudioMixerAlsa::DoSetVolumeMute,
                        volume_pref_.GetValue(), mute_pref_.GetValue()));
}

double AudioMixerAlsa::DoGetVolumeDb_Locked() const {
  double vol_total = 0.0;
  GetElementVolume_Locked(elem_master_, &vol_total);

  double vol_pcm = 0.0;
  if (elem_pcm_ && (GetElementVolume_Locked(elem_pcm_, &vol_pcm)))
    vol_total += vol_pcm;

  return vol_total;
}

void AudioMixerAlsa::DoSetVolumeDb_Locked(double vol_db) {
  double actual_vol = 0.0;

  // If a PCM volume slider exists, then first set the Master volume to the
  // nearest volume >= requested volume, then adjust PCM volume down to get
  // closer to the requested volume.
  if (elem_pcm_) {
    SetElementVolume_Locked(elem_master_, vol_db, &actual_vol, 0.9999f);
    SetElementVolume_Locked(elem_pcm_, vol_db - actual_vol, NULL, 0.5f);
  } else {
    SetElementVolume_Locked(elem_master_, vol_db, NULL, 0.5f);
  }
}

snd_mixer_elem_t* AudioMixerAlsa::FindElementWithName_Locked(
    snd_mixer_t* handle,
    const char* element_name) const {
  snd_mixer_selem_id_t* sid;

  // Using id_malloc/id_free API instead of id_alloca since the latter gives the
  // warning: the address of 'sid' will always evaluate as 'true'.
  if (snd_mixer_selem_id_malloc(&sid))
    return NULL;

  snd_mixer_selem_id_set_index(sid, 0);
  snd_mixer_selem_id_set_name(sid, element_name);
  snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid);
  if (!elem) {
    LOG(ERROR) << "ALSA unable to find simple control "
               << snd_mixer_selem_id_get_name(sid);
  }

  snd_mixer_selem_id_free(sid);
  return elem;
}

bool AudioMixerAlsa::GetElementVolume_Locked(snd_mixer_elem_t* elem,
                                             double* current_vol) const {
  alsa_long_t long_vol = 0;
  snd_mixer_selem_get_playback_dB(elem,
                                  static_cast<snd_mixer_selem_channel_id_t>(0),
                                  &long_vol);
  *current_vol = static_cast<double>(long_vol) / 100.0;

  return true;
}

bool AudioMixerAlsa::SetElementVolume_Locked(snd_mixer_elem_t* elem,
                                             double new_vol,
                                             double* actual_vol,
                                             double rounding_bias) {
  alsa_long_t vol_lo = 0;
  alsa_long_t vol_hi = 0;
  snd_mixer_selem_get_playback_volume_range(elem, &vol_lo, &vol_hi);
  alsa_long_t vol_range = vol_hi - vol_lo;
  if (vol_range <= 0)
    return false;

  alsa_long_t db_lo_int = 0;
  alsa_long_t db_hi_int = 0;
  snd_mixer_selem_get_playback_dB_range(elem, &db_lo_int, &db_hi_int);
  double db_lo = static_cast<double>(db_lo_int) / 100.0;
  double db_hi = static_cast<double>(db_hi_int) / 100.0;
  double db_step = static_cast<double>(db_hi - db_lo) / vol_range;
  if (db_step <= 0.0)
    return false;

  if (new_vol < db_lo)
    new_vol = db_lo;

  alsa_long_t value = static_cast<alsa_long_t>(rounding_bias +
      (new_vol - db_lo) / db_step) + vol_lo;
  snd_mixer_selem_set_playback_volume_all(elem, value);

  VLOG(1) << "Set volume " << snd_mixer_selem_get_name(elem)
          << " to " << new_vol << " ==> " << (value - vol_lo) * db_step + db_lo
          << " dB";

  if (actual_vol) {
    alsa_long_t volume;
    snd_mixer_selem_get_playback_volume(
        elem,
        static_cast<snd_mixer_selem_channel_id_t>(0),
        &volume);
    *actual_vol = db_lo + (volume - vol_lo) * db_step;

    VLOG(1) << "Actual volume " << snd_mixer_selem_get_name(elem)
            << " now " << *actual_vol << " dB";
  }
  return true;
}

bool AudioMixerAlsa::GetElementMuted_Locked(snd_mixer_elem_t* elem) const {
  int enabled;
  snd_mixer_selem_get_playback_switch(
      elem,
      static_cast<snd_mixer_selem_channel_id_t>(0),
      &enabled);
  return (enabled) ? false : true;
}

void AudioMixerAlsa::SetElementMuted_Locked(snd_mixer_elem_t* elem, bool mute) {
  int enabled = mute ? 0 : 1;
  snd_mixer_selem_set_playback_switch_all(elem, enabled);

  VLOG(1) << "Set playback switch " << snd_mixer_selem_get_name(elem)
          << " to " << enabled;
}

}  // namespace chromeos