audio_device_buffer.h 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /*
  2. * Copyright (c) 2012 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. #ifndef MODULES_AUDIO_DEVICE_AUDIO_DEVICE_BUFFER_H_
  11. #define MODULES_AUDIO_DEVICE_AUDIO_DEVICE_BUFFER_H_
  12. #include <stddef.h>
  13. #include <stdint.h>
  14. #include <atomic>
  15. #include "api/task_queue/task_queue_factory.h"
  16. #include "modules/audio_device/include/audio_device_defines.h"
  17. #include "rtc_base/buffer.h"
  18. #include "rtc_base/synchronization/mutex.h"
  19. #include "rtc_base/task_queue.h"
  20. #include "rtc_base/thread_annotations.h"
  21. #include "rtc_base/thread_checker.h"
  22. namespace webrtc {
  23. // Delta times between two successive playout callbacks are limited to this
  24. // value before added to an internal array.
  25. const size_t kMaxDeltaTimeInMs = 500;
  26. // TODO(henrika): remove when no longer used by external client.
  27. const size_t kMaxBufferSizeBytes = 3840; // 10ms in stereo @ 96kHz
  28. class AudioDeviceBuffer {
  29. public:
  30. enum LogState {
  31. LOG_START = 0,
  32. LOG_STOP,
  33. LOG_ACTIVE,
  34. };
  35. struct Stats {
  36. void ResetRecStats() {
  37. rec_callbacks = 0;
  38. rec_samples = 0;
  39. max_rec_level = 0;
  40. }
  41. void ResetPlayStats() {
  42. play_callbacks = 0;
  43. play_samples = 0;
  44. max_play_level = 0;
  45. }
  46. // Total number of recording callbacks where the source provides 10ms audio
  47. // data each time.
  48. uint64_t rec_callbacks = 0;
  49. // Total number of playback callbacks where the sink asks for 10ms audio
  50. // data each time.
  51. uint64_t play_callbacks = 0;
  52. // Total number of recorded audio samples.
  53. uint64_t rec_samples = 0;
  54. // Total number of played audio samples.
  55. uint64_t play_samples = 0;
  56. // Contains max level (max(abs(x))) of recorded audio packets over the last
  57. // 10 seconds where a new measurement is done twice per second. The level
  58. // is reset to zero at each call to LogStats().
  59. int16_t max_rec_level = 0;
  60. // Contains max level of recorded audio packets over the last 10 seconds
  61. // where a new measurement is done twice per second.
  62. int16_t max_play_level = 0;
  63. };
  64. explicit AudioDeviceBuffer(TaskQueueFactory* task_queue_factory);
  65. virtual ~AudioDeviceBuffer();
  66. int32_t RegisterAudioCallback(AudioTransport* audio_callback);
  67. void StartPlayout();
  68. void StartRecording();
  69. void StopPlayout();
  70. void StopRecording();
  71. int32_t SetRecordingSampleRate(uint32_t fsHz);
  72. int32_t SetPlayoutSampleRate(uint32_t fsHz);
  73. uint32_t RecordingSampleRate() const;
  74. uint32_t PlayoutSampleRate() const;
  75. int32_t SetRecordingChannels(size_t channels);
  76. int32_t SetPlayoutChannels(size_t channels);
  77. size_t RecordingChannels() const;
  78. size_t PlayoutChannels() const;
  79. virtual int32_t SetRecordedBuffer(const void* audio_buffer,
  80. size_t samples_per_channel);
  81. virtual void SetVQEData(int play_delay_ms, int rec_delay_ms);
  82. virtual int32_t DeliverRecordedData();
  83. uint32_t NewMicLevel() const;
  84. virtual int32_t RequestPlayoutData(size_t samples_per_channel);
  85. virtual int32_t GetPlayoutData(void* audio_buffer);
  86. int32_t SetTypingStatus(bool typing_status);
  87. private:
  88. // Starts/stops periodic logging of audio stats.
  89. void StartPeriodicLogging();
  90. void StopPeriodicLogging();
  91. // Called periodically on the internal thread created by the TaskQueue.
  92. // Updates some stats but dooes it on the task queue to ensure that access of
  93. // members is serialized hence avoiding usage of locks.
  94. // state = LOG_START => members are initialized and the timer starts.
  95. // state = LOG_STOP => no logs are printed and the timer stops.
  96. // state = LOG_ACTIVE => logs are printed and the timer is kept alive.
  97. void LogStats(LogState state);
  98. // Updates counters in each play/record callback. These counters are later
  99. // (periodically) read by LogStats() using a lock.
  100. void UpdateRecStats(int16_t max_abs, size_t samples_per_channel);
  101. void UpdatePlayStats(int16_t max_abs, size_t samples_per_channel);
  102. // Clears all members tracking stats for recording and playout.
  103. // These methods both run on the task queue.
  104. void ResetRecStats();
  105. void ResetPlayStats();
  106. // This object lives on the main (creating) thread and most methods are
  107. // called on that same thread. When audio has started some methods will be
  108. // called on either a native audio thread for playout or a native thread for
  109. // recording. Some members are not annotated since they are "protected by
  110. // design" and adding e.g. a race checker can cause failures for very few
  111. // edge cases and it is IMHO not worth the risk to use them in this class.
  112. // TODO(henrika): see if it is possible to refactor and annotate all members.
  113. // Main thread on which this object is created.
  114. rtc::ThreadChecker main_thread_checker_;
  115. Mutex lock_;
  116. // Task queue used to invoke LogStats() periodically. Tasks are executed on a
  117. // worker thread but it does not necessarily have to be the same thread for
  118. // each task.
  119. rtc::TaskQueue task_queue_;
  120. // Raw pointer to AudioTransport instance. Supplied to RegisterAudioCallback()
  121. // and it must outlive this object. It is not possible to change this member
  122. // while any media is active. It is possible to start media without calling
  123. // RegisterAudioCallback() but that will lead to ignored audio callbacks in
  124. // both directions where native audio will be active but no audio samples will
  125. // be transported.
  126. AudioTransport* audio_transport_cb_;
  127. // Sample rate in Hertz. Accessed atomically.
  128. std::atomic<uint32_t> rec_sample_rate_;
  129. std::atomic<uint32_t> play_sample_rate_;
  130. // Number of audio channels. Accessed atomically.
  131. std::atomic<size_t> rec_channels_;
  132. std::atomic<size_t> play_channels_;
  133. // Keeps track of if playout/recording are active or not. A combination
  134. // of these states are used to determine when to start and stop the timer.
  135. // Only used on the creating thread and not used to control any media flow.
  136. bool playing_ RTC_GUARDED_BY(main_thread_checker_);
  137. bool recording_ RTC_GUARDED_BY(main_thread_checker_);
  138. // Buffer used for audio samples to be played out. Size can be changed
  139. // dynamically. The 16-bit samples are interleaved, hence the size is
  140. // proportional to the number of channels.
  141. rtc::BufferT<int16_t> play_buffer_;
  142. // Byte buffer used for recorded audio samples. Size can be changed
  143. // dynamically.
  144. rtc::BufferT<int16_t> rec_buffer_;
  145. // Contains true of a key-press has been detected.
  146. bool typing_status_;
  147. // Delay values used by the AEC.
  148. int play_delay_ms_;
  149. int rec_delay_ms_;
  150. // Counts number of times LogStats() has been called.
  151. size_t num_stat_reports_ RTC_GUARDED_BY(task_queue_);
  152. // Time stamp of last timer task (drives logging).
  153. int64_t last_timer_task_time_ RTC_GUARDED_BY(task_queue_);
  154. // Counts number of audio callbacks modulo 50 to create a signal when
  155. // a new storage of audio stats shall be done.
  156. int16_t rec_stat_count_;
  157. int16_t play_stat_count_;
  158. // Time stamps of when playout and recording starts.
  159. int64_t play_start_time_ RTC_GUARDED_BY(main_thread_checker_);
  160. int64_t rec_start_time_ RTC_GUARDED_BY(main_thread_checker_);
  161. // Contains counters for playout and recording statistics.
  162. Stats stats_ RTC_GUARDED_BY(lock_);
  163. // Stores current stats at each timer task. Used to calculate differences
  164. // between two successive timer events.
  165. Stats last_stats_ RTC_GUARDED_BY(task_queue_);
  166. // Set to true at construction and modified to false as soon as one audio-
  167. // level estimate larger than zero is detected.
  168. bool only_silence_recorded_;
  169. // Set to true when logging of audio stats is enabled for the first time in
  170. // StartPeriodicLogging() and set to false by StopPeriodicLogging().
  171. // Setting this member to false prevents (possiby invalid) log messages from
  172. // being printed in the LogStats() task.
  173. bool log_stats_ RTC_GUARDED_BY(task_queue_);
  174. // Should *never* be defined in production builds. Only used for testing.
  175. // When defined, the output signal will be replaced by a sinus tone at 440Hz.
  176. #ifdef AUDIO_DEVICE_PLAYS_SINUS_TONE
  177. double phase_;
  178. #endif
  179. };
  180. } // namespace webrtc
  181. #endif // MODULES_AUDIO_DEVICE_AUDIO_DEVICE_BUFFER_H_