1/*
2 *  Copyright (c) 2014 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 <limits>
12
13#include "webrtc/audio_processing/debug.pb.h"
14#include "webrtc/common_audio/include/audio_util.h"
15#include "webrtc/common_audio/wav_writer.h"
16#include "webrtc/modules/audio_processing/common.h"
17#include "webrtc/modules/audio_processing/include/audio_processing.h"
18#include "webrtc/modules/interface/module_common_types.h"
19#include "webrtc/system_wrappers/interface/scoped_ptr.h"
20
21namespace webrtc {
22
23static const AudioProcessing::Error kNoErr = AudioProcessing::kNoError;
24#define EXPECT_NOERR(expr) EXPECT_EQ(kNoErr, (expr))
25
26class RawFile {
27 public:
28  RawFile(const std::string& filename)
29      : file_handle_(fopen(filename.c_str(), "wb")) {}
30
31  ~RawFile() {
32    fclose(file_handle_);
33  }
34
35  void WriteSamples(const int16_t* samples, size_t num_samples) {
36#ifndef WEBRTC_ARCH_LITTLE_ENDIAN
37#error "Need to convert samples to little-endian when writing to PCM file"
38#endif
39    fwrite(samples, sizeof(*samples), num_samples, file_handle_);
40  }
41
42  void WriteSamples(const float* samples, size_t num_samples) {
43    fwrite(samples, sizeof(*samples), num_samples, file_handle_);
44  }
45
46 private:
47  FILE* file_handle_;
48};
49
50static inline void WriteIntData(const int16_t* data,
51                                size_t length,
52                                WavFile* wav_file,
53                                RawFile* raw_file) {
54  if (wav_file) {
55    wav_file->WriteSamples(data, length);
56  }
57  if (raw_file) {
58    raw_file->WriteSamples(data, length);
59  }
60}
61
62static inline void WriteFloatData(const float* const* data,
63                                  size_t samples_per_channel,
64                                  int num_channels,
65                                  WavFile* wav_file,
66                                  RawFile* raw_file) {
67  size_t length = num_channels * samples_per_channel;
68  scoped_ptr<float[]> buffer(new float[length]);
69  Interleave(data, samples_per_channel, num_channels, buffer.get());
70  if (raw_file) {
71    raw_file->WriteSamples(buffer.get(), length);
72  }
73  // TODO(aluebs): Use ScaleToInt16Range() from audio_util
74  for (size_t i = 0; i < length; ++i) {
75    buffer[i] = buffer[i] > 0 ?
76                buffer[i] * std::numeric_limits<int16_t>::max() :
77                -buffer[i] * std::numeric_limits<int16_t>::min();
78  }
79  if (wav_file) {
80    wav_file->WriteSamples(buffer.get(), length);
81  }
82}
83
84// Exits on failure; do not use in unit tests.
85static inline FILE* OpenFile(const std::string& filename, const char* mode) {
86  FILE* file = fopen(filename.c_str(), mode);
87  if (!file) {
88    printf("Unable to open file %s\n", filename.c_str());
89    exit(1);
90  }
91  return file;
92}
93
94static inline int SamplesFromRate(int rate) {
95  return AudioProcessing::kChunkSizeMs * rate / 1000;
96}
97
98static inline void SetFrameSampleRate(AudioFrame* frame,
99                                      int sample_rate_hz) {
100  frame->sample_rate_hz_ = sample_rate_hz;
101  frame->samples_per_channel_ = AudioProcessing::kChunkSizeMs *
102      sample_rate_hz / 1000;
103}
104
105template <typename T>
106void SetContainerFormat(int sample_rate_hz,
107                        int num_channels,
108                        AudioFrame* frame,
109                        scoped_ptr<ChannelBuffer<T> >* cb) {
110  SetFrameSampleRate(frame, sample_rate_hz);
111  frame->num_channels_ = num_channels;
112  cb->reset(new ChannelBuffer<T>(frame->samples_per_channel_, num_channels));
113}
114
115static inline AudioProcessing::ChannelLayout LayoutFromChannels(
116    int num_channels) {
117  switch (num_channels) {
118    case 1:
119      return AudioProcessing::kMono;
120    case 2:
121      return AudioProcessing::kStereo;
122    default:
123      assert(false);
124      return AudioProcessing::kMono;
125  }
126}
127
128// Allocates new memory in the scoped_ptr to fit the raw message and returns the
129// number of bytes read.
130static inline size_t ReadMessageBytesFromFile(FILE* file,
131                                              scoped_ptr<uint8_t[]>* bytes) {
132  // The "wire format" for the size is little-endian. Assume we're running on
133  // a little-endian machine.
134  int32_t size = 0;
135  if (fread(&size, sizeof(size), 1, file) != 1)
136    return 0;
137  if (size <= 0)
138    return 0;
139
140  bytes->reset(new uint8_t[size]);
141  return fread(bytes->get(), sizeof((*bytes)[0]), size, file);
142}
143
144// Returns true on success, false on error or end-of-file.
145static inline bool ReadMessageFromFile(FILE* file,
146                                       ::google::protobuf::MessageLite* msg) {
147  scoped_ptr<uint8_t[]> bytes;
148  size_t size = ReadMessageBytesFromFile(file, &bytes);
149  if (!size)
150    return false;
151
152  msg->Clear();
153  return msg->ParseFromArray(bytes.get(), size);
154}
155
156}  // namespace webrtc
157