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 "webrtc/modules/audio_coding/neteq/tools/input_audio_file.h"
12
13#include "webrtc/base/checks.h"
14
15namespace webrtc {
16namespace test {
17
18InputAudioFile::InputAudioFile(const std::string file_name) {
19  fp_ = fopen(file_name.c_str(), "rb");
20}
21
22InputAudioFile::~InputAudioFile() { fclose(fp_); }
23
24bool InputAudioFile::Read(size_t samples, int16_t* destination) {
25  if (!fp_) {
26    return false;
27  }
28  size_t samples_read = fread(destination, sizeof(int16_t), samples, fp_);
29  if (samples_read < samples) {
30    // Rewind and read the missing samples.
31    rewind(fp_);
32    size_t missing_samples = samples - samples_read;
33    if (fread(destination, sizeof(int16_t), missing_samples, fp_) <
34        missing_samples) {
35      // Could not read enough even after rewinding the file.
36      return false;
37    }
38  }
39  return true;
40}
41
42bool InputAudioFile::Seek(int samples) {
43  if (!fp_) {
44    return false;
45  }
46  // Find file boundaries.
47  const long current_pos = ftell(fp_);
48  RTC_CHECK_NE(EOF, current_pos)
49      << "Error returned when getting file position.";
50  RTC_CHECK_EQ(0, fseek(fp_, 0, SEEK_END));  // Move to end of file.
51  const long file_size = ftell(fp_);
52  RTC_CHECK_NE(EOF, file_size) << "Error returned when getting file position.";
53  // Find new position.
54  long new_pos = current_pos + sizeof(int16_t) * samples;  // Samples to bytes.
55  RTC_CHECK_GE(new_pos, 0)
56      << "Trying to move to before the beginning of the file";
57  new_pos = new_pos % file_size;  // Wrap around the end of the file.
58  // Move to new position relative to the beginning of the file.
59  RTC_CHECK_EQ(0, fseek(fp_, new_pos, SEEK_SET));
60  return true;
61}
62
63void InputAudioFile::DuplicateInterleaved(const int16_t* source, size_t samples,
64                                          size_t channels,
65                                          int16_t* destination) {
66  // Start from the end of |source| and |destination|, and work towards the
67  // beginning. This is to allow in-place interleaving of the same array (i.e.,
68  // |source| and |destination| are the same array).
69  for (int i = static_cast<int>(samples - 1); i >= 0; --i) {
70    for (int j = static_cast<int>(channels - 1); j >= 0; --j) {
71      destination[i * channels + j] = source[i];
72    }
73  }
74}
75
76}  // namespace test
77}  // namespace webrtc
78