blob: decfacd0c18037608357cb7d153d6dc9ccd81312 [file] [log] [blame]
Alex Loikodb6af362018-06-20 14:14:18 +02001/*
2 * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "modules/audio_processing/agc2/vad_with_level.h"
12
13#include <algorithm>
14
15#include "common_audio/include/audio_util.h"
16#include "modules/audio_processing/agc2/rnn_vad/common.h"
17#include "rtc_base/checks.h"
18
19namespace webrtc {
20
21namespace {
22float ProcessForPeak(AudioFrameView<const float> frame) {
23 float current_max = 0;
24 for (const auto& x : frame.channel(0)) {
25 current_max = std::max(std::fabs(x), current_max);
26 }
27 return current_max;
28}
29
30float ProcessForRms(AudioFrameView<const float> frame) {
31 float rms = 0;
32 for (const auto& x : frame.channel(0)) {
33 rms += x * x;
34 }
35 return sqrt(rms / frame.samples_per_channel());
36}
37} // namespace
38
39VadWithLevel::VadWithLevel() = default;
40VadWithLevel::~VadWithLevel() = default;
41
42VadWithLevel::LevelAndProbability VadWithLevel::AnalyzeFrame(
43 AudioFrameView<const float> frame) {
44 SetSampleRate(static_cast<int>(frame.samples_per_channel() * 100));
45 std::array<float, rnn_vad::kFrameSize10ms24kHz> work_frame;
46 // Feed the 1st channel to the resampler.
47 resampler_.Resample(frame.channel(0).data(), frame.samples_per_channel(),
48 work_frame.data(), rnn_vad::kFrameSize10ms24kHz);
49
50 std::array<float, rnn_vad::kFeatureVectorSize> feature_vector;
51
52 const bool is_silence = features_extractor_.CheckSilenceComputeFeatures(
53 work_frame, feature_vector);
54 const float vad_probability =
55 rnn_vad_.ComputeVadProbability(feature_vector, is_silence);
56 return LevelAndProbability(vad_probability,
57 FloatS16ToDbfs(ProcessForRms(frame)),
58 FloatS16ToDbfs(ProcessForPeak(frame)));
59}
60
61void VadWithLevel::SetSampleRate(int sample_rate_hz) {
62 // The source number of channels in 1, because we always use the 1st
63 // channel.
64 resampler_.InitializeIfNeeded(sample_rate_hz, rnn_vad::kSampleRate24kHz,
65 1 /* num_channels */);
66}
67
68} // namespace webrtc