blob: afd9d7b6dd635e4cd9724c900e7af781e204c832 [file] [log] [blame]
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001/*
2 * Copyright (c) 2012 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 "webrtc/modules/audio_processing/agc/standalone_vad.h"
12
13#include <assert.h>
14
15#include "webrtc/modules/interface/module_common_types.h"
16#include "webrtc/modules/utility/interface/audio_frame_operations.h"
17#include "webrtc/typedefs.h"
18
19namespace webrtc {
20
21static const int kDefaultStandaloneVadMode = 3;
22
23StandaloneVad::StandaloneVad(VadInst* vad)
24 : vad_(vad),
25 buffer_(),
26 index_(0),
27 mode_(kDefaultStandaloneVadMode) {}
28
29StandaloneVad::~StandaloneVad() {
30 WebRtcVad_Free(vad_);
31}
32
33StandaloneVad* StandaloneVad::Create() {
34 VadInst* vad = NULL;
35 if (WebRtcVad_Create(&vad) < 0)
36 return NULL;
37
38 int err = WebRtcVad_Init(vad);
39 err |= WebRtcVad_set_mode(vad, kDefaultStandaloneVadMode);
40 if (err != 0) {
41 WebRtcVad_Free(vad);
42 return NULL;
43 }
44 return new StandaloneVad(vad);
45}
46
47int StandaloneVad::AddAudio(const int16_t* data, int length) {
48 if (length != kLength10Ms)
49 return -1;
50
51 if (index_ + length > kLength10Ms * kMaxNum10msFrames)
52 // Reset the buffer if it's full.
53 // TODO(ajm): Instead, consider just processing every 10 ms frame. Then we
54 // can forgo the buffering.
55 index_ = 0;
56
57 memcpy(&buffer_[index_], data, sizeof(int16_t) * length);
58 index_ += length;
59 return 0;
60}
61
62int StandaloneVad::GetActivity(double* p, int length_p) {
63 if (index_ == 0)
64 return -1;
65
66 const int num_frames = index_ / kLength10Ms;
67 if (num_frames > length_p)
68 return -1;
69 assert(WebRtcVad_ValidRateAndFrameLength(kSampleRateHz, index_) == 0);
70
71 int activity = WebRtcVad_Process(vad_, kSampleRateHz, buffer_, index_);
72 if (activity < 0)
73 return -1;
74 else if (activity == 0)
75 p[0] = 0.01; // Arbitrary but small and non-zero.
76 else
77 p[0] = 0.5; // 0.5 is neutral values when combinned by other probabilities.
78 for (int n = 1; n < num_frames; n++)
79 p[n] = p[0];
80 // Reset the buffer to start from the beginning.
81 index_ = 0;
82 return activity;
83}
84
85int StandaloneVad::set_mode(int mode) {
86 if (mode < 0 || mode > 3)
87 return -1;
88 if (WebRtcVad_set_mode(vad_, mode) != 0)
89 return -1;
90
91 mode_ = mode;
92 return 0;
93}
94
95} // namespace webrtc
96