xref: /aosp_15_r20/external/webrtc/modules/audio_coding/neteq/tools/audio_loop.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
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 #include "modules/audio_coding/neteq/tools/audio_loop.h"
12 
13 #include <stdio.h>
14 #include <string.h>
15 
16 #include "absl/strings/string_view.h"
17 
18 namespace webrtc {
19 namespace test {
20 
Init(absl::string_view file_name,size_t max_loop_length_samples,size_t block_length_samples)21 bool AudioLoop::Init(absl::string_view file_name,
22                      size_t max_loop_length_samples,
23                      size_t block_length_samples) {
24   FILE* fp = fopen(std::string(file_name).c_str(), "rb");
25   if (!fp)
26     return false;
27 
28   audio_array_.reset(
29       new int16_t[max_loop_length_samples + block_length_samples]);
30   size_t samples_read =
31       fread(audio_array_.get(), sizeof(int16_t), max_loop_length_samples, fp);
32   fclose(fp);
33 
34   // Block length must be shorter than the loop length.
35   if (block_length_samples > samples_read)
36     return false;
37 
38   // Add an extra block length of samples to the end of the array, starting
39   // over again from the beginning of the array. This is done to simplify
40   // the reading process when reading over the end of the loop.
41   memcpy(&audio_array_[samples_read], audio_array_.get(),
42          block_length_samples * sizeof(int16_t));
43 
44   loop_length_samples_ = samples_read;
45   block_length_samples_ = block_length_samples;
46   next_index_ = 0;
47   return true;
48 }
49 
GetNextBlock()50 rtc::ArrayView<const int16_t> AudioLoop::GetNextBlock() {
51   // Check that the AudioLoop is initialized.
52   if (block_length_samples_ == 0)
53     return rtc::ArrayView<const int16_t>();
54 
55   const int16_t* output_ptr = &audio_array_[next_index_];
56   next_index_ = (next_index_ + block_length_samples_) % loop_length_samples_;
57   return rtc::ArrayView<const int16_t>(output_ptr, block_length_samples_);
58 }
59 
60 }  // namespace test
61 }  // namespace webrtc
62