audio_hash.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2013 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. #include "media/base/audio_hash.h"
  5. #include <cmath>
  6. #include <sstream>
  7. #include "base/numerics/math_constants.h"
  8. #include "base/strings/stringprintf.h"
  9. #include "media/base/audio_bus.h"
  10. namespace media {
  11. AudioHash::AudioHash()
  12. : audio_hash_(),
  13. sample_count_(0) {
  14. }
  15. AudioHash::~AudioHash() = default;
  16. void AudioHash::Update(const AudioBus* audio_bus, int frames) {
  17. // Use uint32_t to ensure overflow is a defined operation.
  18. for (uint32_t ch = 0; ch < static_cast<uint32_t>(audio_bus->channels());
  19. ++ch) {
  20. const float* channel = audio_bus->channel(ch);
  21. for (uint32_t i = 0; i < static_cast<uint32_t>(frames); ++i) {
  22. const uint32_t kSampleIndex = sample_count_ + i;
  23. const uint32_t kHashIndex =
  24. (kSampleIndex * (ch + 1)) % std::size(audio_hash_);
  25. // Mix in a sine wave with the result so we ensure that sequences of empty
  26. // buffers don't result in an empty hash.
  27. if (ch == 0) {
  28. audio_hash_[kHashIndex] +=
  29. channel[i] +
  30. std::sin(2.0 * base::kPiDouble * base::kPiDouble * kSampleIndex);
  31. } else {
  32. audio_hash_[kHashIndex] += channel[i];
  33. }
  34. }
  35. }
  36. sample_count_ += static_cast<uint32_t>(frames);
  37. }
  38. std::string AudioHash::ToString() const {
  39. std::string result;
  40. for (size_t i = 0; i < std::size(audio_hash_); ++i)
  41. result += base::StringPrintf("%.2f,", audio_hash_[i]);
  42. return result;
  43. }
  44. bool AudioHash::IsEquivalent(const std::string& other, double tolerance) const {
  45. float other_hash;
  46. char comma;
  47. std::stringstream is(other);
  48. for (size_t i = 0; i < std::size(audio_hash_); ++i) {
  49. is >> other_hash >> comma;
  50. if (std::fabs(audio_hash_[i] - other_hash) > tolerance)
  51. return false;
  52. }
  53. return true;
  54. }
  55. } // namespace media