1 /*
2  *  Copyright (c) 2013 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 #ifndef MODULES_AUDIO_PROCESSING_TRANSIENT_DYADIC_DECIMATOR_H_
12 #define MODULES_AUDIO_PROCESSING_TRANSIENT_DYADIC_DECIMATOR_H_
13 
14 #include <cstdlib>
15 
16 // Provides a set of static methods to perform dyadic decimations.
17 
18 namespace webrtc {
19 
20 // Returns the proper length of the output buffer that you should use for the
21 // given |in_length| and decimation |odd_sequence|.
22 // Return -1 on error.
GetOutLengthToDyadicDecimate(size_t in_length,bool odd_sequence)23 inline size_t GetOutLengthToDyadicDecimate(size_t in_length,
24                                            bool odd_sequence) {
25   size_t out_length = in_length / 2;
26 
27   if (in_length % 2 == 1 && !odd_sequence) {
28     ++out_length;
29   }
30 
31   return out_length;
32 }
33 
34 // Performs a dyadic decimation: removes every odd/even member of a sequence
35 // halving its overall length.
36 // Arguments:
37 //    in: array of |in_length|.
38 //    odd_sequence: If false, the odd members will be removed (1, 3, 5, ...);
39 //                  if true, the even members will be removed (0, 2, 4, ...).
40 //    out: array of |out_length|. |out_length| must be large enough to
41 //         hold the decimated output. The necessary length can be provided by
42 //         GetOutLengthToDyadicDecimate().
43 //         Must be previously allocated.
44 // Returns the number of output samples, -1 on error.
45 template <typename T>
DyadicDecimate(const T * in,size_t in_length,bool odd_sequence,T * out,size_t out_length)46 static size_t DyadicDecimate(const T* in,
47                              size_t in_length,
48                              bool odd_sequence,
49                              T* out,
50                              size_t out_length) {
51   size_t half_length = GetOutLengthToDyadicDecimate(in_length, odd_sequence);
52 
53   if (!in || !out || in_length <= 0 || out_length < half_length) {
54     return 0;
55   }
56 
57   size_t output_samples = 0;
58   size_t index_adjustment = odd_sequence ? 1 : 0;
59   for (output_samples = 0; output_samples < half_length; ++output_samples) {
60     out[output_samples] = in[output_samples * 2 + index_adjustment];
61   }
62 
63   return output_samples;
64 }
65 
66 }  // namespace webrtc
67 
68 #endif  // MODULES_AUDIO_PROCESSING_TRANSIENT_DYADIC_DECIMATOR_H_
69