1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "media/base/audio_bus.h"
6 
7 #include <stddef.h>
8 #include <stdint.h>
9 
10 #include <limits>
11 #include <utility>
12 
13 #include "base/logging.h"
14 #include "base/memory/ptr_util.h"
15 #include "base/numerics/safe_conversions.h"
16 #include "media/base/audio_parameters.h"
17 #include "media/base/limits.h"
18 #include "media/base/vector_math.h"
19 
20 namespace media {
21 
IsAligned(void * ptr)22 static bool IsAligned(void* ptr) {
23   return (reinterpret_cast<uintptr_t>(ptr) &
24           (AudioBus::kChannelAlignment - 1)) == 0U;
25 }
26 
27 // In order to guarantee that the memory block for each channel starts at an
28 // aligned address when splitting a contiguous block of memory into one block
29 // per channel, we may have to make these blocks larger than otherwise needed.
30 // We do this by allocating space for potentially more frames than requested.
31 // This method returns the required size for the contiguous memory block
32 // in bytes and outputs the adjusted number of frames via |out_aligned_frames|.
CalculateMemorySizeInternal(int channels,int frames,int * out_aligned_frames)33 static int CalculateMemorySizeInternal(int channels,
34                                        int frames,
35                                        int* out_aligned_frames) {
36   // Since our internal sample format is float, we can guarantee the alignment
37   // by making the number of frames an integer multiple of
38   // AudioBus::kChannelAlignment / sizeof(float).
39   int aligned_frames =
40       ((frames * sizeof(float) + AudioBus::kChannelAlignment - 1) &
41        ~(AudioBus::kChannelAlignment - 1)) / sizeof(float);
42 
43   if (out_aligned_frames)
44     *out_aligned_frames = aligned_frames;
45 
46   return sizeof(float) * channels * aligned_frames;
47 }
48 
ValidateConfig(int channels,int frames)49 static void ValidateConfig(int channels, int frames) {
50   CHECK_GT(frames, 0);
51   CHECK_GT(channels, 0);
52   CHECK_LE(channels, static_cast<int>(limits::kMaxChannels));
53 }
54 
CheckOverflow(int start_frame,int frames,int total_frames)55 void AudioBus::CheckOverflow(int start_frame, int frames, int total_frames) {
56   CHECK_GE(start_frame, 0);
57   CHECK_GE(frames, 0);
58   CHECK_GT(total_frames, 0);
59   int sum = start_frame + frames;
60   CHECK_LE(sum, total_frames);
61   CHECK_GE(sum, 0);
62 }
63 
AudioBus(int channels,int frames)64 AudioBus::AudioBus(int channels, int frames)
65     : frames_(frames),
66       can_set_channel_data_(false) {
67   ValidateConfig(channels, frames_);
68 
69   int aligned_frames = 0;
70   int size = CalculateMemorySizeInternal(channels, frames, &aligned_frames);
71 
72   data_.reset(static_cast<float*>(base::AlignedAlloc(
73       size, AudioBus::kChannelAlignment)));
74 
75   BuildChannelData(channels, aligned_frames, data_.get());
76 }
77 
AudioBus(int channels,int frames,float * data)78 AudioBus::AudioBus(int channels, int frames, float* data)
79     : frames_(frames),
80       can_set_channel_data_(false) {
81   // Since |data| may have come from an external source, ensure it's valid.
82   CHECK(data);
83   ValidateConfig(channels, frames_);
84 
85   int aligned_frames = 0;
86   CalculateMemorySizeInternal(channels, frames, &aligned_frames);
87 
88   BuildChannelData(channels, aligned_frames, data);
89 }
90 
AudioBus(int frames,const std::vector<float * > & channel_data)91 AudioBus::AudioBus(int frames, const std::vector<float*>& channel_data)
92     : channel_data_(channel_data),
93       frames_(frames),
94       can_set_channel_data_(false) {
95   ValidateConfig(
96       base::checked_cast<int>(channel_data_.size()), frames_);
97 
98   // Sanity check wrapped vector for alignment and channel count.
99   for (size_t i = 0; i < channel_data_.size(); ++i)
100     DCHECK(IsAligned(channel_data_[i]));
101 }
102 
AudioBus(int channels)103 AudioBus::AudioBus(int channels)
104     : channel_data_(channels),
105       frames_(0),
106       can_set_channel_data_(true) {
107   CHECK_GT(channels, 0);
108   for (size_t i = 0; i < channel_data_.size(); ++i)
109     channel_data_[i] = NULL;
110 }
111 
112 AudioBus::~AudioBus() = default;
113 
Create(int channels,int frames)114 std::unique_ptr<AudioBus> AudioBus::Create(int channels, int frames) {
115   return base::WrapUnique(new AudioBus(channels, frames));
116 }
117 
Create(const AudioParameters & params)118 std::unique_ptr<AudioBus> AudioBus::Create(const AudioParameters& params) {
119   return base::WrapUnique(
120       new AudioBus(params.channels(), params.frames_per_buffer()));
121 }
122 
CreateWrapper(int channels)123 std::unique_ptr<AudioBus> AudioBus::CreateWrapper(int channels) {
124   return base::WrapUnique(new AudioBus(channels));
125 }
126 
WrapVector(int frames,const std::vector<float * > & channel_data)127 std::unique_ptr<AudioBus> AudioBus::WrapVector(
128     int frames,
129     const std::vector<float*>& channel_data) {
130   return base::WrapUnique(new AudioBus(frames, channel_data));
131 }
132 
WrapMemory(int channels,int frames,void * data)133 std::unique_ptr<AudioBus> AudioBus::WrapMemory(int channels,
134                                                int frames,
135                                                void* data) {
136   // |data| must be aligned by AudioBus::kChannelAlignment.
137   CHECK(IsAligned(data));
138   return base::WrapUnique(
139       new AudioBus(channels, frames, static_cast<float*>(data)));
140 }
141 
WrapMemory(const AudioParameters & params,void * data)142 std::unique_ptr<AudioBus> AudioBus::WrapMemory(const AudioParameters& params,
143                                                void* data) {
144   // |data| must be aligned by AudioBus::kChannelAlignment.
145   CHECK(IsAligned(data));
146   return base::WrapUnique(new AudioBus(params.channels(),
147                                        params.frames_per_buffer(),
148                                        static_cast<float*>(data)));
149 }
150 
WrapReadOnlyMemory(int channels,int frames,const void * data)151 std::unique_ptr<const AudioBus> AudioBus::WrapReadOnlyMemory(int channels,
152                                                              int frames,
153                                                              const void* data) {
154   // Note: const_cast is generally dangerous but is used in this case since
155   // AudioBus accomodates both read-only and read/write use cases. A const
156   // AudioBus object is returned to ensure no one accidentally writes to the
157   // read-only data.
158   return WrapMemory(channels, frames, const_cast<void*>(data));
159 }
160 
WrapReadOnlyMemory(const AudioParameters & params,const void * data)161 std::unique_ptr<const AudioBus> AudioBus::WrapReadOnlyMemory(
162     const AudioParameters& params,
163     const void* data) {
164   // Note: const_cast is generally dangerous but is used in this case since
165   // AudioBus accomodates both read-only and read/write use cases. A const
166   // AudioBus object is returned to ensure no one accidentally writes to the
167   // read-only data.
168   return WrapMemory(params, const_cast<void*>(data));
169 }
170 
SetChannelData(int channel,float * data)171 void AudioBus::SetChannelData(int channel, float* data) {
172   CHECK(can_set_channel_data_);
173   CHECK(data);
174   CHECK_GE(channel, 0);
175   CHECK_LT(static_cast<size_t>(channel), channel_data_.size());
176   DCHECK(IsAligned(data));
177   channel_data_[channel] = data;
178 }
179 
set_frames(int frames)180 void AudioBus::set_frames(int frames) {
181   CHECK(can_set_channel_data_);
182   ValidateConfig(static_cast<int>(channel_data_.size()), frames);
183   frames_ = frames;
184 }
185 
GetBitstreamDataSize() const186 size_t AudioBus::GetBitstreamDataSize() const {
187   DCHECK(is_bitstream_format_);
188   return bitstream_data_size_;
189 }
190 
SetBitstreamDataSize(size_t data_size)191 void AudioBus::SetBitstreamDataSize(size_t data_size) {
192   DCHECK(is_bitstream_format_);
193   bitstream_data_size_ = data_size;
194 }
195 
GetBitstreamFrames() const196 int AudioBus::GetBitstreamFrames() const {
197   DCHECK(is_bitstream_format_);
198   return bitstream_frames_;
199 }
200 
SetBitstreamFrames(int frames)201 void AudioBus::SetBitstreamFrames(int frames) {
202   DCHECK(is_bitstream_format_);
203   bitstream_frames_ = frames;
204 }
205 
ZeroFramesPartial(int start_frame,int frames)206 void AudioBus::ZeroFramesPartial(int start_frame, int frames) {
207   CheckOverflow(start_frame, frames, frames_);
208 
209   if (frames <= 0)
210     return;
211 
212   if (is_bitstream_format_) {
213     // No need to clean unused region for bitstream formats.
214     if (start_frame >= bitstream_frames_)
215       return;
216 
217     // Cannot clean partial frames.
218     DCHECK_EQ(start_frame, 0);
219     DCHECK(frames >= bitstream_frames_);
220 
221     // For compressed bitstream, zeroed buffer is not valid and would be
222     // discarded immediately. It is faster and makes more sense to reset
223     // |bitstream_data_size_| and |is_bitstream_format_| so that the buffer
224     // contains no data instead of zeroed data.
225     SetBitstreamDataSize(0);
226     SetBitstreamFrames(0);
227     return;
228   }
229 
230   for (size_t i = 0; i < channel_data_.size(); ++i) {
231     memset(channel_data_[i] + start_frame, 0,
232            frames * sizeof(*channel_data_[i]));
233   }
234 }
235 
ZeroFrames(int frames)236 void AudioBus::ZeroFrames(int frames) {
237   ZeroFramesPartial(0, frames);
238 }
239 
Zero()240 void AudioBus::Zero() {
241   ZeroFrames(frames_);
242 }
243 
AreFramesZero() const244 bool AudioBus::AreFramesZero() const {
245   DCHECK(!is_bitstream_format_);
246   for (size_t i = 0; i < channel_data_.size(); ++i) {
247     for (int j = 0; j < frames_; ++j) {
248       if (channel_data_[i][j])
249         return false;
250     }
251   }
252   return true;
253 }
254 
CalculateMemorySize(const AudioParameters & params)255 int AudioBus::CalculateMemorySize(const AudioParameters& params) {
256   return CalculateMemorySizeInternal(
257       params.channels(), params.frames_per_buffer(), NULL);
258 }
259 
CalculateMemorySize(int channels,int frames)260 int AudioBus::CalculateMemorySize(int channels, int frames) {
261   return CalculateMemorySizeInternal(channels, frames, NULL);
262 }
263 
BuildChannelData(int channels,int aligned_frames,float * data)264 void AudioBus::BuildChannelData(int channels, int aligned_frames, float* data) {
265   DCHECK(!is_bitstream_format_);
266   DCHECK(IsAligned(data));
267   DCHECK_EQ(channel_data_.size(), 0U);
268   // Initialize |channel_data_| with pointers into |data|.
269   channel_data_.reserve(channels);
270   for (int i = 0; i < channels; ++i)
271     channel_data_.push_back(data + i * aligned_frames);
272 }
273 
274 // Forwards to non-deprecated version.
FromInterleaved(const void * source,int frames,int bytes_per_sample)275 void AudioBus::FromInterleaved(const void* source,
276                                int frames,
277                                int bytes_per_sample) {
278   DCHECK(!is_bitstream_format_);
279   switch (bytes_per_sample) {
280     case 1:
281       FromInterleaved<UnsignedInt8SampleTypeTraits>(
282           reinterpret_cast<const uint8_t*>(source), frames);
283       break;
284     case 2:
285       FromInterleaved<SignedInt16SampleTypeTraits>(
286           reinterpret_cast<const int16_t*>(source), frames);
287       break;
288     case 4:
289       FromInterleaved<SignedInt32SampleTypeTraits>(
290           reinterpret_cast<const int32_t*>(source), frames);
291       break;
292     default:
293       NOTREACHED() << "Unsupported bytes per sample encountered: "
294                    << bytes_per_sample;
295       ZeroFrames(frames);
296   }
297 }
298 
299 // Forwards to non-deprecated version.
FromInterleavedPartial(const void * source,int start_frame,int frames,int bytes_per_sample)300 void AudioBus::FromInterleavedPartial(const void* source,
301                                       int start_frame,
302                                       int frames,
303                                       int bytes_per_sample) {
304   DCHECK(!is_bitstream_format_);
305   switch (bytes_per_sample) {
306     case 1:
307       FromInterleavedPartial<UnsignedInt8SampleTypeTraits>(
308           reinterpret_cast<const uint8_t*>(source), start_frame, frames);
309       break;
310     case 2:
311       FromInterleavedPartial<SignedInt16SampleTypeTraits>(
312           reinterpret_cast<const int16_t*>(source), start_frame, frames);
313       break;
314     case 4:
315       FromInterleavedPartial<SignedInt32SampleTypeTraits>(
316           reinterpret_cast<const int32_t*>(source), start_frame, frames);
317       break;
318     default:
319       NOTREACHED() << "Unsupported bytes per sample encountered: "
320                    << bytes_per_sample;
321       ZeroFramesPartial(start_frame, frames);
322   }
323 }
324 
325 // Forwards to non-deprecated version.
ToInterleaved(int frames,int bytes_per_sample,void * dest) const326 void AudioBus::ToInterleaved(int frames,
327                              int bytes_per_sample,
328                              void* dest) const {
329   DCHECK(!is_bitstream_format_);
330   switch (bytes_per_sample) {
331     case 1:
332       ToInterleaved<UnsignedInt8SampleTypeTraits>(
333           frames, reinterpret_cast<uint8_t*>(dest));
334       break;
335     case 2:
336       ToInterleaved<SignedInt16SampleTypeTraits>(
337           frames, reinterpret_cast<int16_t*>(dest));
338       break;
339     case 4:
340       ToInterleaved<SignedInt32SampleTypeTraits>(
341           frames, reinterpret_cast<int32_t*>(dest));
342       break;
343     default:
344       NOTREACHED() << "Unsupported bytes per sample encountered: "
345                    << bytes_per_sample;
346   }
347 }
348 
CopyTo(AudioBus * dest) const349 void AudioBus::CopyTo(AudioBus* dest) const {
350   dest->set_is_bitstream_format(is_bitstream_format());
351   if (is_bitstream_format()) {
352     dest->SetBitstreamDataSize(GetBitstreamDataSize());
353     dest->SetBitstreamFrames(GetBitstreamFrames());
354     memcpy(dest->channel(0), channel(0), GetBitstreamDataSize());
355     return;
356   }
357 
358   CopyPartialFramesTo(0, frames(), 0, dest);
359 }
360 
CopyAndClipTo(AudioBus * dest) const361 void AudioBus::CopyAndClipTo(AudioBus* dest) const {
362   DCHECK(!is_bitstream_format_);
363   CHECK_EQ(channels(), dest->channels());
364   CHECK_LE(frames(), dest->frames());
365   for (int i = 0; i < channels(); ++i) {
366     float* dest_ptr = dest->channel(i);
367     const float* source_ptr = channel(i);
368     for (int j = 0; j < frames(); ++j)
369       dest_ptr[j] = Float32SampleTypeTraits::FromFloat(source_ptr[j]);
370   }
371 }
372 
CopyPartialFramesTo(int source_start_frame,int frame_count,int dest_start_frame,AudioBus * dest) const373 void AudioBus::CopyPartialFramesTo(int source_start_frame,
374                                    int frame_count,
375                                    int dest_start_frame,
376                                    AudioBus* dest) const {
377   DCHECK(!is_bitstream_format_);
378   CHECK_EQ(channels(), dest->channels());
379   CHECK_LE(source_start_frame + frame_count, frames());
380   CHECK_LE(dest_start_frame + frame_count, dest->frames());
381 
382   // Since we don't know if the other AudioBus is wrapped or not (and we don't
383   // want to care), just copy using the public channel() accessors.
384   for (int i = 0; i < channels(); ++i) {
385     memcpy(dest->channel(i) + dest_start_frame,
386            channel(i) + source_start_frame,
387            sizeof(*channel(i)) * frame_count);
388   }
389 }
390 
Scale(float volume)391 void AudioBus::Scale(float volume) {
392   DCHECK(!is_bitstream_format_);
393   if (volume > 0 && volume != 1) {
394     for (int i = 0; i < channels(); ++i)
395       vector_math::FMUL(channel(i), volume, frames(), channel(i));
396   } else if (volume == 0) {
397     Zero();
398   }
399 }
400 
SwapChannels(int a,int b)401 void AudioBus::SwapChannels(int a, int b) {
402   DCHECK(!is_bitstream_format_);
403   DCHECK(a < channels() && a >= 0);
404   DCHECK(b < channels() && b >= 0);
405   DCHECK_NE(a, b);
406   std::swap(channel_data_[a], channel_data_[b]);
407 }
408 
409 }  // namespace media
410