summaryrefslogtreecommitdiffstats
path: root/media/audio/linux/alsa_input.cc
blob: 1eba936352ce6e1022c8c694df365daedcd52f3c (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
// Copyright (c) 2011 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 "media/audio/linux/alsa_input.h"

#include "base/basictypes.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "media/audio/linux/alsa_util.h"
#include "media/audio/linux/alsa_wrapper.h"

static const int kNumPacketsInRingBuffer = 3;

// If a read failed with no audio data, try again after this duration.
static const int kNoAudioReadAgainTimeoutMs = 20;

static const char kDefaultDevice1[] = "default";
static const char kDefaultDevice2[] = "plug:default";

const char* AlsaPcmInputStream::kAutoSelectDevice = "";

AlsaPcmInputStream::AlsaPcmInputStream(const std::string& device_name,
                                       const AudioParameters& params,
                                       AlsaWrapper* wrapper)
    : device_name_(device_name),
      params_(params),
      bytes_per_packet_(params.samples_per_packet *
                        (params.channels * params.bits_per_sample) / 8),
      wrapper_(wrapper),
      packet_duration_ms_(
          (params.samples_per_packet * base::Time::kMillisecondsPerSecond) /
          params.sample_rate),
      callback_(NULL),
      device_handle_(NULL),
      ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)),
      read_callback_behind_schedule_(false) {
}

AlsaPcmInputStream::~AlsaPcmInputStream() {}

bool AlsaPcmInputStream::Open() {
  if (device_handle_)
    return false;  // Already open.

  snd_pcm_format_t pcm_format = alsa_util::BitsToFormat(
      params_.bits_per_sample);
  if (pcm_format == SND_PCM_FORMAT_UNKNOWN) {
    LOG(WARNING) << "Unsupported bits per sample: "
                 << params_.bits_per_sample;
    return false;
  }

  int latency_us = packet_duration_ms_ * kNumPacketsInRingBuffer *
      base::Time::kMicrosecondsPerMillisecond;
  if (device_name_ == kAutoSelectDevice) {
    device_handle_ = alsa_util::OpenCaptureDevice(wrapper_, kDefaultDevice1,
                                                  params_.channels,
                                                  params_.sample_rate,
                                                  pcm_format, latency_us);
    if (!device_handle_) {
      device_handle_ = alsa_util::OpenCaptureDevice(wrapper_, kDefaultDevice2,
                                                    params_.channels,
                                                    params_.sample_rate,
                                                    pcm_format, latency_us);
    }
  } else {
    device_handle_ = alsa_util::OpenCaptureDevice(wrapper_,
                                                  device_name_.c_str(),
                                                  params_.channels,
                                                  params_.sample_rate,
                                                  pcm_format, latency_us);
  }

  if (device_handle_)
    audio_packet_.reset(new uint8[bytes_per_packet_]);

  return device_handle_ != NULL;
}

void AlsaPcmInputStream::Start(AudioInputCallback* callback) {
  DCHECK(!callback_ && callback);
  callback_ = callback;
  int error = wrapper_->PcmPrepare(device_handle_);
  if (error < 0) {
    HandleError("PcmPrepare", error);
  } else {
    error = wrapper_->PcmStart(device_handle_);
    if (error < 0)
      HandleError("PcmStart", error);
  }

  if (error < 0) {
    callback_ = NULL;
  } else {
    // We start reading data a little later than when the packet might have got
    // filled, to accommodate some delays in the audio driver. This could
    // also give us a smooth read sequence going forward.
    int64 delay_ms = packet_duration_ms_ + kNoAudioReadAgainTimeoutMs;
    next_read_time_ = base::Time::Now() + base::TimeDelta::FromMilliseconds(
        delay_ms);
    MessageLoop::current()->PostDelayedTask(
        FROM_HERE,
        task_factory_.NewRunnableMethod(&AlsaPcmInputStream::ReadAudio),
        delay_ms);
  }
}

