aboutsummaryrefslogtreecommitdiff
path: root/platform/android/platform_audio.cc
blob: 39812b76ebe0f8725ee4509bc2dd01f95c738bdd (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
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "chre/platform/platform_audio.h"

#include <cinttypes>

#include "chre/core/audio_request_manager.h"
#include "chre/core/audio_util.h"
#include "chre/core/event_loop_manager.h"
#include "chre/platform/fatal_error.h"
#include "chre/platform/log.h"
#include "chre/platform/system_time.h"

namespace chre {

namespace {

//! The fixed sampling rate for audio data when running CHRE on Android.
constexpr uint32_t kAndroidAudioSampleRate = 16000;

//! The minimum buffer size in samples.
constexpr uint32_t kAndroidAudioMinBufferSize = kAndroidAudioSampleRate / 10;

//! The maximum buffer size in samples.
constexpr uint32_t kAndroidAudioMaxBufferSize = kAndroidAudioSampleRate * 10;

}  // namespace

void PlatformAudioBase::audioReadCallback(void *cookie) {
  auto *platformAudio = static_cast<PlatformAudio *>(cookie);

  auto &dataEvent = platformAudio->mDataEvent;
  Nanoseconds samplingTime = AudioUtil::getDurationFromSampleCountAndRate(
      platformAudio->mNumSamples, kAndroidAudioSampleRate);
  dataEvent.timestamp =
      (SystemTime::getMonotonicTime() - samplingTime).toRawNanoseconds();

  if (dataEvent.format == CHRE_AUDIO_DATA_FORMAT_16_BIT_SIGNED_PCM) {
    uint32_t intervalNumSamples = AudioUtil::getSampleCountFromRateAndDuration(
        kAndroidAudioSampleRate, platformAudio->mEventDelay);

    // Determine how much new audio data is required to be read from the device.
    // Samples that are already buffered by this implementation may be reused.
    int16_t *audioBuffer = platformAudio->mBuffer.data();
    uint32_t readAmount = platformAudio->mNumSamples;
    if (intervalNumSamples > platformAudio->mNumSamples) {
      uint32_t seekAmount = intervalNumSamples - platformAudio->mNumSamples;
      audioBuffer = &platformAudio->mBuffer.data()[seekAmount];
      readAmount = platformAudio->mNumSamples - seekAmount;
    }

    // Perform a blocking read. A timeout of 1 nanoasecond is passed here to
    // ensure that we read exactly the amount of requested audio frames. The
    // timer ensures that we wait approximately long enough to read the
    // requested number of samples and the timeout ensures that they match
    // exactly.
    int32_t framesRead =
        AAudioStream_read(platformAudio->mStream, audioBuffer, readAmount, 1);
    if (framesRead != static_cast<int32_t>(platformAudio->mNumSamples)) {
      FATAL_ERROR("Failed to read requested number of audio samples");
    } else {
      EventLoopManagerSingleton::get()
          ->getAudioRequestManager()
          .handleAudioDataEvent(&dataEvent);
    }
  } else {
    FATAL_ERROR("Unimplemented data format");
  }
}

PlatformAudio::PlatformAudio() {
  if (!mTimer.init()) {
    FATAL_ERROR("Failed to initialize audio timer");
  }

  aaudio_result_t result = AAudio_createStreamBuilder(&mStreamBuilder);
  if (result != AAUDIO_OK) {
    FATAL_ERROR("Failed to create audio stream builder with %" PRId32, result);
  }

  AAudioStreamBuilder_setDirection(mStreamBuilder, AAUDIO_DIRECTION_INPUT);
  AAudioStreamBuilder_setSharingMode(mStreamBuilder,
                                     AAUDIO_SHARING_MODE_SHARED);
  AAudioStreamBuilder_setSampleRate(mStreamBuilder, kAndroidAudioSampleRate);
  AAudioStreamBuilder_setChannelCount(mStreamBuilder, 1);
  AAudioStreamBuilder_setFormat(mStreamBuilder, AAUDIO_FORMAT_PCM_I16);
  AAudioStreamBuilder_setBufferCapacityInFrames(mStreamBuilder,
                                                kAndroidAudioMaxBufferSize);

  result = AAudioStreamBuilder_openStream(mStreamBuilder, &mStream);
  if (result != AAUDIO_OK) {
    FATAL_ERROR("Failed to create audio stream with %" PRId32, result);
  }

  int32_t bufferSize = AAudioStream_getBufferCapacityInFrames(mStream);
  LOGD("Created audio stream with %" PRId32 " frames buffer size", bufferSize);

  mMinBufferDuration = AudioUtil::getDurationFromSampleCountAndRate(
                           kAndroidAudioMinBufferSize, kAndroidAudioSampleRate)
                           .toRawNanoseconds();
  mMaxBufferDuration = AudioUtil::getDurationFromSampleCountAndRate(
                           bufferSize, kAndroidAudioSampleRate)
                           .toRawNanoseconds();

  result = AAudioStream_requestStart(mStream);
  if (result != AAUDIO_OK) {
    FATAL_ERROR("Failed to start audio stream with %" PRId32, result);
  }

  mBuffer.resize(bufferSize);
  initAudioDataEvent();
}

PlatformAudio::~PlatformAudio() {
  AAudioStream_close(mStream);
  AAudioStreamBuilder_delete(mStreamBuilder);
}

void PlatformAudio::init() {
  // TODO: Implement this.
}

void PlatformAudio::setHandleEnabled(uint32_t handle, bool enabled) {
  // TODO: Implement this.
}

bool PlatformAudio::requestAudioDataEvent(uint32_t handle, uint32_t numSamples,
                                          Nanoseconds eventDelay) {
  mNumSamples = numSamples;
  mEventDelay = eventDelay;
  mDataEvent.sampleCount = numSamples;
  return mTimer.set(audioReadCallback, this, eventDelay);
}

void PlatformAudio::cancelAudioDataEventRequest(uint32_t handle) {
  mTimer.cancel();
}

void PlatformAudio::releaseAudioDataEvent(struct chreAudioDataEvent *event) {}

size_t PlatformAudio::getSourceCount() {
  // Hardcoded at one as the Android platform only surfaces the default mic.
  return 1;
}

bool PlatformAudio::getAudioSource(uint32_t handle,
                                   chreAudioSource *audioSource) const {
  bool success = false;
  if (handle == 0) {
    audioSource->name = "Default Android Audio Input";
    audioSource->sampleRate = kAndroidAudioSampleRate;
    audioSource->minBufferDuration = mMinBufferDuration;
    audioSource->maxBufferDuration = mMaxBufferDuration;
    audioSource->format = mDataEvent.format;
    success = true;
  }

  return success;
}

void PlatformAudioBase::initAudioDataEvent() {
  mDataEvent.version = CHRE_AUDIO_DATA_EVENT_VERSION;
  memset(mDataEvent.reserved, 0, sizeof(mDataEvent.reserved));
  mDataEvent.handle = 0;
  mDataEvent.sampleRate = kAndroidAudioSampleRate;
  mDataEvent.format = CHRE_AUDIO_DATA_FORMAT_16_BIT_SIGNED_PCM;
  mDataEvent.samplesS16 = mBuffer.data();
}

}  // namespace chre