summaryrefslogtreecommitdiffstats
path: root/media/audio/audio_controller.cc
blob: 802a97c40be5958917928f8db0b5716b687364b0 (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
// 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 "media/audio/audio_controller.h"

// The following parameters limit the request buffer and packet size from the
// renderer to avoid renderer from requesting too much memory.
static const uint32 kMegabytes = 1024 * 1024;
static const uint32 kMaxHardwareBufferSize = 2 * kMegabytes;
static const int kMaxChannels = 32;
static const int kMaxBitsPerSample = 64;
static const int kMaxSampleRate = 192000;

// Return true if the parameters for creating an audio stream is valid.
// Return false otherwise.
static bool CheckParameters(int channels, int sample_rate,
                            int bits_per_sample, uint32 hardware_buffer_size) {
  if (channels <= 0 || channels > kMaxChannels)
    return false;
  if (sample_rate <= 0 || sample_rate > kMaxSampleRate)
    return false;
  if (bits_per_sample <= 0 || bits_per_sample > kMaxBitsPerSample)
    return false;
  if (hardware_buffer_size <= 0 ||
      hardware_buffer_size > kMaxHardwareBufferSize) {
    return false;
  }
  return true;
}

namespace media {

AudioController::AudioController(EventHandler* handler, uint32 capacity,
                                 SyncReader* sync_reader)
    : handler_(handler),
      volume_(0),
      state_(kEmpty),
      hardware_pending_bytes_(0),
      buffer_capacity_(capacity),
      sync_reader_(sync_reader),
      thread_("AudioControllerThread") {
}

AudioController::~AudioController() {
  DCHECK(kClosed == state_);
}

// static
scoped_refptr<AudioController> AudioController::Create(
    EventHandler* event_handler,
    AudioManager::Format format,
    int channels,
    int sample_rate,
    int bits_per_sample,
    uint32 hardware_buffer_size,
    uint32 buffer_capacity) {

  if (!CheckParameters(channels, sample_rate, bits_per_sample,
                       hardware_buffer_size))
    return NULL;

  // Starts the audio controller thread.
  scoped_refptr<AudioController> controller = new AudioController(
      event_handler, buffer_capacity, NULL);

  // Start the audio controller thread and post a task to create the
  // audio stream.
  controller->thread_.Start();
  controller->thread_.message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(controller.get(), &AudioController::DoCreate,
                        format, channels, sample_rate, bits_per_sample,
                        hardware_buffer_size));
  return controller;
}

// static
scoped_refptr<AudioController> AudioController::CreateLowLatency(
    EventHandler* event_handler,
    AudioManager::Format format,
    int channels,
    int sample_rate,
    int bits_per_sample,
    uint32 hardware_buffer_size,
    SyncReader* sync_reader) {

  DCHECK(sync_reader);

  if (!CheckParameters(channels, sample_rate, bits_per_sample,
                       hardware_buffer_size))
    return NULL;

  // Starts the audio controller thread.
  scoped_refptr<AudioController> controller = new AudioController(
      event_handler, 0, sync_reader);

  // Start the audio controller thread and post a task to create the
  // audio stream.
  controller->thread_.Start();
  controller->thread_.message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(controller.get(), &AudioController::DoCreate,
                        format, channels, sample_rate, bits_per_sample,
                        hardware_buffer_size));
  return controller;
}

void AudioController::Play() {
  DCHECK(thread_.IsRunning());
  thread_.message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(this, &AudioController::DoPlay));
}

void AudioController::Pause() {
  DCHECK(thread_.IsRunning());
  thread_.message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(this, &AudioController::DoPause));
}

void AudioController::Flush() {
  DCHECK(thread_.IsRunning());
  thread_.message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(this, &AudioController::DoFlush));
}

void AudioController::Close() {
  if (!thread_.IsRunning()) {
    // If the thread is not running make sure we are stopped.
    DCHECK_EQ(kClosed, state_);
    return;
  }

  // Wait for all tasks to complete on the audio thread.
  thread_.message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(this, &AudioController::DoClose));
  thread_.Stop();
}

void AudioController::SetVolume(double volume) {
  DCHECK(thread_.IsRunning());
  thread_.message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(this, &AudioController::DoSetVolume, volume));
}

void AudioController::EnqueueData(const uint8* data, uint32 size) {
  // Write data to the push source and ask for more data if needed.
  AutoLock auto_lock(lock_);
  push_source_.Write(data, size);
  SubmitOnMoreData_Locked();
}

void AudioController::DoCreate(AudioManager::Format format, int channels,
                              int sample_rate, int bits_per_sample,
                              uint32 hardware_buffer_size) {
  DCHECK_EQ(thread_.message_loop(), MessageLoop::current());
  DCHECK_EQ(kEmpty, state_);

  // Create the stream in the first place.
  stream_ = AudioManager::GetAudioManager()->MakeAudioStream(
      format, channels, sample_rate, bits_per_sample);

  if (!stream_) {
    // TODO(hclam): Define error types.
    handler_->OnError(this, 0);
    return;
  }

  if (stream_ && !stream_->Open(hardware_buffer_size)) {
    stream_->Close();
    stream_ = NULL;

    // TODO(hclam): Define error types.
    handler_->OnError(this, 0);
    return;
  }
  // We have successfully opened the stream. Set the initial volume.
  stream_->SetVolume(volume_);

  // Finally set the state to kCreated.
  state_ = kCreated;

  // And then report we have been created.
  handler_->OnCreated(this);

  // If in normal latency mode then start buffering.
  if (!LowLatencyMode()) {
    AutoLock auto_lock(lock_);
    SubmitOnMoreData_Locked();
  }
}

