audio_pull_fifo.cc revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
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/base/audio_pull_fifo.h"
6
7#include <algorithm>
8
9#include "base/logging.h"
10
11namespace media {
12
13AudioPullFifo::AudioPullFifo(int channels, int frames, const ReadCB& read_cb)
14    : read_cb_(read_cb) {
15  fifo_.reset(new AudioFifo(channels, frames));
16  bus_ = AudioBus::Create(channels, frames);
17}
18
19AudioPullFifo::~AudioPullFifo() {
20  read_cb_.Reset();
21}
22
23void AudioPullFifo::Consume(AudioBus* destination, int frames_to_consume) {
24  DCHECK(destination);
25  DCHECK_LE(frames_to_consume, destination->frames());
26
27  int write_pos = 0;
28  int remaining_frames_to_provide = frames_to_consume;
29
30  // Try to fulfill the request using what's available in the FIFO.
31  ReadFromFifo(destination, &remaining_frames_to_provide, &write_pos);
32
33  // Get the remaining audio frames from the producer using the callback.
34  while (remaining_frames_to_provide > 0) {
35    // Fill up the FIFO by acquiring audio data from the producer.
36    read_cb_.Run(write_pos, bus_.get());
37    fifo_->Push(bus_.get());
38
39    // Try to fulfill the request using what's available in the FIFO.
40    ReadFromFifo(destination, &remaining_frames_to_provide, &write_pos);
41  }
42}
43
44void AudioPullFifo::Clear() {
45  fifo_->Clear();
46}
47
48void AudioPullFifo::ReadFromFifo(AudioBus* destination,
49                                 int* frames_to_provide,
50                                 int* write_pos) {
51  DCHECK(frames_to_provide);
52  DCHECK(write_pos);
53  int frames = std::min(fifo_->frames(), *frames_to_provide);
54  fifo_->Consume(destination, *write_pos, frames);
55  *write_pos += frames;
56  *frames_to_provide -= frames;
57}
58
59}  // namespace media
60