diff --git a/media/BUILD.gn b/media/BUILD.gn index 4079d1bad9..0481e3f0fe 100644 --- a/media/BUILD.gn +++ b/media/BUILD.gn @@ -159,7 +159,6 @@ rtc_library("rtc_simulcast_encoder_adapter") { "../common_video", "../modules/video_coding:video_codec_interface", "../modules/video_coding:video_coding_utility", - "../rtc_base:atomicops", "../rtc_base:checks", "../rtc_base:logging", "../rtc_base/experiments:encoder_info_settings", diff --git a/media/engine/simulcast_encoder_adapter.cc b/media/engine/simulcast_encoder_adapter.cc index e1dfc94609..4a53b8027c 100644 --- a/media/engine/simulcast_encoder_adapter.cc +++ b/media/engine/simulcast_encoder_adapter.cc @@ -30,7 +30,6 @@ #include "media/base/video_common.h" #include "modules/video_coding/include/video_error_codes.h" #include "modules/video_coding/utility/simulcast_rate_allocator.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/experiments/rate_control_settings.h" #include "rtc_base/logging.h" @@ -294,7 +293,7 @@ int SimulcastEncoderAdapter::Release() { // It's legal to move the encoder to another queue now. encoder_queue_.Detach(); - rtc::AtomicOps::ReleaseStore(&inited_, 0); + inited_.store(0); return WEBRTC_VIDEO_CODEC_OK; } @@ -368,7 +367,7 @@ int SimulcastEncoderAdapter::InitEncode( bypass_mode_ = true; DestroyStoredEncoders(); - rtc::AtomicOps::ReleaseStore(&inited_, 1); + inited_.store(1); return WEBRTC_VIDEO_CODEC_OK; } @@ -424,7 +423,7 @@ int SimulcastEncoderAdapter::InitEncode( // To save memory, don't store encoders that we don't use. DestroyStoredEncoders(); - rtc::AtomicOps::ReleaseStore(&inited_, 1); + inited_.store(1); return WEBRTC_VIDEO_CODEC_OK; } @@ -678,7 +677,7 @@ void SimulcastEncoderAdapter::OnDroppedFrame(size_t stream_idx) { } bool SimulcastEncoderAdapter::Initialized() const { - return rtc::AtomicOps::AcquireLoad(&inited_) == 1; + return inited_.load() == 1; } void SimulcastEncoderAdapter::DestroyStoredEncoders() { diff --git a/media/engine/simulcast_encoder_adapter.h b/media/engine/simulcast_encoder_adapter.h index e6b6badbe5..ef8205e91a 100644 --- a/media/engine/simulcast_encoder_adapter.h +++ b/media/engine/simulcast_encoder_adapter.h @@ -12,6 +12,7 @@ #ifndef MEDIA_ENGINE_SIMULCAST_ENCODER_ADAPTER_H_ #define MEDIA_ENGINE_SIMULCAST_ENCODER_ADAPTER_H_ +#include #include #include #include @@ -27,7 +28,6 @@ #include "api/video_codecs/video_encoder_factory.h" #include "common_video/framerate_controller.h" #include "modules/video_coding/include/video_codec_interface.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/experiments/encoder_info_settings.h" #include "rtc_base/system/no_unique_address.h" #include "rtc_base/system/rtc_export.h" @@ -167,7 +167,7 @@ class RTC_EXPORT SimulcastEncoderAdapter : public VideoEncoder { void OverrideFromFieldTrial(VideoEncoder::EncoderInfo* info) const; - volatile int inited_; // Accessed atomically. + std::atomic inited_; VideoEncoderFactory* const primary_encoder_factory_; VideoEncoderFactory* const fallback_encoder_factory_; const SdpVideoFormat video_format_; diff --git a/modules/audio_processing/BUILD.gn b/modules/audio_processing/BUILD.gn index 0bd43312e9..b1f7331b5e 100644 --- a/modules/audio_processing/BUILD.gn +++ b/modules/audio_processing/BUILD.gn @@ -128,7 +128,6 @@ rtc_library("gain_controller2") { ":audio_buffer", ":audio_frame_view", "../../common_audio", - "../../rtc_base:atomicops", "../../rtc_base:checks", "../../rtc_base:logging", "../../rtc_base:stringutils", @@ -177,7 +176,6 @@ rtc_library("audio_processing") { "../../audio/utility:audio_frame_operations", "../../common_audio:common_audio_c", "../../common_audio/third_party/ooura:fft_size_256", - "../../rtc_base:atomicops", "../../rtc_base:checks", "../../rtc_base:event_tracer", "../../rtc_base:gtest_prod", @@ -244,7 +242,6 @@ rtc_library("residual_echo_detector") { ":api", ":apm_logging", "../../api:array_view", - "../../rtc_base:atomicops", "../../rtc_base:checks", "../../rtc_base:logging", "../../system_wrappers:metrics", @@ -488,7 +485,6 @@ if (rtc_include_tests) { ":audio_processing", ":audioproc_test_utils", "../../api:array_view", - "../../rtc_base:atomicops", "../../rtc_base:platform_thread", "../../rtc_base:protobuf_utils", "../../rtc_base:random", diff --git a/modules/audio_processing/aec3/BUILD.gn b/modules/audio_processing/aec3/BUILD.gn index 6e9e7a3379..70d049549a 100644 --- a/modules/audio_processing/aec3/BUILD.gn +++ b/modules/audio_processing/aec3/BUILD.gn @@ -144,7 +144,6 @@ rtc_library("aec3") { "../../../api/audio:aec3_config", "../../../api/audio:echo_control", "../../../common_audio:common_audio_c", - "../../../rtc_base:atomicops", "../../../rtc_base:checks", "../../../rtc_base:logging", "../../../rtc_base:macromagic", diff --git a/modules/audio_processing/aec3/aec_state.cc b/modules/audio_processing/aec3/aec_state.cc index 92cf3e2f2c..81fd91fab9 100644 --- a/modules/audio_processing/aec3/aec_state.cc +++ b/modules/audio_processing/aec3/aec_state.cc @@ -20,7 +20,6 @@ #include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "system_wrappers/include/field_trial.h" @@ -97,7 +96,7 @@ void ComputeAvgRenderReverb( } // namespace -int AecState::instance_count_ = 0; +std::atomic AecState::instance_count_(0); void AecState::GetResidualEchoScaling( rtc::ArrayView residual_scaling) const { @@ -115,8 +114,7 @@ void AecState::GetResidualEchoScaling( AecState::AecState(const EchoCanceller3Config& config, size_t num_capture_channels) - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), config_(config), num_capture_channels_(num_capture_channels), deactivate_initial_state_reset_at_echo_path_change_( diff --git a/modules/audio_processing/aec3/aec_state.h b/modules/audio_processing/aec3/aec_state.h index dbd0fccb67..a39325c8b8 100644 --- a/modules/audio_processing/aec3/aec_state.h +++ b/modules/audio_processing/aec3/aec_state.h @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -154,7 +155,7 @@ class AecState { } private: - static int instance_count_; + static std::atomic instance_count_; std::unique_ptr data_dumper_; const EchoCanceller3Config config_; const size_t num_capture_channels_; diff --git a/modules/audio_processing/aec3/block_processor.cc b/modules/audio_processing/aec3/block_processor.cc index 4525cc9d66..11b8aa62ee 100644 --- a/modules/audio_processing/aec3/block_processor.cc +++ b/modules/audio_processing/aec3/block_processor.cc @@ -11,6 +11,7 @@ #include +#include #include #include #include @@ -26,7 +27,6 @@ #include "modules/audio_processing/aec3/render_delay_buffer.h" #include "modules/audio_processing/aec3/render_delay_controller.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -64,7 +64,7 @@ class BlockProcessorImpl final : public BlockProcessor { void SetCaptureOutputUsage(bool capture_output_used) override; private: - static int instance_count_; + static std::atomic instance_count_; std::unique_ptr data_dumper_; const EchoCanceller3Config config_; bool capture_properly_started_ = false; @@ -79,7 +79,7 @@ class BlockProcessorImpl final : public BlockProcessor { absl::optional estimated_delay_; }; -int BlockProcessorImpl::instance_count_ = 0; +std::atomic BlockProcessorImpl::instance_count_(0); BlockProcessorImpl::BlockProcessorImpl( const EchoCanceller3Config& config, @@ -89,8 +89,7 @@ BlockProcessorImpl::BlockProcessorImpl( std::unique_ptr render_buffer, std::unique_ptr delay_controller, std::unique_ptr echo_remover) - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), config_(config), sample_rate_hz_(sample_rate_hz), render_buffer_(std::move(render_buffer)), diff --git a/modules/audio_processing/aec3/echo_canceller3.cc b/modules/audio_processing/aec3/echo_canceller3.cc index f4e3541071..8e306aca56 100644 --- a/modules/audio_processing/aec3/echo_canceller3.cc +++ b/modules/audio_processing/aec3/echo_canceller3.cc @@ -15,7 +15,6 @@ #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/high_pass_filter.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/experiments/field_trial_parser.h" #include "rtc_base/logging.h" #include "system_wrappers/include/field_trial.h" @@ -707,7 +706,7 @@ void EchoCanceller3::RenderWriter::Insert(const AudioBuffer& input) { static_cast(render_transfer_queue_->Insert(&render_queue_input_frame_)); } -int EchoCanceller3::instance_count_ = 0; +std::atomic EchoCanceller3::instance_count_(0); EchoCanceller3::EchoCanceller3( const EchoCanceller3Config& config, @@ -715,8 +714,7 @@ EchoCanceller3::EchoCanceller3( int sample_rate_hz, size_t num_render_channels, size_t num_capture_channels) - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), config_(AdjustConfig(config)), sample_rate_hz_(sample_rate_hz), num_bands_(NumBandsForRate(sample_rate_hz_)), diff --git a/modules/audio_processing/aec3/echo_canceller3.h b/modules/audio_processing/aec3/echo_canceller3.h index 179659a032..7bf8e51a4b 100644 --- a/modules/audio_processing/aec3/echo_canceller3.h +++ b/modules/audio_processing/aec3/echo_canceller3.h @@ -13,6 +13,7 @@ #include +#include #include #include @@ -185,7 +186,7 @@ class EchoCanceller3 : public EchoControl { RTC_GUARDED_BY(render_race_checker_); // State that may be accessed by the capture thread. - static int instance_count_; + static std::atomic instance_count_; std::unique_ptr data_dumper_; const EchoCanceller3Config config_; const int sample_rate_hz_; diff --git a/modules/audio_processing/aec3/echo_remover.cc b/modules/audio_processing/aec3/echo_remover.cc index 3bca86c7de..673d88af03 100644 --- a/modules/audio_processing/aec3/echo_remover.cc +++ b/modules/audio_processing/aec3/echo_remover.cc @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -33,7 +34,6 @@ #include "modules/audio_processing/aec3/suppression_filter.h" #include "modules/audio_processing/aec3/suppression_gain.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -142,7 +142,7 @@ class EchoRemoverImpl final : public EchoRemover { void FormLinearFilterOutput(const SubtractorOutput& subtractor_output, rtc::ArrayView output); - static int instance_count_; + static std::atomic instance_count_; const EchoCanceller3Config config_; const Aec3Fft fft_; std::unique_ptr data_dumper_; @@ -180,7 +180,7 @@ class EchoRemoverImpl final : public EchoRemover { std::vector subtractor_output_heap_; }; -int EchoRemoverImpl::instance_count_ = 0; +std::atomic EchoRemoverImpl::instance_count_(0); EchoRemoverImpl::EchoRemoverImpl(const EchoCanceller3Config& config, int sample_rate_hz, @@ -188,8 +188,7 @@ EchoRemoverImpl::EchoRemoverImpl(const EchoCanceller3Config& config, size_t num_capture_channels) : config_(config), fft_(), - data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), optimization_(DetectOptimization()), sample_rate_hz_(sample_rate_hz), num_render_channels_(num_render_channels), diff --git a/modules/audio_processing/aec3/filter_analyzer.cc b/modules/audio_processing/aec3/filter_analyzer.cc index c809a34d62..d8fd3aa275 100644 --- a/modules/audio_processing/aec3/filter_analyzer.cc +++ b/modules/audio_processing/aec3/filter_analyzer.cc @@ -19,7 +19,6 @@ #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" namespace webrtc { @@ -45,12 +44,11 @@ size_t FindPeakIndex(rtc::ArrayView filter_time_domain, } // namespace -int FilterAnalyzer::instance_count_ = 0; +std::atomic FilterAnalyzer::instance_count_(0); FilterAnalyzer::FilterAnalyzer(const EchoCanceller3Config& config, size_t num_capture_channels) - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), bounded_erl_(config.ep_strength.bounded_erl), default_gain_(config.ep_strength.default_gain), h_highpass_(num_capture_channels, diff --git a/modules/audio_processing/aec3/filter_analyzer.h b/modules/audio_processing/aec3/filter_analyzer.h index 7c6b5409e8..9aec8b14d7 100644 --- a/modules/audio_processing/aec3/filter_analyzer.h +++ b/modules/audio_processing/aec3/filter_analyzer.h @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -129,7 +130,7 @@ class FilterAnalyzer { ConsistentFilterDetector consistent_filter_detector; }; - static int instance_count_; + static std::atomic instance_count_; std::unique_ptr data_dumper_; const bool bounded_erl_; const float default_gain_; diff --git a/modules/audio_processing/aec3/refined_filter_update_gain.cc b/modules/audio_processing/aec3/refined_filter_update_gain.cc index db5203d542..8e391d6fa6 100644 --- a/modules/audio_processing/aec3/refined_filter_update_gain.cc +++ b/modules/audio_processing/aec3/refined_filter_update_gain.cc @@ -20,7 +20,6 @@ #include "modules/audio_processing/aec3/render_signal_analyzer.h" #include "modules/audio_processing/aec3/subtractor_output.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" namespace webrtc { @@ -31,13 +30,12 @@ constexpr int kPoorExcitationCounterInitial = 1000; } // namespace -int RefinedFilterUpdateGain::instance_count_ = 0; +std::atomic RefinedFilterUpdateGain::instance_count_(0); RefinedFilterUpdateGain::RefinedFilterUpdateGain( const EchoCanceller3Config::Filter::RefinedConfiguration& config, size_t config_change_duration_blocks) - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), config_change_duration_blocks_( static_cast(config_change_duration_blocks)), poor_excitation_counter_(kPoorExcitationCounterInitial) { diff --git a/modules/audio_processing/aec3/refined_filter_update_gain.h b/modules/audio_processing/aec3/refined_filter_update_gain.h index ae4fe84df5..1a68ebc296 100644 --- a/modules/audio_processing/aec3/refined_filter_update_gain.h +++ b/modules/audio_processing/aec3/refined_filter_update_gain.h @@ -14,6 +14,7 @@ #include #include +#include #include #include "api/array_view.h" @@ -69,7 +70,7 @@ class RefinedFilterUpdateGain { } private: - static int instance_count_; + static std::atomic instance_count_; std::unique_ptr data_dumper_; const int config_change_duration_blocks_; float one_by_config_change_duration_blocks_; diff --git a/modules/audio_processing/aec3/render_delay_buffer.cc b/modules/audio_processing/aec3/render_delay_buffer.cc index a46c378a1c..05791216a5 100644 --- a/modules/audio_processing/aec3/render_delay_buffer.cc +++ b/modules/audio_processing/aec3/render_delay_buffer.cc @@ -32,7 +32,6 @@ #include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/aec3/spectrum_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "system_wrappers/include/field_trial.h" @@ -74,7 +73,7 @@ class RenderDelayBufferImpl final : public RenderDelayBuffer { bool HasReceivedBufferDelay() override; private: - static int instance_count_; + static std::atomic instance_count_; std::unique_ptr data_dumper_; const Aec3Optimization optimization_; const EchoCanceller3Config config_; @@ -119,13 +118,12 @@ class RenderDelayBufferImpl final : public RenderDelayBuffer { bool RenderUnderrun(); }; -int RenderDelayBufferImpl::instance_count_ = 0; +std::atomic RenderDelayBufferImpl::instance_count_ = 0; RenderDelayBufferImpl::RenderDelayBufferImpl(const EchoCanceller3Config& config, int sample_rate_hz, size_t num_render_channels) - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), optimization_(DetectOptimization()), config_(config), update_capture_call_counter_on_skipped_blocks_( diff --git a/modules/audio_processing/aec3/render_delay_controller.cc b/modules/audio_processing/aec3/render_delay_controller.cc index 8860404665..aa3d440c33 100644 --- a/modules/audio_processing/aec3/render_delay_controller.cc +++ b/modules/audio_processing/aec3/render_delay_controller.cc @@ -23,7 +23,6 @@ #include "modules/audio_processing/aec3/echo_path_delay_estimator.h" #include "modules/audio_processing/aec3/render_delay_controller_metrics.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" namespace webrtc { @@ -51,7 +50,7 @@ class RenderDelayControllerImpl final : public RenderDelayController { bool HasClockdrift() const override; private: - static int instance_count_; + static std::atomic instance_count_; std::unique_ptr data_dumper_; const int hysteresis_limit_blocks_; const int delay_headroom_samples_; @@ -90,14 +89,13 @@ DelayEstimate ComputeBufferDelay( return new_delay; } -int RenderDelayControllerImpl::instance_count_ = 0; +std::atomic RenderDelayControllerImpl::instance_count_(0); RenderDelayControllerImpl::RenderDelayControllerImpl( const EchoCanceller3Config& config, int sample_rate_hz, size_t num_capture_channels) - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), hysteresis_limit_blocks_( static_cast(config.delay.hysteresis_limit_blocks)), delay_headroom_samples_(config.delay.delay_headroom_samples), diff --git a/modules/audio_processing/aec3/stationarity_estimator.cc b/modules/audio_processing/aec3/stationarity_estimator.cc index 01628f3e8a..4d364041b3 100644 --- a/modules/audio_processing/aec3/stationarity_estimator.cc +++ b/modules/audio_processing/aec3/stationarity_estimator.cc @@ -17,7 +17,6 @@ #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/spectrum_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" namespace webrtc { @@ -29,8 +28,7 @@ constexpr int kNBlocksInitialPhase = kNumBlocksPerSecond * 2.; } // namespace StationarityEstimator::StationarityEstimator() - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))) { + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)) { Reset(); } @@ -153,7 +151,7 @@ void StationarityEstimator::SmoothStationaryPerFreq() { stationarity_flags_ = all_ahead_stationary_smooth; } -int StationarityEstimator::instance_count_ = 0; +std::atomic StationarityEstimator::instance_count_(0); StationarityEstimator::NoiseSpectrum::NoiseSpectrum() { Reset(); diff --git a/modules/audio_processing/aec3/stationarity_estimator.h b/modules/audio_processing/aec3/stationarity_estimator.h index 6f7ad4060f..8bcd3b789e 100644 --- a/modules/audio_processing/aec3/stationarity_estimator.h +++ b/modules/audio_processing/aec3/stationarity_estimator.h @@ -14,6 +14,7 @@ #include #include +#include #include #include "api/array_view.h" @@ -110,7 +111,7 @@ class StationarityEstimator { size_t block_counter_; }; - static int instance_count_; + static std::atomic instance_count_; std::unique_ptr data_dumper_; NoiseSpectrum noise_; std::array hangovers_; diff --git a/modules/audio_processing/aec3/suppression_gain.cc b/modules/audio_processing/aec3/suppression_gain.cc index 0017ca0a7e..037dabaabe 100644 --- a/modules/audio_processing/aec3/suppression_gain.cc +++ b/modules/audio_processing/aec3/suppression_gain.cc @@ -21,7 +21,6 @@ #include "modules/audio_processing/aec3/subband_nearend_detector.h" #include "modules/audio_processing/aec3/vector_math.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "system_wrappers/include/field_trial.h" @@ -102,7 +101,7 @@ void WeightEchoForAudibility(const EchoCanceller3Config& config, } // namespace -int SuppressionGain::instance_count_ = 0; +std::atomic SuppressionGain::instance_count_(0); float SuppressionGain::UpperBandsGain( rtc::ArrayView> echo_spectrum, @@ -326,8 +325,7 @@ SuppressionGain::SuppressionGain(const EchoCanceller3Config& config, Aec3Optimization optimization, int sample_rate_hz, size_t num_capture_channels) - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), optimization_(optimization), config_(config), num_capture_channels_(num_capture_channels), diff --git a/modules/audio_processing/aec3/suppression_gain.h b/modules/audio_processing/aec3/suppression_gain.h index e63c045c2d..c19ddd7e30 100644 --- a/modules/audio_processing/aec3/suppression_gain.h +++ b/modules/audio_processing/aec3/suppression_gain.h @@ -12,6 +12,7 @@ #define MODULES_AUDIO_PROCESSING_AEC3_SUPPRESSION_GAIN_H_ #include +#include #include #include @@ -118,7 +119,7 @@ class SuppressionGain { std::array emr_transparent_; }; - static int instance_count_; + static std::atomic instance_count_; std::unique_ptr data_dumper_; const Aec3Optimization optimization_; const EchoCanceller3Config config_; diff --git a/modules/audio_processing/agc/BUILD.gn b/modules/audio_processing/agc/BUILD.gn index 7b8f0fd82e..ade35af06a 100644 --- a/modules/audio_processing/agc/BUILD.gn +++ b/modules/audio_processing/agc/BUILD.gn @@ -30,7 +30,6 @@ rtc_library("agc") { "../../../api:array_view", "../../../common_audio", "../../../common_audio:common_audio_c", - "../../../rtc_base:atomicops", "../../../rtc_base:checks", "../../../rtc_base:gtest_prod", "../../../rtc_base:logging", diff --git a/modules/audio_processing/agc/agc_manager_direct.cc b/modules/audio_processing/agc/agc_manager_direct.cc index fb54cf52f6..af25c61179 100644 --- a/modules/audio_processing/agc/agc_manager_direct.cc +++ b/modules/audio_processing/agc/agc_manager_direct.cc @@ -18,7 +18,6 @@ #include "modules/audio_processing/agc/gain_control.h" #include "modules/audio_processing/agc/gain_map_internal.h" #include "modules/audio_processing/include/audio_frame_view.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_minmax.h" @@ -439,7 +438,7 @@ void MonoAgc::UpdateCompressor() { } } -int AgcManagerDirect::instance_counter_ = 0; +std::atomic AgcManagerDirect::instance_counter_(0); AgcManagerDirect::AgcManagerDirect( Agc* agc, @@ -472,8 +471,7 @@ AgcManagerDirect::AgcManagerDirect( int clipped_wait_frames, const ClippingPredictorConfig& clipping_config) : min_mic_level_override_(GetMinMicLevelOverride()), - data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_counter_))), + data_dumper_(new ApmDataDumper(instance_counter_.fetch_add(1) + 1)), use_min_channel_level_(!UseMaxAnalogChannelLevel()), num_capture_channels_(num_capture_channels), disable_digital_adaptive_(disable_digital_adaptive), diff --git a/modules/audio_processing/agc/agc_manager_direct.h b/modules/audio_processing/agc/agc_manager_direct.h index ce67a971b4..86abeecb91 100644 --- a/modules/audio_processing/agc/agc_manager_direct.h +++ b/modules/audio_processing/agc/agc_manager_direct.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC_AGC_MANAGER_DIRECT_H_ #define MODULES_AUDIO_PROCESSING_AGC_AGC_MANAGER_DIRECT_H_ +#include #include #include "absl/types/optional.h" @@ -128,7 +129,7 @@ class AgcManagerDirect final { const absl::optional min_mic_level_override_; std::unique_ptr data_dumper_; - static int instance_counter_; + static std::atomic instance_counter_; const bool use_min_channel_level_; const int num_capture_channels_; const bool disable_digital_adaptive_; diff --git a/modules/audio_processing/audio_processing_impl.cc b/modules/audio_processing/audio_processing_impl.cc index 31a6a14d6a..b7d23409da 100644 --- a/modules/audio_processing/audio_processing_impl.cc +++ b/modules/audio_processing/audio_processing_impl.cc @@ -28,7 +28,6 @@ #include "modules/audio_processing/include/audio_frame_view.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "modules/audio_processing/optionally_built_submodule_creators.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/time_utils.h" @@ -253,7 +252,7 @@ AudioProcessingImpl::AudioProcessingImpl() /*echo_detector=*/nullptr, /*capture_analyzer=*/nullptr) {} -int AudioProcessingImpl::instance_count_ = 0; +std::atomic AudioProcessingImpl::instance_count_(0); AudioProcessingImpl::AudioProcessingImpl( const AudioProcessing::Config& config, @@ -262,8 +261,7 @@ AudioProcessingImpl::AudioProcessingImpl( std::unique_ptr echo_control_factory, rtc::scoped_refptr echo_detector, std::unique_ptr capture_analyzer) - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), use_setup_specific_default_aec3_config_( UseSetupSpecificDefaultAec3Congfig()), use_denormal_disabler_( diff --git a/modules/audio_processing/audio_processing_impl.h b/modules/audio_processing/audio_processing_impl.h index 974089ba8b..86ecb807a9 100644 --- a/modules/audio_processing/audio_processing_impl.h +++ b/modules/audio_processing/audio_processing_impl.h @@ -13,6 +13,7 @@ #include +#include #include #include #include @@ -180,7 +181,7 @@ class AudioProcessingImpl : public AudioProcessing { }; const std::unique_ptr data_dumper_; - static int instance_count_; + static std::atomic instance_count_; const bool use_setup_specific_default_aec3_config_; const bool use_denormal_disabler_; diff --git a/modules/audio_processing/audio_processing_performance_unittest.cc b/modules/audio_processing/audio_processing_performance_unittest.cc index 57655aea6d..49e435f6f8 100644 --- a/modules/audio_processing/audio_processing_performance_unittest.cc +++ b/modules/audio_processing/audio_processing_performance_unittest.cc @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -17,7 +18,6 @@ #include "modules/audio_processing/audio_processing_impl.h" #include "modules/audio_processing/test/audio_processing_builder_for_testing.h" #include "modules/audio_processing/test/test_utils.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/event.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/platform_thread.h" @@ -134,16 +134,16 @@ struct SimulationConfig { // Handler for the frame counters. class FrameCounters { public: - void IncreaseRenderCounter() { rtc::AtomicOps::Increment(&render_count_); } + void IncreaseRenderCounter() { render_count_.fetch_add(1); } - void IncreaseCaptureCounter() { rtc::AtomicOps::Increment(&capture_count_); } + void IncreaseCaptureCounter() { capture_count_.fetch_add(1); } int CaptureMinusRenderCounters() const { // The return value will be approximate, but that's good enough since // by the time we return the value, it's not guaranteed to be correct // anyway. - return rtc::AtomicOps::AcquireLoad(&capture_count_) - - rtc::AtomicOps::AcquireLoad(&render_count_); + return capture_count_.load(std::memory_order_acquire) - + render_count_.load(std::memory_order_acquire); } int RenderMinusCaptureCounters() const { @@ -153,28 +153,31 @@ class FrameCounters { bool BothCountersExceedeThreshold(int threshold) const { // TODO(tommi): We could use an event to signal this so that we don't need // to be polling from the main thread and possibly steal cycles. - const int capture_count = rtc::AtomicOps::AcquireLoad(&capture_count_); - const int render_count = rtc::AtomicOps::AcquireLoad(&render_count_); + const int capture_count = capture_count_.load(std::memory_order_acquire); + const int render_count = render_count_.load(std::memory_order_acquire); return (render_count > threshold && capture_count > threshold); } private: - int render_count_ = 0; - int capture_count_ = 0; + std::atomic render_count_{0}; + std::atomic capture_count_{0}; }; // Class that represents a flag that can only be raised. class LockedFlag { public: - bool get_flag() const { return rtc::AtomicOps::AcquireLoad(&flag_); } + bool get_flag() const { return flag_.load(std::memory_order_acquire); } void set_flag() { - if (!get_flag()) // read-only operation to avoid affecting the cache-line. - rtc::AtomicOps::CompareAndSwap(&flag_, 0, 1); + if (!get_flag()) { + // read-only operation to avoid affecting the cache-line. + int zero = 0; + flag_.compare_exchange_strong(zero, 1); + } } private: - int flag_ = 0; + std::atomic flag_{0}; }; // Parent class for the thread processors. diff --git a/modules/audio_processing/gain_controller2.cc b/modules/audio_processing/gain_controller2.cc index 83a595e439..f1907bbd92 100644 --- a/modules/audio_processing/gain_controller2.cc +++ b/modules/audio_processing/gain_controller2.cc @@ -18,7 +18,6 @@ #include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/include/audio_frame_view.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/strings/string_builder.h" @@ -65,14 +64,14 @@ std::unique_ptr CreateAdaptiveDigitalController( } // namespace -int GainController2::instance_count_ = 0; +std::atomic GainController2::instance_count_(0); GainController2::GainController2(const Agc2Config& config, int sample_rate_hz, int num_channels, bool use_internal_vad) : cpu_features_(GetAllowedCpuFeatures()), - data_dumper_(rtc::AtomicOps::Increment(&instance_count_)), + data_dumper_(instance_count_.fetch_add(1) + 1), fixed_gain_applier_( /*hard_clip_samples=*/false, /*initial_gain_factor=*/DbToRatio(config.fixed_digital.gain_db)), diff --git a/modules/audio_processing/gain_controller2.h b/modules/audio_processing/gain_controller2.h index 616f88ae24..304fa40489 100644 --- a/modules/audio_processing/gain_controller2.h +++ b/modules/audio_processing/gain_controller2.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_GAIN_CONTROLLER2_H_ #define MODULES_AUDIO_PROCESSING_GAIN_CONTROLLER2_H_ +#include #include #include @@ -60,7 +61,7 @@ class GainController2 { AvailableCpuFeatures GetCpuFeatures() const { return cpu_features_; } private: - static int instance_count_; + static std::atomic instance_count_; const AvailableCpuFeatures cpu_features_; ApmDataDumper data_dumper_; GainApplier fixed_gain_applier_; diff --git a/modules/audio_processing/residual_echo_detector.cc b/modules/audio_processing/residual_echo_detector.cc index fe1149a896..2a564fc233 100644 --- a/modules/audio_processing/residual_echo_detector.cc +++ b/modules/audio_processing/residual_echo_detector.cc @@ -15,7 +15,6 @@ #include "absl/types/optional.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "system_wrappers/include/metrics.h" @@ -41,11 +40,10 @@ constexpr size_t kAggregationBufferSize = 10 * 100; namespace webrtc { -int ResidualEchoDetector::instance_count_ = 0; +std::atomic ResidualEchoDetector::instance_count_(0); ResidualEchoDetector::ResidualEchoDetector() - : data_dumper_( - new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), + : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)), render_buffer_(kRenderBufferSize), render_power_(kLookbackFrames), render_power_mean_(kLookbackFrames), diff --git a/modules/audio_processing/residual_echo_detector.h b/modules/audio_processing/residual_echo_detector.h index 44252af655..ac554b17c4 100644 --- a/modules/audio_processing/residual_echo_detector.h +++ b/modules/audio_processing/residual_echo_detector.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_RESIDUAL_ECHO_DETECTOR_H_ #define MODULES_AUDIO_PROCESSING_RESIDUAL_ECHO_DETECTOR_H_ +#include #include #include "api/array_view.h" @@ -49,7 +50,7 @@ class ResidualEchoDetector : public EchoDetector { EchoDetector::Metrics GetMetrics() const override; private: - static int instance_count_; + static std::atomic instance_count_; std::unique_ptr data_dumper_; // Keep track if the `Process` function has been previously called. bool first_process_call_ = true; diff --git a/rtc_base/BUILD.gn b/rtc_base/BUILD.gn index b58b4a94ac..c8e23a8e7f 100644 --- a/rtc_base/BUILD.gn +++ b/rtc_base/BUILD.gn @@ -194,7 +194,6 @@ rtc_library("event_tracer") { "trace_event.h", ] deps = [ - ":atomicops", ":checks", ":logging", ":macromagic", @@ -346,7 +345,6 @@ rtc_library("criticalsection") { "deprecated/recursive_critical_section.h", ] deps = [ - ":atomicops", ":checks", ":macromagic", ":platform_thread_types", @@ -361,7 +359,6 @@ rtc_library("platform_thread") { "platform_thread.h", ] deps = [ - ":atomicops", ":checks", ":macromagic", ":platform_thread_types", @@ -453,10 +450,6 @@ rtc_library("logging") { } } -rtc_source_set("atomicops") { - sources = [ "atomic_ops.h" ] -} - rtc_library("checks") { # TODO(bugs.webrtc.org/9607): This should not be public. visibility = [ "*" ] @@ -922,7 +915,6 @@ rtc_library("threading") { ] deps = [ ":async_resolver_interface", - ":atomicops", ":byte_order", ":checks", ":criticalsection", @@ -1497,7 +1489,6 @@ if (rtc_include_tests) { rtc_library("rtc_base_approved_unittests") { testonly = true sources = [ - "atomic_ops_unittest.cc", "base64_unittest.cc", "bit_buffer_unittest.cc", "bitstream_reader_unittest.cc", @@ -1541,7 +1532,6 @@ if (rtc_include_tests) { "zero_memory_unittest.cc", ] deps = [ - ":atomicops", ":bit_buffer", ":bitstream_reader", ":bounded_inline_vector", @@ -1710,7 +1700,6 @@ if (rtc_include_tests) { "unique_id_generator_unittest.cc", ] deps = [ - ":atomicops", ":buffer", ":buffer_queue", ":checks", diff --git a/rtc_base/atomic_ops.h b/rtc_base/atomic_ops.h deleted file mode 100644 index 18a24a8e2e..0000000000 --- a/rtc_base/atomic_ops.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2011 The WebRTC Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef RTC_BASE_ATOMIC_OPS_H_ -#define RTC_BASE_ATOMIC_OPS_H_ - -#if defined(WEBRTC_WIN) -// clang-format off -// clang formating would change include order. - -// Include winsock2.h before including to maintain consistency with -// win32.h. To include win32.h directly, it must be broken out into its own -// build target. -#include -#include -// clang-format on -#endif // defined(WEBRTC_WIN) - -namespace rtc { -class AtomicOps { - public: -#if defined(WEBRTC_WIN) - // Assumes sizeof(int) == sizeof(LONG), which it is on Win32 and Win64. - static int Increment(volatile int* i) { - return ::InterlockedIncrement(reinterpret_cast(i)); - } - static int Decrement(volatile int* i) { - return ::InterlockedDecrement(reinterpret_cast(i)); - } - static int AcquireLoad(volatile const int* i) { return *i; } - static void ReleaseStore(volatile int* i, int value) { *i = value; } - static int CompareAndSwap(volatile int* i, int old_value, int new_value) { - return ::InterlockedCompareExchange(reinterpret_cast(i), - new_value, old_value); - } - // Pointer variants. - template - static T* AcquireLoadPtr(T* volatile* ptr) { - return *ptr; - } - template - static T* CompareAndSwapPtr(T* volatile* ptr, T* old_value, T* new_value) { - return static_cast(::InterlockedCompareExchangePointer( - reinterpret_cast(ptr), new_value, old_value)); - } -#else - static int Increment(volatile int* i) { return __sync_add_and_fetch(i, 1); } - static int Decrement(volatile int* i) { return __sync_sub_and_fetch(i, 1); } - static int AcquireLoad(volatile const int* i) { - return __atomic_load_n(i, __ATOMIC_ACQUIRE); - } - static void ReleaseStore(volatile int* i, int value) { - __atomic_store_n(i, value, __ATOMIC_RELEASE); - } - static int CompareAndSwap(volatile int* i, int old_value, int new_value) { - return __sync_val_compare_and_swap(i, old_value, new_value); - } - // Pointer variants. - template - static T* AcquireLoadPtr(T* volatile* ptr) { - return __atomic_load_n(ptr, __ATOMIC_ACQUIRE); - } - template - static T* CompareAndSwapPtr(T* volatile* ptr, T* old_value, T* new_value) { - return __sync_val_compare_and_swap(ptr, old_value, new_value); - } -#endif -}; - -} // namespace rtc - -#endif // RTC_BASE_ATOMIC_OPS_H_ diff --git a/rtc_base/atomic_ops_unittest.cc b/rtc_base/atomic_ops_unittest.cc deleted file mode 100644 index d5a1105f81..0000000000 --- a/rtc_base/atomic_ops_unittest.cc +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright 2011 The WebRTC Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -// TODO(pbos): Move AtomicOps tests to here from -// webrtc/rtc_base/criticalsection_unittest.cc. diff --git a/rtc_base/deprecated/recursive_critical_section.cc b/rtc_base/deprecated/recursive_critical_section.cc index 068b9aa808..540819888e 100644 --- a/rtc_base/deprecated/recursive_critical_section.cc +++ b/rtc_base/deprecated/recursive_critical_section.cc @@ -12,7 +12,6 @@ #include -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/platform_thread_types.h" #include "rtc_base/synchronization/yield.h" diff --git a/rtc_base/deprecated/recursive_critical_section.h b/rtc_base/deprecated/recursive_critical_section.h index cc308e45b7..da1e92b9b0 100644 --- a/rtc_base/deprecated/recursive_critical_section.h +++ b/rtc_base/deprecated/recursive_critical_section.h @@ -11,6 +11,8 @@ #ifndef RTC_BASE_DEPRECATED_RECURSIVE_CRITICAL_SECTION_H_ #define RTC_BASE_DEPRECATED_RECURSIVE_CRITICAL_SECTION_H_ +#include + #include "rtc_base/platform_thread_types.h" #include "rtc_base/thread_annotations.h" @@ -68,7 +70,7 @@ class RTC_LOCKABLE RecursiveCriticalSection { // Number of times the lock has been locked + number of threads waiting. // TODO(tommi): We could use this number and subtract the recursion count // to find places where we have multiple threads contending on the same lock. - mutable volatile int lock_queue_; + mutable std::atomic lock_queue_; // `recursion_` represents the recursion count + 1 for the thread that owns // the lock. Only modified by the thread that owns the lock. mutable int recursion_; diff --git a/rtc_base/deprecated/recursive_critical_section_unittest.cc b/rtc_base/deprecated/recursive_critical_section_unittest.cc index 9256a76f58..571867aeb9 100644 --- a/rtc_base/deprecated/recursive_critical_section_unittest.cc +++ b/rtc_base/deprecated/recursive_critical_section_unittest.cc @@ -21,7 +21,6 @@ #include "absl/base/attributes.h" #include "rtc_base/arraysize.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/event.h" #include "rtc_base/location.h" @@ -94,7 +93,7 @@ class RunnerBase : public MessageHandlerAutoCleanup { return done_event_.Wait(kLongTime); } - void SetExpectedThreadCount(int count) { threads_active_ = count; } + void SetExpectedThreadCount(int count) { threads_active_.store(count); } int shared_value() const { return shared_value_; } @@ -105,14 +104,14 @@ class RunnerBase : public MessageHandlerAutoCleanup { // Returns true if all threads have finished. bool AfterEnd() { - if (AtomicOps::Decrement(&threads_active_) == 0) { + if (threads_active_.fetch_sub(1) == 1) { done_event_.Set(); return true; } return false; } - int threads_active_; + std::atomic threads_active_; Event start_event_; Event done_event_; int shared_value_; @@ -156,49 +155,6 @@ class LockRunner : public RunnerBase { Lock lock_; }; -template -class AtomicOpRunner : public RunnerBase { - public: - explicit AtomicOpRunner(int initial_value) : RunnerBase(initial_value) {} - - void OnMessage(Message* msg) override { - BeforeStart(); - - std::vector values; - values.reserve(kOperationsToRun); - - // Generate a bunch of values by updating shared_value_ atomically. - for (int i = 0; i < kOperationsToRun; ++i) { - values.push_back(Op::AtomicOp(&shared_value_)); - } - - { // Add them all to the set. - CritScope cs(&all_values_crit_); - verifier_.Verify(values); - } - - if (AfterEnd()) { - verifier_.Finalize(); - } - } - - private: - RecursiveCriticalSection all_values_crit_; - Verifier verifier_; -}; - -struct IncrementOp { - static int AtomicOp(int* i) { return AtomicOps::Increment(i); } -}; - -struct DecrementOp { - static int AtomicOp(int* i) { return AtomicOps::Decrement(i); } -}; - -struct CompareAndSwapOp { - static int AtomicOp(int* i) { return AtomicOps::CompareAndSwap(i, 0, 1); } -}; - void StartThreads(std::vector>* threads, MessageHandler* handler) { for (int i = 0; i < kNumThreads; ++i) { @@ -211,77 +167,6 @@ void StartThreads(std::vector>* threads, } // namespace -TEST(AtomicOpsTest, Simple) { - int value = 0; - EXPECT_EQ(1, AtomicOps::Increment(&value)); - EXPECT_EQ(1, value); - EXPECT_EQ(2, AtomicOps::Increment(&value)); - EXPECT_EQ(2, value); - EXPECT_EQ(1, AtomicOps::Decrement(&value)); - EXPECT_EQ(1, value); - EXPECT_EQ(0, AtomicOps::Decrement(&value)); - EXPECT_EQ(0, value); -} - -TEST(AtomicOpsTest, SimplePtr) { - class Foo {}; - Foo* volatile foo = nullptr; - std::unique_ptr a(new Foo()); - std::unique_ptr b(new Foo()); - // Reading the initial value should work as expected. - EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == nullptr); - // Setting using compare and swap should work. - EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr( - &foo, static_cast(nullptr), a.get()) == nullptr); - EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get()); - // Setting another value but with the wrong previous pointer should fail - // (remain a). - EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr( - &foo, static_cast(nullptr), b.get()) == a.get()); - EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get()); - // Replacing a with b should work. - EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(&foo, a.get(), b.get()) == - a.get()); - EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == b.get()); -} - -TEST(AtomicOpsTest, Increment) { - // Create and start lots of threads. - AtomicOpRunner runner(0); - std::vector> threads; - StartThreads(&threads, &runner); - runner.SetExpectedThreadCount(kNumThreads); - - // Release the hounds! - EXPECT_TRUE(runner.Run()); - EXPECT_EQ(kOperationsToRun * kNumThreads, runner.shared_value()); -} - -TEST(AtomicOpsTest, Decrement) { - // Create and start lots of threads. - AtomicOpRunner runner(kOperationsToRun * - kNumThreads); - std::vector> threads; - StartThreads(&threads, &runner); - runner.SetExpectedThreadCount(kNumThreads); - - // Release the hounds! - EXPECT_TRUE(runner.Run()); - EXPECT_EQ(0, runner.shared_value()); -} - -TEST(AtomicOpsTest, CompareAndSwap) { - // Create and start lots of threads. - AtomicOpRunner runner(0); - std::vector> threads; - StartThreads(&threads, &runner); - runner.SetExpectedThreadCount(kNumThreads); - - // Release the hounds! - EXPECT_TRUE(runner.Run()); - EXPECT_EQ(1, runner.shared_value()); -} - TEST(RecursiveCriticalSectionTest, Basic) { // Create and start lots of threads. LockRunner runner; diff --git a/rtc_base/event_tracer.cc b/rtc_base/event_tracer.cc index e6acbdca8f..28f1bfef69 100644 --- a/rtc_base/event_tracer.cc +++ b/rtc_base/event_tracer.cc @@ -14,12 +14,12 @@ #include #include +#include #include #include #include "absl/strings/string_view.h" #include "api/sequence_checker.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/event.h" #include "rtc_base/logging.h" @@ -81,7 +81,7 @@ namespace tracing { namespace { // Atomic-int fast path for avoiding logging when disabled. -static volatile int g_event_logging_active = 0; +static std::atomic g_event_logging_active(0); // TODO(pbos): Log metadata for all threads, etc. class EventLogger final { @@ -199,8 +199,8 @@ class EventLogger final { } // Enable event logging (fast-path). This should be disabled since starting // shouldn't be done twice. - RTC_CHECK_EQ(0, - rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 0, 1)); + int zero = 0; + RTC_CHECK(g_event_logging_active.compare_exchange_strong(zero, 1)); // Finally start, everything should be set up now. logging_thread_ = @@ -212,7 +212,8 @@ class EventLogger final { RTC_DCHECK(thread_checker_.IsCurrent()); TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Stop"); // Try to stop. Abort if we're not currently logging. - if (rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 1, 0) == 0) + int one = 1; + if (g_event_logging_active.compare_exchange_strong(one, 0)) return; // Wake up logging thread to finish writing. @@ -321,7 +322,7 @@ class EventLogger final { bool output_file_owned_ = false; }; -static EventLogger* volatile g_event_logger = nullptr; +static std::atomic g_event_logger(nullptr); static const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT(""); const unsigned char* InternalGetCategoryEnabled(const char* name) { const char* prefix_ptr = &kDisabledTracePrefix[0]; @@ -349,33 +350,35 @@ void InternalAddTraceEvent(char phase, const unsigned long long* arg_values, unsigned char flags) { // Fast path for when event tracing is inactive. - if (rtc::AtomicOps::AcquireLoad(&g_event_logging_active) == 0) + if (g_event_logging_active.load() == 0) return; - g_event_logger->AddTraceEvent(name, category_enabled, phase, num_args, - arg_names, arg_types, arg_values, - rtc::TimeMicros(), 1, rtc::CurrentThreadId()); + g_event_logger.load()->AddTraceEvent( + name, category_enabled, phase, num_args, arg_names, arg_types, arg_values, + rtc::TimeMicros(), 1, rtc::CurrentThreadId()); } } // namespace void SetupInternalTracer(bool enable_all_categories) { - RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr( - &g_event_logger, static_cast(nullptr), - new EventLogger()) == nullptr); + EventLogger* null_logger = nullptr; + RTC_CHECK( + g_event_logger.compare_exchange_strong(null_logger, new EventLogger())); webrtc::SetupEventTracer(enable_all_categories ? InternalEnableAllCategories : InternalGetCategoryEnabled, InternalAddTraceEvent); } void StartInternalCaptureToFile(FILE* file) { - if (g_event_logger) { - g_event_logger->Start(file, false); + EventLogger* event_logger = g_event_logger.load(); + if (event_logger) { + event_logger->Start(file, false); } } bool StartInternalCapture(absl::string_view filename) { - if (!g_event_logger) + EventLogger* event_logger = g_event_logger.load(); + if (!event_logger) return false; FILE* file = fopen(std::string(filename).c_str(), "w"); @@ -384,23 +387,22 @@ bool StartInternalCapture(absl::string_view filename) { << "' for writing."; return false; } - g_event_logger->Start(file, true); + event_logger->Start(file, true); return true; } void StopInternalCapture() { - if (g_event_logger) { - g_event_logger->Stop(); + EventLogger* event_logger = g_event_logger.load(); + if (event_logger) { + event_logger->Stop(); } } void ShutdownInternalTracer() { StopInternalCapture(); - EventLogger* old_logger = rtc::AtomicOps::AcquireLoadPtr(&g_event_logger); + EventLogger* old_logger = g_event_logger.load(std::memory_order_acquire); RTC_DCHECK(old_logger); - RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr( - &g_event_logger, old_logger, - static_cast(nullptr)) == old_logger); + RTC_CHECK(g_event_logger.compare_exchange_strong(old_logger, nullptr)); delete old_logger; webrtc::SetupEventTracer(nullptr, nullptr); } diff --git a/rtc_base/thread.cc b/rtc_base/thread.cc index 6693979259..e1db2bc24f 100644 --- a/rtc_base/thread.cc +++ b/rtc_base/thread.cc @@ -33,7 +33,6 @@ #include "absl/algorithm/container.h" #include "api/sequence_checker.h" #include "api/task_queue/to_queued_task.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/deprecated/recursive_critical_section.h" #include "rtc_base/event.h" @@ -212,19 +211,19 @@ void ThreadManager::ProcessAllMessageQueuesInternal() { // This works by posting a delayed message at the current time and waiting // for it to be dispatched on all queues, which will ensure that all messages // that came before it were also dispatched. - volatile int queues_not_done = 0; + std::atomic queues_not_done(0); // This class is used so that whether the posted message is processed, or the // message queue is simply cleared, queues_not_done gets decremented. class ScopedIncrement : public MessageData { public: - ScopedIncrement(volatile int* value) : value_(value) { - AtomicOps::Increment(value_); + ScopedIncrement(std::atomic* value) : value_(value) { + value_->fetch_add(1); } - ~ScopedIncrement() override { AtomicOps::Decrement(value_); } + ~ScopedIncrement() override { value_->fetch_sub(1); } private: - volatile int* value_; + std::atomic* value_; }; { @@ -245,7 +244,7 @@ void ThreadManager::ProcessAllMessageQueuesInternal() { // Note: One of the message queues may have been on this thread, which is // why we can't synchronously wait for queues_not_done to go to 0; we need // to process messages as well. - while (AtomicOps::AcquireLoad(&queues_not_done) > 0) { + while (queues_not_done.load() > 0) { if (current) { current->ProcessMessages(0); } @@ -436,16 +435,16 @@ void Thread::WakeUpSocketServer() { } void Thread::Quit() { - AtomicOps::ReleaseStore(&stop_, 1); + stop_.store(1, std::memory_order_release); WakeUpSocketServer(); } bool Thread::IsQuitting() { - return AtomicOps::AcquireLoad(&stop_) != 0; + return stop_.load(std::memory_order_acquire) != 0; } void Thread::Restart() { - AtomicOps::ReleaseStore(&stop_, 0); + stop_.store(0, std::memory_order_release); } bool Thread::Peek(Message* pmsg, int cmsWait) { diff --git a/rtc_base/thread.h b/rtc_base/thread.h index 885d7b8350..33646843dd 100644 --- a/rtc_base/thread.h +++ b/rtc_base/thread.h @@ -628,7 +628,7 @@ class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase { bool fInitialized_; bool fDestroyed_; - volatile int stop_; + std::atomic stop_; // The SocketServer might not be owned by Thread. SocketServer* const ss_; diff --git a/rtc_base/thread_unittest.cc b/rtc_base/thread_unittest.cc index 5490e6171e..321cbc3a22 100644 --- a/rtc_base/thread_unittest.cc +++ b/rtc_base/thread_unittest.cc @@ -17,7 +17,6 @@ #include "api/task_queue/to_queued_task.h" #include "rtc_base/async_invoker.h" #include "rtc_base/async_udp_socket.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/event.h" #include "rtc_base/gunit.h" @@ -658,7 +657,7 @@ TEST(ThreadManager, ProcessAllMessageQueues) { a->Start(); b->Start(); - volatile int messages_processed = 0; + std::atomic messages_processed(0); auto incrementer = [&messages_processed, &entered_process_all_message_queues] { // Wait for event as a means to ensure Increment doesn't occur outside @@ -666,7 +665,7 @@ TEST(ThreadManager, ProcessAllMessageQueues) { // the main thread, which is guaranteed to be handled inside // ProcessAllMessageQueues. entered_process_all_message_queues.Wait(Event::kForever); - AtomicOps::Increment(&messages_processed); + messages_processed.fetch_add(1); }; auto event_signaler = [&entered_process_all_message_queues] { entered_process_all_message_queues.Set(); @@ -680,7 +679,7 @@ TEST(ThreadManager, ProcessAllMessageQueues) { main_thread.PostTask(ToQueuedTask(event_signaler)); ThreadManager::ProcessAllMessageQueuesForTesting(); - EXPECT_EQ(4, AtomicOps::AcquireLoad(&messages_processed)); + EXPECT_EQ(4, messages_processed.load(std::memory_order_acquire)); } // Test that ProcessAllMessageQueues doesn't hang if a thread is quitting. diff --git a/sdk/BUILD.gn b/sdk/BUILD.gn index 649320a568..db266b88d1 100644 --- a/sdk/BUILD.gn +++ b/sdk/BUILD.gn @@ -277,7 +277,6 @@ if (is_ios || is_mac) { "../modules/audio_device:audio_device_buffer", "../modules/audio_device:audio_device_generic", "../rtc_base", - "../rtc_base:atomicops", "../rtc_base:buffer", "../rtc_base:checks", "../rtc_base:logging", @@ -348,7 +347,6 @@ if (is_ios || is_mac) { ":base_objc", ":helpers_objc", "../rtc_base", - "../rtc_base:atomicops", "../rtc_base:checks", "../rtc_base/synchronization:mutex", ] diff --git a/sdk/android/BUILD.gn b/sdk/android/BUILD.gn index 8bed067379..8611707808 100644 --- a/sdk/android/BUILD.gn +++ b/sdk/android/BUILD.gn @@ -951,7 +951,6 @@ if (current_os == "linux" || is_android) { ":generated_native_api_jni", ":internal_jni", "../../api:sequence_checker", - "../../rtc_base:atomicops", "//api:array_view", "//rtc_base:checks", ] diff --git a/sdk/android/src/jni/jni_generator_helper.cc b/sdk/android/src/jni/jni_generator_helper.cc index 8ddcdff4f6..dc34849d1b 100644 --- a/sdk/android/src/jni/jni_generator_helper.cc +++ b/sdk/android/src/jni/jni_generator_helper.cc @@ -10,7 +10,6 @@ #include "sdk/android/src/jni/jni_generator_helper.h" -#include "rtc_base/atomic_ops.h" #include "sdk/android/native_api/jni/class_loader.h" namespace webrtc { diff --git a/sdk/objc/components/audio/RTCAudioSession.mm b/sdk/objc/components/audio/RTCAudioSession.mm index 0d0db5aa5b..550a426d36 100644 --- a/sdk/objc/components/audio/RTCAudioSession.mm +++ b/sdk/objc/components/audio/RTCAudioSession.mm @@ -12,10 +12,10 @@ #import +#include #include #include "absl/base/attributes.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/synchronization/mutex.h" @@ -48,8 +48,8 @@ ABSL_CONST_INIT thread_local bool mutex_locked = false; @implementation RTC_OBJC_TYPE (RTCAudioSession) { webrtc::Mutex _mutex; AVAudioSession *_session; - volatile int _activationCount; - volatile int _webRTCSessionCount; + std::atomic _activationCount; + std::atomic _webRTCSessionCount; BOOL _isActive; BOOL _useManualAudio; BOOL _isAudioEnabled; @@ -351,7 +351,7 @@ ABSL_CONST_INIT thread_local bool mutex_locked = false; if (![self checkLock:outError]) { return NO; } - int activationCount = _activationCount; + int activationCount = _activationCount.load(); if (!active && activationCount == 0) { RTCLogWarning(@"Attempting to deactivate without prior activation."); } @@ -403,7 +403,7 @@ ABSL_CONST_INIT thread_local bool mutex_locked = false; [self notifyDidSetActive:active]; [self decrementActivationCount]; } - RTCLog(@"Number of current activations: %d", _activationCount); + RTCLog(@"Number of current activations: %d", _activationCount.load()); return success; } @@ -643,21 +643,21 @@ ABSL_CONST_INIT thread_local bool mutex_locked = false; } - (int)activationCount { - return _activationCount; + return _activationCount.load(); } - (int)incrementActivationCount { RTCLog(@"Incrementing activation count."); - return rtc::AtomicOps::Increment(&_activationCount); + return _activationCount.fetch_add(1) + 1; } - (NSInteger)decrementActivationCount { RTCLog(@"Decrementing activation count."); - return rtc::AtomicOps::Decrement(&_activationCount); + return _activationCount.fetch_sub(1) - 1; } - (int)webRTCSessionCount { - return _webRTCSessionCount; + return _webRTCSessionCount.load(); } - (BOOL)canPlayOrRecord { @@ -693,7 +693,7 @@ ABSL_CONST_INIT thread_local bool mutex_locked = false; if (outError) { *outError = nil; } - rtc::AtomicOps::Increment(&_webRTCSessionCount); + _webRTCSessionCount.fetch_add(1); [self notifyDidStartPlayOrRecord]; return YES; } @@ -702,7 +702,7 @@ ABSL_CONST_INIT thread_local bool mutex_locked = false; if (outError) { *outError = nil; } - rtc::AtomicOps::Decrement(&_webRTCSessionCount); + _webRTCSessionCount.fetch_sub(1); [self notifyDidStopPlayOrRecord]; return YES; } diff --git a/sdk/objc/native/src/audio/audio_device_ios.h b/sdk/objc/native/src/audio/audio_device_ios.h index 69fd8a953c..dc9f462063 100644 --- a/sdk/objc/native/src/audio/audio_device_ios.h +++ b/sdk/objc/native/src/audio/audio_device_ios.h @@ -11,6 +11,7 @@ #ifndef SDK_OBJC_NATIVE_SRC_AUDIO_AUDIO_DEVICE_IOS_H_ #define SDK_OBJC_NATIVE_SRC_AUDIO_AUDIO_DEVICE_IOS_H_ +#include #include #include "api/sequence_checker.h" @@ -266,10 +267,10 @@ class AudioDeviceIOS : public AudioDeviceGeneric, rtc::BufferT record_audio_buffer_; // Set to 1 when recording is active and 0 otherwise. - volatile int recording_; + std::atomic recording_; // Set to 1 when playout is active and 0 otherwise. - volatile int playing_; + std::atomic playing_; // Set to true after successful call to Init(), false otherwise. bool initialized_ RTC_GUARDED_BY(thread_checker_); diff --git a/sdk/objc/native/src/audio/audio_device_ios.mm b/sdk/objc/native/src/audio/audio_device_ios.mm index a416b92b31..f3f87c04b6 100644 --- a/sdk/objc/native/src/audio/audio_device_ios.mm +++ b/sdk/objc/native/src/audio/audio_device_ios.mm @@ -18,7 +18,6 @@ #include "api/array_view.h" #include "helpers.h" #include "modules/audio_device/fine_audio_buffer.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/thread.h" @@ -188,7 +187,7 @@ int32_t AudioDeviceIOS::InitPlayout() { RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK(initialized_); RTC_DCHECK(!audio_is_initialized_); - RTC_DCHECK(!playing_); + RTC_DCHECK(!playing_.load()); if (!audio_is_initialized_) { if (!InitPlayOrRecord()) { RTC_LOG_F(LS_ERROR) << "InitPlayOrRecord failed for InitPlayout!"; @@ -214,7 +213,7 @@ int32_t AudioDeviceIOS::InitRecording() { RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK(initialized_); RTC_DCHECK(!audio_is_initialized_); - RTC_DCHECK(!recording_); + RTC_DCHECK(!recording_.load()); if (!audio_is_initialized_) { if (!InitPlayOrRecord()) { RTC_LOG_F(LS_ERROR) << "InitPlayOrRecord failed for InitRecording!"; @@ -229,12 +228,12 @@ int32_t AudioDeviceIOS::StartPlayout() { LOGI() << "StartPlayout"; RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK(audio_is_initialized_); - RTC_DCHECK(!playing_); + RTC_DCHECK(!playing_.load()); RTC_DCHECK(audio_unit_); if (fine_audio_buffer_) { fine_audio_buffer_->ResetPlayout(); } - if (!recording_ && audio_unit_->GetState() == VoiceProcessingAudioUnit::kInitialized) { + if (!recording_.load() && audio_unit_->GetState() == VoiceProcessingAudioUnit::kInitialized) { OSStatus result = audio_unit_->Start(); if (result != noErr) { RTC_OBJC_TYPE(RTCAudioSession)* session = [RTC_OBJC_TYPE(RTCAudioSession) sharedInstance]; @@ -244,7 +243,7 @@ int32_t AudioDeviceIOS::StartPlayout() { } RTC_LOG(LS_INFO) << "Voice-Processing I/O audio unit is now started"; } - rtc::AtomicOps::ReleaseStore(&playing_, 1); + playing_.store(1, std::memory_order_release); num_playout_callbacks_ = 0; num_detected_playout_glitches_ = 0; return 0; @@ -253,14 +252,14 @@ int32_t AudioDeviceIOS::StartPlayout() { int32_t AudioDeviceIOS::StopPlayout() { LOGI() << "StopPlayout"; RTC_DCHECK_RUN_ON(&thread_checker_); - if (!audio_is_initialized_ || !playing_) { + if (!audio_is_initialized_ || !playing_.load()) { return 0; } - if (!recording_) { + if (!recording_.load()) { ShutdownPlayOrRecord(); audio_is_initialized_ = false; } - rtc::AtomicOps::ReleaseStore(&playing_, 0); + playing_.store(0, std::memory_order_release); // Derive average number of calls to OnGetPlayoutData() between detected // audio glitches and add the result to a histogram. @@ -278,19 +277,19 @@ int32_t AudioDeviceIOS::StopPlayout() { } bool AudioDeviceIOS::Playing() const { - return playing_; + return playing_.load(); } int32_t AudioDeviceIOS::StartRecording() { LOGI() << "StartRecording"; RTC_DCHECK_RUN_ON(&thread_checker_); RTC_DCHECK(audio_is_initialized_); - RTC_DCHECK(!recording_); + RTC_DCHECK(!recording_.load()); RTC_DCHECK(audio_unit_); if (fine_audio_buffer_) { fine_audio_buffer_->ResetRecord(); } - if (!playing_ && audio_unit_->GetState() == VoiceProcessingAudioUnit::kInitialized) { + if (!playing_.load() && audio_unit_->GetState() == VoiceProcessingAudioUnit::kInitialized) { OSStatus result = audio_unit_->Start(); if (result != noErr) { RTC_OBJC_TYPE(RTCAudioSession)* session = [RTC_OBJC_TYPE(RTCAudioSession) sharedInstance]; @@ -300,26 +299,26 @@ int32_t AudioDeviceIOS::StartRecording() { } RTC_LOG(LS_INFO) << "Voice-Processing I/O audio unit is now started"; } - rtc::AtomicOps::ReleaseStore(&recording_, 1); + recording_.store(1, std::memory_order_release); return 0; } int32_t AudioDeviceIOS::StopRecording() { LOGI() << "StopRecording"; RTC_DCHECK_RUN_ON(&thread_checker_); - if (!audio_is_initialized_ || !recording_) { + if (!audio_is_initialized_ || !recording_.load()) { return 0; } - if (!playing_) { + if (!playing_.load()) { ShutdownPlayOrRecord(); audio_is_initialized_ = false; } - rtc::AtomicOps::ReleaseStore(&recording_, 0); + recording_.store(0, std::memory_order_release); return 0; } bool AudioDeviceIOS::Recording() const { - return recording_; + return recording_.load(); } int32_t AudioDeviceIOS::PlayoutDelay(uint16_t& delayMS) const { @@ -381,7 +380,7 @@ OSStatus AudioDeviceIOS::OnDeliverRecordedData(AudioUnitRenderActionFlags* flags RTC_DCHECK_RUN_ON(&io_thread_checker_); OSStatus result = noErr; // Simply return if recording is not enabled. - if (!rtc::AtomicOps::AcquireLoad(&recording_)) return result; + if (!recording_.load(std::memory_order_acquire)) return result; // Set the size of our own audio buffer and clear it first to avoid copying // in combination with potential reallocations. @@ -434,7 +433,7 @@ OSStatus AudioDeviceIOS::OnGetPlayoutData(AudioUnitRenderActionFlags* flags, // Produce silence and give audio unit a hint about it if playout is not // activated. - if (!rtc::AtomicOps::AcquireLoad(&playing_)) { + if (!playing_.load(std::memory_order_acquire)) { const size_t size_in_bytes = audio_buffer->mDataByteSize; RTC_CHECK_EQ(size_in_bytes / VoiceProcessingAudioUnit::kBytesPerSample, num_frames); *flags |= kAudioUnitRenderAction_OutputIsSilence; @@ -783,16 +782,17 @@ void AudioDeviceIOS::UpdateAudioUnit(bool can_play_or_record) { case VoiceProcessingAudioUnit::kUninitialized: RTCLog(@"VPAU state: Uninitialized"); should_initialize_audio_unit = can_play_or_record; - should_start_audio_unit = should_initialize_audio_unit && (playing_ || recording_); + should_start_audio_unit = + should_initialize_audio_unit && (playing_.load() || recording_.load()); break; case VoiceProcessingAudioUnit::kInitialized: RTCLog(@"VPAU state: Initialized"); - should_start_audio_unit = can_play_or_record && (playing_ || recording_); + should_start_audio_unit = can_play_or_record && (playing_.load() || recording_.load()); should_uninitialize_audio_unit = !can_play_or_record; break; case VoiceProcessingAudioUnit::kStarted: RTCLog(@"VPAU state: Started"); - RTC_DCHECK(playing_ || recording_); + RTC_DCHECK(playing_.load() || recording_.load()); should_stop_audio_unit = !can_play_or_record; should_uninitialize_audio_unit = should_stop_audio_unit; break; diff --git a/system_wrappers/BUILD.gn b/system_wrappers/BUILD.gn index 4e424d969a..c979a6aae6 100644 --- a/system_wrappers/BUILD.gn +++ b/system_wrappers/BUILD.gn @@ -102,7 +102,6 @@ rtc_library("metrics") { defines = [ "WEBRTC_EXCLUDE_METRICS_DEFAULT" ] } deps = [ - "../rtc_base:atomicops", "../rtc_base:checks", "../rtc_base:macromagic", "../rtc_base:stringutils", diff --git a/system_wrappers/include/metrics.h b/system_wrappers/include/metrics.h index 7bf7983aa3..ca9ed6d09b 100644 --- a/system_wrappers/include/metrics.h +++ b/system_wrappers/include/metrics.h @@ -13,12 +13,12 @@ #include +#include #include #include #include #include "absl/strings/string_view.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/string_utils.h" @@ -190,25 +190,22 @@ void NoOp(const Ts&...) {} webrtc::metrics::HistogramFactoryGetEnumeration(name, boundary)) // The name of the histogram should not vary. -#define RTC_HISTOGRAM_COMMON_BLOCK(constant_name, sample, \ - factory_get_invocation) \ - do { \ - static webrtc::metrics::Histogram* atomic_histogram_pointer = nullptr; \ - webrtc::metrics::Histogram* histogram_pointer = \ - rtc::AtomicOps::AcquireLoadPtr(&atomic_histogram_pointer); \ - if (!histogram_pointer) { \ - histogram_pointer = factory_get_invocation; \ - webrtc::metrics::Histogram* prev_pointer = \ - rtc::AtomicOps::CompareAndSwapPtr( \ - &atomic_histogram_pointer, \ - static_cast(nullptr), \ - histogram_pointer); \ - RTC_DCHECK(prev_pointer == nullptr || \ - prev_pointer == histogram_pointer); \ - } \ - if (histogram_pointer) { \ - webrtc::metrics::HistogramAdd(histogram_pointer, sample); \ - } \ +#define RTC_HISTOGRAM_COMMON_BLOCK(constant_name, sample, \ + factory_get_invocation) \ + do { \ + static std::atomic atomic_histogram_pointer( \ + nullptr); \ + webrtc::metrics::Histogram* histogram_pointer = \ + atomic_histogram_pointer.load(std::memory_order_acquire); \ + if (!histogram_pointer) { \ + histogram_pointer = factory_get_invocation; \ + webrtc::metrics::Histogram* null_histogram = nullptr; \ + atomic_histogram_pointer.compare_exchange_strong(null_histogram, \ + histogram_pointer); \ + } \ + if (histogram_pointer) { \ + webrtc::metrics::HistogramAdd(histogram_pointer, sample); \ + } \ } while (0) // The histogram is constructed/found for each call. diff --git a/system_wrappers/source/metrics.cc b/system_wrappers/source/metrics.cc index 0063405752..39ca590070 100644 --- a/system_wrappers/source/metrics.cc +++ b/system_wrappers/source/metrics.cc @@ -190,15 +190,13 @@ class RtcHistogramMap { // The histogram getter functions, which return pointer values to the histograms // in the map, are cached in WebRTC. Therefore, this memory is not freed by the // application (the memory will be reclaimed by the OS). -static RtcHistogramMap* volatile g_rtc_histogram_map = nullptr; +static std::atomic g_rtc_histogram_map(nullptr); void CreateMap() { - RtcHistogramMap* map = rtc::AtomicOps::AcquireLoadPtr(&g_rtc_histogram_map); + RtcHistogramMap* map = g_rtc_histogram_map.load(std::memory_order_acquire); if (map == nullptr) { RtcHistogramMap* new_map = new RtcHistogramMap(); - RtcHistogramMap* old_map = rtc::AtomicOps::CompareAndSwapPtr( - &g_rtc_histogram_map, static_cast(nullptr), new_map); - if (old_map != nullptr) + if (!g_rtc_histogram_map.compare_exchange_strong(map, new_map)) delete new_map; } } @@ -206,15 +204,15 @@ void CreateMap() { // Set the first time we start using histograms. Used to make sure Enable() is // not called thereafter. #if RTC_DCHECK_IS_ON -static volatile int g_rtc_histogram_called = 0; +static std::atomic g_rtc_histogram_called(0); #endif // Gets the map (or nullptr). RtcHistogramMap* GetMap() { #if RTC_DCHECK_IS_ON - rtc::AtomicOps::ReleaseStore(&g_rtc_histogram_called, 1); + g_rtc_histogram_called.store(1, std::memory_order_release); #endif - return g_rtc_histogram_map; + return g_rtc_histogram_map.load(); } } // namespace @@ -287,9 +285,9 @@ SampleInfo::~SampleInfo() {} // Implementation of global functions in metrics.h. void Enable() { - RTC_DCHECK(g_rtc_histogram_map == nullptr); + RTC_DCHECK(g_rtc_histogram_map.load() == nullptr); #if RTC_DCHECK_IS_ON - RTC_DCHECK_EQ(0, rtc::AtomicOps::AcquireLoad(&g_rtc_histogram_called)); + RTC_DCHECK_EQ(0, g_rtc_histogram_called.load(std::memory_order_acquire)); #endif CreateMap(); } diff --git a/video/BUILD.gn b/video/BUILD.gn index 2bf0454bd3..ac1652444a 100644 --- a/video/BUILD.gn +++ b/video/BUILD.gn @@ -112,7 +112,6 @@ rtc_library("video") { "../modules/video_coding/timing:inter_frame_delay", "../modules/video_coding/timing:timing_module", "../modules/video_processing", - "../rtc_base:atomicops", "../rtc_base:checks", "../rtc_base:event_tracer", "../rtc_base:histogram_percentile_counter", diff --git a/video/video_send_stream_impl.cc b/video/video_send_stream_impl.cc index 7e815288e4..83fa9e1574 100644 --- a/video/video_send_stream_impl.cc +++ b/video/video_send_stream_impl.cc @@ -26,7 +26,6 @@ #include "call/rtp_transport_controller_send_interface.h" #include "call/video_send_stream.h" #include "modules/pacing/pacing_controller.h" -#include "rtc_base/atomic_ops.h" #include "rtc_base/checks.h" #include "rtc_base/experiments/alr_experiment.h" #include "rtc_base/experiments/field_trial_parser.h"