void AudioController::DoPlay() {
  DCHECK_EQ(thread_.message_loop(), MessageLoop::current());

  // We can start from created or paused state.
  if (state_ != kCreated && state_ != kPaused)
    return;

  State old_state;
  // Update the |state_| to kPlaying.
  {
    AutoLock auto_lock(lock_);
    old_state = state_;
    state_ = kPlaying;
  }

  // We start the AudioOutputStream lazily.
  if (old_state == kCreated) {
    stream_->Start(this);
  }

  // Tell the event handler that we are now playing.
  handler_->OnPlaying(this);
}

void AudioController::DoPause() {
  DCHECK_EQ(thread_.message_loop(), MessageLoop::current());

  // We can pause from started state.
  if (state_ != kPlaying)
    return;

  // Sets the |state_| to kPaused so we don't draw more audio data.
  // TODO(hclam): Actually pause the audio device.
  {
    AutoLock auto_lock(lock_);
    state_ = kPaused;
  }

  handler_->OnPaused(this);
}

void AudioController::DoFlush() {
  DCHECK_EQ(thread_.message_loop(), MessageLoop::current());

  if (state_ != kPaused)
    return;

  // TODO(hclam): Actually flush the audio device.

  // If we are in the regular latency mode then flush the push source.
  if (!sync_reader_) {
    AutoLock auto_lock(lock_);
    push_source_.ClearAll();
  }
}

void AudioController::DoClose() {
  DCHECK_EQ(thread_.message_loop(), MessageLoop::current());
  DCHECK_NE(kClosed, state_);

  // |stream_| can be null if creating the device failed in DoCreate().
  if (stream_) {
    stream_->Stop();
    stream_->Close();
    // After stream is closed it is destroyed, so don't keep a reference to it.
    stream_ = NULL;
  }

  // Update the current state. Since the stream is closed at this point
  // there's no other threads reading |state_| so we don't need to lock.
  state_ = kClosed;
}

void AudioController::DoSetVolume(double volume) {
  DCHECK_EQ(thread_.message_loop(), MessageLoop::current());

  // Saves the volume to a member first. We may not be able to set the volume
  // right away but when the stream is created we'll set the volume.
  volume_ = volume;

  if (state_ != kPlaying && state_ != kPaused && state_ != kCreated)
    return;

  stream_->SetVolume(volume_);
}

void AudioController::DoReportError(int code) {
  DCHECK_EQ(thread_.message_loop(), MessageLoop::current());
  handler_->OnError(this, code);
}

uint32 AudioController::OnMoreData(AudioOutputStream* stream,
                                   void* dest,
                                   uint32 max_size,
                                   uint32 pending_bytes) {
  // If regular latency mode is used.
  if (!sync_reader_) {
    AutoLock auto_lock(lock_);

    // Record the callback time.
    last_callback_time_ = base::Time::Now();

    if (state_ != kPlaying) {
      // Don't read anything. Save the number of bytes in the hardware buffer.
      hardware_pending_bytes_ = pending_bytes;
      return 0;
    }

    // Push source doesn't need to know the stream and number of pending bytes.
    // So just pass in NULL and 0.
    uint32 size = push_source_.OnMoreData(NULL, dest, max_size, 0);
    hardware_pending_bytes_ = pending_bytes + size;
    SubmitOnMoreData_Locked();
    return size;
  }

  // Low latency mode.
  uint32 size =  sync_reader_->Read(dest, max_size);
  sync_reader_->UpdatePendingBytes(pending_bytes + size);
  return size;
}

void AudioController::OnClose(AudioOutputStream* stream) {
  // Push source doesn't need to know the stream so just pass in NULL.
  if (LowLatencyMode()) {
    sync_reader_->Close();
  } else {
    AutoLock auto_lock(lock_);
    push_source_.OnClose(NULL);
  }
}

void AudioController::OnError(AudioOutputStream* stream, int code) {
  // Handle error on the audio controller thread.
  thread_.message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(this, &AudioController::DoReportError, code));
}

void AudioController::SubmitOnMoreData_Locked() {
  lock_.AssertAcquired();

  if (push_source_.UnProcessedBytes() > buffer_capacity_)
    return;

  base::Time timestamp = last_callback_time_;
  uint32 pending_bytes = hardware_pending_bytes_ +
      push_source_.UnProcessedBytes();

  // If we need more data then call the event handler to ask for more data.
  // It is okay that we don't lock in this block because the parameters are
  // correct and in the worst case we are just asking more data than needed.
  AutoUnlock auto_unlock(lock_);
  handler_->OnMoreData(this, timestamp, pending_bytes);
}

}  // namespace media