bool AlsaPcmInputStream::Recover(int original_error) {
  int error = wrapper_->PcmRecover(device_handle_, original_error, 1);
  if (error < 0) {
    // Docs say snd_pcm_recover returns the original error if it is not one
    // of the recoverable ones, so this log message will probably contain the
    // same error twice.
    LOG(WARNING) << "Unable to recover from \""
                 << wrapper_->StrError(original_error) << "\": "
                 << wrapper_->StrError(error);
    return false;
  }

  if (original_error == -EPIPE) {  // Buffer underrun/overrun.
    // For capture streams we have to repeat the explicit start() to get
    // data flowing again.
    error = wrapper_->PcmStart(device_handle_);
    if (error < 0) {
      HandleError("PcmStart", error);
      return false;
    }
  }

  return true;
}

void AlsaPcmInputStream::ReadAudio() {
  DCHECK(callback_);

  snd_pcm_sframes_t frames = wrapper_->PcmAvailUpdate(device_handle_);
  if (frames < 0) {  // Potentially recoverable error?
    LOG(WARNING) << "PcmAvailUpdate(): " << wrapper_->StrError(frames);
    Recover(frames);
  }

  if (frames < params_.samples_per_packet) {
    // Not enough data yet or error happened. In both cases wait for a very
    // small duration before checking again.
    // Even Though read callback was behind schedule, there is no data, so
    // reset the next_read_time_.
    if (read_callback_behind_schedule_) {
      next_read_time_ = base::Time::Now();
      read_callback_behind_schedule_ = false;
    }
    MessageLoop::current()->PostDelayedTask(
        FROM_HERE,
        task_factory_.NewRunnableMethod(&AlsaPcmInputStream::ReadAudio),
        kNoAudioReadAgainTimeoutMs);
    return;
  }

  int num_packets = frames / params_.samples_per_packet;
  int num_packets_read = num_packets;
  while (num_packets--) {
    int frames_read = wrapper_->PcmReadi(device_handle_, audio_packet_.get(),
                                         params_.samples_per_packet);
    if (frames_read == params_.samples_per_packet) {
      callback_->OnData(this, audio_packet_.get(), bytes_per_packet_);
    } else {
      LOG(WARNING) << "PcmReadi returning less than expected frames: "
                   << frames_read << " vs. " << params_.samples_per_packet
                   << ". Dropping this packet.";
    }
  }

  next_read_time_ += base::TimeDelta::FromMilliseconds(
      packet_duration_ms_ * num_packets_read);
  int64 delay_ms = (next_read_time_ - base::Time::Now()).InMilliseconds();
  if (delay_ms < 0) {
    LOG(WARNING) << "Audio read callback behind schedule by "
                 << (packet_duration_ms_ - delay_ms) << " (ms).";
    // Read callback is behind schedule. Assuming there is data pending in
    // the soundcard, invoke the read callback immediate in order to catch up.
    read_callback_behind_schedule_ = true;
    delay_ms = 0;
  }

  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      task_factory_.NewRunnableMethod(&AlsaPcmInputStream::ReadAudio),
      delay_ms);
}

void AlsaPcmInputStream::Stop() {
  if (!device_handle_ || !callback_)
    return;

  task_factory_.RevokeAll();  // Cancel the next scheduled read.
  int error = wrapper_->PcmDrop(device_handle_);
  if (error < 0)
    HandleError("PcmDrop", error);
}

void AlsaPcmInputStream::Close() {
  scoped_ptr<AlsaPcmInputStream> self_deleter(this);

  // Check in case we were already closed or not initialized yet.
  if (!device_handle_ || !callback_)
    return;

  task_factory_.RevokeAll();  // Cancel the next scheduled read.
  int error = alsa_util::CloseDevice(wrapper_, device_handle_);
  if (error < 0)
    HandleError("PcmClose", error);

  audio_packet_.reset();
  device_handle_ = NULL;
  callback_->OnClose(this);
}

void AlsaPcmInputStream::HandleError(const char* method, int error) {
  LOG(WARNING) << method << ": " << wrapper_->StrError(error);
  callback_->OnError(this, error);
}