diff options
author | Jordan Bayles <jophba@chromium.org> | 2020-06-02 15:51:31 -0700 |
---|---|---|
committer | Commit Bot <commit-bot@chromium.org> | 2020-06-03 14:49:40 +0000 |
commit | c9201dd611b0aa8d66fe7ef2749c7ce0c157f0a1 (patch) | |
tree | 35865dd50de7765c9c82abb42c74a7d70a4b8178 | |
parent | 724a60fb10c7042a3e00eb4f1cf25b41b88b0c8b (diff) | |
download | openscreen-c9201dd611b0aa8d66fe7ef2749c7ce0c157f0a1.tar.gz |
Move std::chrono using statements to util/
This patch moves openscreen::<time type> using statements to be part of
a new util/ header, chrono_helpers.h. Some helpful convenience
functions are provided for doing conversions, and a new conversion
method, to_duration, is added to the Clock implementation.
Change-Id: I5a153c4da5266bceea97de0cad00a71a739f71ca
Reviewed-on: https://chromium-review.googlesource.com/c/openscreen/+/2222684
Reviewed-by: mark a. foltz <mfoltz@chromium.org>
Reviewed-by: Ryan Keane <rwkeane@google.com>
Commit-Queue: Jordan Bayles <jophba@chromium.org>
76 files changed, 328 insertions, 240 deletions
diff --git a/cast/common/certificate/cast_cert_validator_internal.cc b/cast/common/certificate/cast_cert_validator_internal.cc index 8284802e..569d22b1 100644 --- a/cast/common/certificate/cast_cert_validator_internal.cc +++ b/cast/common/certificate/cast_cert_validator_internal.cc @@ -10,6 +10,7 @@ #include <openssl/x509v3.h> #include <time.h> +#include <string> #include <vector> #include "cast/common/certificate/types.h" diff --git a/cast/common/discovery/e2e_test/tests.cc b/cast/common/discovery/e2e_test/tests.cc index 0d281dc7..90f5f824 100644 --- a/cast/common/discovery/e2e_test/tests.cc +++ b/cast/common/discovery/e2e_test/tests.cc @@ -20,20 +20,19 @@ #include "platform/impl/network_interface.h" #include "platform/impl/platform_client_posix.h" #include "platform/impl/task_runner.h" +#include "util/chrono_helpers.h" namespace openscreen { namespace cast { namespace { // Total wait time = 4 seconds. -constexpr std::chrono::milliseconds kWaitLoopSleepTime = - std::chrono::milliseconds(500); +constexpr milliseconds kWaitLoopSleepTime(500); constexpr int kMaxWaitLoopIterations = 8; // Total wait time = 2.5 seconds. // NOTE: This must be less than the above wait time. -constexpr std::chrono::milliseconds kCheckLoopSleepTime = - std::chrono::milliseconds(100); +constexpr milliseconds kCheckLoopSleepTime(100); constexpr int kMaxCheckLoopIterations = 25; @@ -132,9 +131,9 @@ class DiscoveryE2ETest : public testing::Test { public: DiscoveryE2ETest() { // Sleep to let any packets clear off the network before further tests. - std::this_thread::sleep_for(std::chrono::milliseconds(500)); + std::this_thread::sleep_for(milliseconds(500)); - PlatformClientPosix::Create(milliseconds{50}, milliseconds{50}); + PlatformClientPosix::Create(milliseconds(50), milliseconds(50)); task_runner_ = PlatformClientPosix::GetInstance()->GetTaskRunner(); } @@ -422,7 +421,7 @@ TEST_F(DiscoveryE2ETest, ValidateAnnouncementFlow) { ASSERT_FALSE(result.is_error()); ASSERT_EQ(result.value(), 3); }); - std::this_thread::sleep_for(std::chrono::seconds(3)); + std::this_thread::sleep_for(seconds(3)); found1 = false; found2 = false; found3 = false; @@ -524,7 +523,7 @@ TEST_F(DiscoveryE2ETest, ValidateRefreshFlow) { auto discovery_config = GetConfigSettings(); discovery_config.new_record_announcement_count = 0; discovery_config.new_query_announcement_count = 2; - constexpr std::chrono::seconds kMaxQueryDuration{3}; + constexpr seconds kMaxQueryDuration{3}; SetUpService(discovery_config); auto instance = GetInfo(1); diff --git a/cast/sender/channel/cast_auth_util.h b/cast/sender/channel/cast_auth_util.h index 4ca6df5e..d23ebd7e 100644 --- a/cast/sender/channel/cast_auth_util.h +++ b/cast/sender/channel/cast_auth_util.h @@ -7,7 +7,7 @@ #include <openssl/x509.h> -#include <chrono> // NOLINT +#include <chrono> #include <string> #include <vector> diff --git a/cast/standalone_receiver/cast_agent_integration_tests.cc b/cast/standalone_receiver/cast_agent_integration_tests.cc index 49b1ced4..919711ab 100644 --- a/cast/standalone_receiver/cast_agent_integration_tests.cc +++ b/cast/standalone_receiver/cast_agent_integration_tests.cc @@ -7,8 +7,8 @@ #include "cast/common/channel/virtual_connection_manager.h" #include "cast/common/channel/virtual_connection_router.h" #include "cast/sender/public/sender_socket_factory.h" +#include "cast/standalone_receiver/cast_agent.h" #include "cast/standalone_receiver/static_credentials.h" -#include "cast_agent.h" #include "gtest/gtest.h" #include "platform/api/serial_delete_ptr.h" #include "platform/api/time.h" @@ -57,8 +57,8 @@ class MockSender final : public SenderSocketFactory::Client, class CastAgentIntegrationTest : public ::testing::Test { public: void SetUp() override { - PlatformClientPosix::Create(std::chrono::milliseconds{50}, - std::chrono::milliseconds{50}); + PlatformClientPosix::Create(std::chrono::milliseconds(50), + std::chrono::milliseconds(50)); task_runner_ = reinterpret_cast<TaskRunnerImpl*>( PlatformClientPosix::GetInstance()->GetTaskRunner()); diff --git a/cast/standalone_receiver/decoder.cc b/cast/standalone_receiver/decoder.cc index 221c8570..9a2324e3 100644 --- a/cast/standalone_receiver/decoder.cc +++ b/cast/standalone_receiver/decoder.cc @@ -6,7 +6,7 @@ #include <algorithm> #include <sstream> -#include <thread> // NOLINT +#include <thread> #include "util/osp_logging.h" #include "util/trace_logging.h" @@ -32,7 +32,8 @@ void Decoder::Buffer::Resize(int new_size) { } absl::Span<const uint8_t> Decoder::Buffer::GetSpan() const { - return const_cast<Buffer*>(this)->GetSpan(); + return absl::Span<const uint8_t>( + buffer_.data(), buffer_.size() - AV_INPUT_BUFFER_PADDING_SIZE); } absl::Span<uint8_t> Decoder::Buffer::GetSpan() { diff --git a/cast/standalone_receiver/dummy_player.cc b/cast/standalone_receiver/dummy_player.cc index 5778f0b8..512ea7da 100644 --- a/cast/standalone_receiver/dummy_player.cc +++ b/cast/standalone_receiver/dummy_player.cc @@ -8,6 +8,7 @@ #include "absl/types/span.h" #include "cast/streaming/encoded_frame.h" +#include "util/chrono_helpers.h" #include "util/osp_logging.h" namespace openscreen { @@ -31,7 +32,7 @@ void DummyPlayer::OnFramesReady(int buffer_size) { // Convert the RTP timestamp to a human-readable timestamp (in µs) and log // some short information about the frame. const auto media_timestamp = - frame.rtp_timestamp.ToTimeSinceOrigin<microseconds>( + frame.rtp_timestamp.ToTimeSinceOrigin<std::chrono::microseconds>( receiver_->rtp_timebase()); OSP_LOG_INFO << "[SSRC " << receiver_->ssrc() << "] " << (frame.dependency == EncodedFrame::KEY_FRAME ? "KEY " : "") diff --git a/cast/standalone_receiver/main.cc b/cast/standalone_receiver/main.cc index 027edd81..44a1a0a0 100644 --- a/cast/standalone_receiver/main.cc +++ b/cast/standalone_receiver/main.cc @@ -5,7 +5,7 @@ #include <getopt.h> #include <array> -#include <chrono> // NOLINT +#include <chrono> #include <iostream> #include "absl/strings/str_cat.h" @@ -26,6 +26,7 @@ #include "platform/impl/platform_client_posix.h" #include "platform/impl/task_runner.h" #include "platform/impl/text_trace_logging_platform.h" +#include "util/chrono_helpers.h" #include "util/stringprintf.h" #include "util/trace_logging.h" @@ -178,7 +179,7 @@ int RunStandaloneReceiver(int argc, char* argv[]) { : openscreen::LogLevel::kInfo); auto* const task_runner = new TaskRunnerImpl(&Clock::now); - PlatformClientPosix::Create(milliseconds{50}, milliseconds{50}, + PlatformClientPosix::Create(milliseconds(50), milliseconds(50), std::unique_ptr<TaskRunnerImpl>(task_runner)); auto discovery_state = StartDiscovery(task_runner, interface_info); diff --git a/cast/standalone_receiver/sdl_audio_player.cc b/cast/standalone_receiver/sdl_audio_player.cc index fdb32b4b..3392b706 100644 --- a/cast/standalone_receiver/sdl_audio_player.cc +++ b/cast/standalone_receiver/sdl_audio_player.cc @@ -6,10 +6,12 @@ #include <chrono> #include <sstream> +#include <utility> #include "absl/types/span.h" #include "cast/standalone_receiver/avcodec_glue.h" #include "util/big_endian.h" +#include "util/chrono_helpers.h" #include "util/osp_logging.h" #include "util/trace_logging.h" @@ -113,9 +115,9 @@ ErrorOr<Clock::time_point> SDLAudioPlayer::RenderNextFrame( pending_audio_spec_.samples *= 2; } - approximate_lead_time_ = (pending_audio_spec_.samples * - duration_cast<Clock::duration>(kOneSecond)) / - pending_audio_spec_.freq; + approximate_lead_time_ = + (pending_audio_spec_.samples * Clock::to_duration(kOneSecond)) / + pending_audio_spec_.freq; } // If the decoded audio is in planar format, interleave it for SDL. diff --git a/cast/standalone_receiver/sdl_player_base.cc b/cast/standalone_receiver/sdl_player_base.cc index e1c03784..ab2f1327 100644 --- a/cast/standalone_receiver/sdl_player_base.cc +++ b/cast/standalone_receiver/sdl_player_base.cc @@ -6,11 +6,13 @@ #include <chrono> #include <sstream> +#include <utility> #include "absl/types/span.h" #include "cast/standalone_receiver/avcodec_glue.h" #include "cast/streaming/encoded_frame.h" #include "util/big_endian.h" +#include "util/chrono_helpers.h" #include "util/osp_logging.h" #include "util/trace_logging.h" @@ -71,8 +73,7 @@ Clock::time_point SDLPlayerBase::ResyncAndDeterminePresentationTime( .ToDuration<Clock::duration>(receiver_->rtp_timebase()); Clock::time_point presentation_time = last_sync_reference_time_ + media_time_since_last_sync; - const auto drift = - duration_cast<milliseconds>(frame.reference_time - presentation_time); + const auto drift = to_microseconds(frame.reference_time - presentation_time); if (drift > kMaxPlayoutDrift || drift < -kMaxPlayoutDrift) { // Only log if not the very first frame. OSP_LOG_IF(INFO, frame.frame_id != FrameId::first()) diff --git a/cast/standalone_receiver/static_credentials.cc b/cast/standalone_receiver/static_credentials.cc index 2ced690b..9980f20c 100644 --- a/cast/standalone_receiver/static_credentials.cc +++ b/cast/standalone_receiver/static_credentials.cc @@ -7,6 +7,7 @@ #include <openssl/mem.h> #include <memory> +#include <string> #include <utility> #include <vector> diff --git a/cast/standalone_sender/main.cc b/cast/standalone_sender/main.cc index 67c7a500..2f605e62 100644 --- a/cast/standalone_sender/main.cc +++ b/cast/standalone_sender/main.cc @@ -4,7 +4,7 @@ #include <getopt.h> -#include <chrono> // NOLINT +#include <chrono> #include <cinttypes> #include <csignal> #include <cstdio> @@ -26,6 +26,7 @@ #include "platform/impl/task_runner.h" #include "platform/impl/text_trace_logging_platform.h" #include "util/alarm.h" +#include "util/chrono_helpers.h" #if defined(CAST_STANDALONE_SENDER_HAVE_EXTERNAL_LIBS) #include "cast/standalone_sender/simulated_capturer.h" @@ -243,9 +244,8 @@ class LoopingFileSender final : public SimulatedAudioCapturer::Client, void UpdateStatusOnConsole() { const Clock::duration elapsed = latest_frame_time_ - capture_start_time_; - const auto seconds_part = duration_cast<seconds>(elapsed); - const auto millis_part = - duration_cast<milliseconds>(elapsed - seconds_part); + const auto seconds_part = to_seconds(elapsed); + const auto millis_part = to_microseconds(elapsed - seconds_part); // The control codes here attempt to erase the current line the cursor is // on, and then print out the updated status text. If the terminal does not // support simple ANSI escape codes, the following will still work, but @@ -440,7 +440,7 @@ int StandaloneSenderMain(int argc, char* argv[]) { #if defined(CAST_STANDALONE_SENDER_HAVE_EXTERNAL_LIBS) auto* const task_runner = new TaskRunnerImpl(&Clock::now); - PlatformClientPosix::Create(milliseconds{50}, milliseconds{50}, + PlatformClientPosix::Create(Clock::duration{50}, Clock::duration{50}, std::unique_ptr<TaskRunnerImpl>(task_runner)); { diff --git a/cast/standalone_sender/simulated_capturer.cc b/cast/standalone_sender/simulated_capturer.cc index 405922be..87313010 100644 --- a/cast/standalone_sender/simulated_capturer.cc +++ b/cast/standalone_sender/simulated_capturer.cc @@ -5,10 +5,10 @@ #include "cast/standalone_sender/simulated_capturer.h" #include <algorithm> -#include <chrono> // NOLINT -#include <ratio> // NOLINT +#include <chrono> +#include <ratio> #include <sstream> -#include <thread> // NOLINT +#include <thread> #include "cast/streaming/environment.h" #include "util/osp_logging.h" diff --git a/cast/standalone_sender/streaming_opus_encoder.cc b/cast/standalone_sender/streaming_opus_encoder.cc index 8ade76db..ef9cc577 100644 --- a/cast/standalone_sender/streaming_opus_encoder.cc +++ b/cast/standalone_sender/streaming_opus_encoder.cc @@ -7,7 +7,7 @@ #include <opus/opus.h> #include <algorithm> -#include <chrono> // NOLINT +#include <chrono> namespace openscreen { namespace cast { @@ -34,7 +34,7 @@ StreamingOpusEncoder::StreamingOpusEncoder(int num_channels, sender_(sender), samples_per_cast_frame_(sample_rate() / cast_frames_per_second), approximate_cast_frame_duration_( - duration_cast<Clock::duration>(seconds(1)) / cast_frames_per_second), + Clock::to_duration(std::chrono::seconds(1)) / cast_frames_per_second), encoder_storage_(new uint8_t[opus_encoder_get_size(num_channels_)]), input_(new float[num_channels_ * samples_per_cast_frame_]), output_(new uint8_t[kOpusMaxPayloadSize]) { diff --git a/cast/standalone_sender/streaming_vp8_encoder.cc b/cast/standalone_sender/streaming_vp8_encoder.cc index df7495ca..066e37f5 100644 --- a/cast/standalone_sender/streaming_vp8_encoder.cc +++ b/cast/standalone_sender/streaming_vp8_encoder.cc @@ -8,12 +8,14 @@ #include <string.h> #include <vpx/vp8cx.h> +#include <chrono> #include <cmath> #include <utility> #include "cast/streaming/encoded_frame.h" #include "cast/streaming/environment.h" #include "cast/streaming/sender.h" +#include "util/chrono_helpers.h" #include "util/osp_logging.h" #include "util/saturate_cast.h" @@ -367,7 +369,7 @@ void StreamingVp8Encoder::ComputeFrameEncodeStats( constexpr double kBytesPerBit = 1.0 / CHAR_BIT; constexpr double kSecondsPerClockTick = - 1.0 / duration_cast<Clock::duration>(seconds(1)).count(); + 1.0 / Clock::to_duration(seconds(1)).count(); const double target_bytes_per_clock_tick = target_bitrate * (kBytesPerBit * kSecondsPerClockTick); stats.target_size = target_bytes_per_clock_tick * work_unit->duration.count(); diff --git a/cast/standalone_sender/streaming_vp8_encoder.h b/cast/standalone_sender/streaming_vp8_encoder.h index 1c64cafc..c5d52248 100644 --- a/cast/standalone_sender/streaming_vp8_encoder.h +++ b/cast/standalone_sender/streaming_vp8_encoder.h @@ -12,9 +12,9 @@ #include <condition_variable> // NOLINT #include <functional> #include <memory> -#include <mutex> // NOLINT +#include <mutex> #include <queue> -#include <thread> // NOLINT +#include <thread> #include <vector> #include "absl/base/thread_annotations.h" diff --git a/cast/streaming/answer_messages.h b/cast/streaming/answer_messages.h index 60b9a494..efd72d6a 100644 --- a/cast/streaming/answer_messages.h +++ b/cast/streaming/answer_messages.h @@ -6,7 +6,7 @@ #define CAST_STREAMING_ANSWER_MESSAGES_H_ #include <array> -#include <chrono> // NOLINT +#include <chrono> #include <cstdint> #include <initializer_list> #include <memory> diff --git a/cast/streaming/answer_messages_unittest.cc b/cast/streaming/answer_messages_unittest.cc index d1c70828..35ad846a 100644 --- a/cast/streaming/answer_messages_unittest.cc +++ b/cast/streaming/answer_messages_unittest.cc @@ -4,10 +4,12 @@ #include "cast/streaming/answer_messages.h" +#include <chrono> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "util/chrono_helpers.h" #include "util/json/json_serialization.h" namespace openscreen { @@ -22,12 +24,12 @@ const Answer kValidAnswer{ std::vector<Ssrc>{123, 456}, // ssrcs Constraints{ AudioConstraints{ - 96000, // max_sample_rate - 7, // max_channels - 32000, // min_bit_rate - 96000, // max_bit_rate - std::chrono::milliseconds(2000) // max_delay - }, // audio + 96000, // max_sample_rate + 7, // max_channels + 32000, // min_bit_rate + 96000, // max_bit_rate + milliseconds(2000) // max_delay + }, // audio VideoConstraints{ 40000.0, // max_pixels_per_second Dimensions{ @@ -40,11 +42,11 @@ const Answer kValidAnswer{ 1080, // height SimpleFraction{288, 2} // frame_rate }, - 300000, // min_bit_rate - 144000000, // max_bit_rate - std::chrono::milliseconds(3000) // max_delay - } // video - }, // constraints + 300000, // min_bit_rate + 144000000, // max_bit_rate + milliseconds(3000) // max_delay + } // video + }, // constraints DisplayDescription{ Dimensions{ 640, // width diff --git a/cast/streaming/bandwidth_estimator.cc b/cast/streaming/bandwidth_estimator.cc index 5c42aa4a..e6bc594f 100644 --- a/cast/streaming/bandwidth_estimator.cc +++ b/cast/streaming/bandwidth_estimator.cc @@ -24,8 +24,7 @@ int ToClampedBitsPerSecond(int32_t bytes, Clock::duration time_window) { // Divide |bytes| by |time_window| and scale the units to bits per second. constexpr int64_t kBitsPerByte = 8; constexpr int64_t kClockTicksPerSecond = - std::chrono::duration_cast<Clock::duration>(std::chrono::seconds(1)) - .count(); + Clock::to_duration(std::chrono::seconds(1)).count(); const int64_t bits = bytes * kBitsPerByte; const int64_t bits_per_second = (bits * kClockTicksPerSecond) / time_window.count(); diff --git a/cast/streaming/bandwidth_estimator_unittest.cc b/cast/streaming/bandwidth_estimator_unittest.cc index d5891da3..6a2e1fc9 100644 --- a/cast/streaming/bandwidth_estimator_unittest.cc +++ b/cast/streaming/bandwidth_estimator_unittest.cc @@ -4,12 +4,14 @@ #include "cast/streaming/bandwidth_estimator.h" +#include <chrono> #include <limits> #include <random> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "platform/api/time.h" +#include "util/chrono_helpers.h" namespace openscreen { namespace cast { diff --git a/cast/streaming/compound_rtcp_builder_unittest.cc b/cast/streaming/compound_rtcp_builder_unittest.cc index 969056cf..4cc7de00 100644 --- a/cast/streaming/compound_rtcp_builder_unittest.cc +++ b/cast/streaming/compound_rtcp_builder_unittest.cc @@ -14,6 +14,7 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" #include "platform/api/time.h" +#include "util/chrono_helpers.h" using testing::_; using testing::Invoke; @@ -57,7 +58,7 @@ class CompoundRtcpBuilderTest : public testing::Test { TEST_F(CompoundRtcpBuilderTest, TheBasics) { const FrameId checkpoint = FrameId::first() + 42; builder()->SetCheckpointFrame(checkpoint); - const std::chrono::milliseconds playout_delay{321}; + const milliseconds playout_delay{321}; builder()->SetPlayoutDelay(playout_delay); const auto send_time = Clock::now(); @@ -115,7 +116,7 @@ TEST_F(CompoundRtcpBuilderTest, WithReceiverReportBlock) { // Build again, but this time the builder should not include the receiver // report block. - const auto second_send_time = send_time + std::chrono::milliseconds(500); + const auto second_send_time = send_time + milliseconds(500); const auto second_packet = builder()->BuildPacket(second_send_time, buffer); ASSERT_TRUE(second_packet.data()); EXPECT_CALL(*(client()), OnReceiverReferenceTimeAdvanced( @@ -160,7 +161,7 @@ TEST_F(CompoundRtcpBuilderTest, WithPictureLossIndicator) { Mock::VerifyAndClearExpectations(client()); ++checkpoint; - send_time += std::chrono::milliseconds(500); + send_time += milliseconds(500); } } } @@ -200,7 +201,7 @@ TEST_F(CompoundRtcpBuilderTest, WithNacks) { Mock::VerifyAndClearExpectations(client()); // Build again, but this time the builder should not include the feedback. - const auto second_send_time = send_time + std::chrono::milliseconds(500); + const auto second_send_time = send_time + milliseconds(500); const auto second_packet = builder()->BuildPacket(second_send_time, buffer); ASSERT_TRUE(second_packet.data()); EXPECT_CALL(*(client()), OnReceiverReferenceTimeAdvanced( @@ -248,7 +249,7 @@ TEST_F(CompoundRtcpBuilderTest, WithAcks) { // Build again, but this time the builder should not include the feedback // because it was already provided in the prior packet. - send_time += std::chrono::milliseconds(500); + send_time += milliseconds(500); const auto second_packet = builder()->BuildPacket(send_time, buffer); ASSERT_TRUE(second_packet.data()); EXPECT_CALL(*(client()), OnReceiverReferenceTimeAdvanced( @@ -258,7 +259,7 @@ TEST_F(CompoundRtcpBuilderTest, WithAcks) { ASSERT_TRUE(parser()->Parse(second_packet, kMaxFeedbackFrameId)); Mock::VerifyAndClearExpectations(client()); - send_time += std::chrono::milliseconds(500); + send_time += milliseconds(500); } } diff --git a/cast/streaming/compound_rtcp_parser_unittest.cc b/cast/streaming/compound_rtcp_parser_unittest.cc index 9f8e3c50..7b2499a2 100644 --- a/cast/streaming/compound_rtcp_parser_unittest.cc +++ b/cast/streaming/compound_rtcp_parser_unittest.cc @@ -12,6 +12,7 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" #include "platform/api/time.h" +#include "util/chrono_helpers.h" using testing::_; using testing::Mock; @@ -264,7 +265,7 @@ TEST_F(CompoundRtcpParserTest, ParsesSimpleFeedback) { // First scenario: Valid range of FrameIds is [0,42]. const auto kMaxFeedbackFrameId0 = FrameId::first() + 42; const auto expected_frame_id0 = FrameId::first() + 10; - const auto expected_playout_delay = std::chrono::milliseconds(550); + const auto expected_playout_delay = milliseconds(550); EXPECT_CALL(*(client()), OnReceiverCheckpoint(expected_frame_id0, expected_playout_delay)); EXPECT_TRUE(parser()->Parse(kFeedbackPacket, kMaxFeedbackFrameId0)); @@ -321,7 +322,7 @@ TEST_F(CompoundRtcpParserTest, ParsesFeedbackWithNacks) { const auto kMaxFeedbackFrameId = FrameId::first() + 42; const auto expected_frame_id = FrameId::first() + 10; - const auto expected_playout_delay = std::chrono::milliseconds(552); + const auto expected_playout_delay = milliseconds(552); EXPECT_CALL(*(client()), OnReceiverCheckpoint(expected_frame_id, expected_playout_delay)); EXPECT_CALL(*(client()), OnReceiverIsMissingPackets(kMissingPackets)); @@ -386,7 +387,7 @@ TEST_F(CompoundRtcpParserTest, ParsesFeedbackWithAcks) { // Test the smaller packet. const auto kMaxFeedbackFrameId = FrameId::first() + 100; const auto expected_frame_id = FrameId::first() + 10; - const auto expected_playout_delay = std::chrono::milliseconds(294); + const auto expected_playout_delay = milliseconds(294); EXPECT_CALL(*(client()), OnReceiverCheckpoint(expected_frame_id, expected_playout_delay)); EXPECT_CALL(*(client()), OnReceiverHasFrames(kFrame13Only)); diff --git a/cast/streaming/ntp_time.cc b/cast/streaming/ntp_time.cc index d983de50..9fd04e03 100644 --- a/cast/streaming/ntp_time.cc +++ b/cast/streaming/ntp_time.cc @@ -19,17 +19,19 @@ constexpr NtpSeconds kTimeBetweenNtpEpochAndUnixEpoch{INT64_C(2208988800)}; NtpTimeConverter::NtpTimeConverter(Clock::time_point now, std::chrono::seconds since_unix_epoch) : start_time_(now), - since_ntp_epoch_(duration_cast<NtpSeconds>(since_unix_epoch) + - kTimeBetweenNtpEpochAndUnixEpoch) {} + since_ntp_epoch_( + std::chrono::duration_cast<NtpSeconds>(since_unix_epoch) + + kTimeBetweenNtpEpochAndUnixEpoch) {} NtpTimeConverter::~NtpTimeConverter() = default; NtpTimestamp NtpTimeConverter::ToNtpTimestamp( Clock::time_point time_point) const { const Clock::duration time_since_start = time_point - start_time_; - const auto whole_seconds = duration_cast<NtpSeconds>(time_since_start); + const auto whole_seconds = + std::chrono::duration_cast<NtpSeconds>(time_since_start); const auto remainder = - duration_cast<NtpFraction>(time_since_start - whole_seconds); + std::chrono::duration_cast<NtpFraction>(time_since_start - whole_seconds); return AssembleNtpTimestamp(since_ntp_epoch_ + whole_seconds, remainder); } @@ -45,9 +47,8 @@ Clock::time_point NtpTimeConverter::ToLocalTime(NtpTimestamp timestamp) const { const auto whole_seconds = ntp_seconds - since_ntp_epoch_; const auto seconds_since_start = - duration_cast<Clock::duration>(whole_seconds) + start_time_; - const auto remainder = - duration_cast<Clock::duration>(NtpFractionPart(timestamp)); + Clock::to_duration(whole_seconds) + start_time_; + const auto remainder = Clock::to_duration(NtpFractionPart(timestamp)); return seconds_since_start + remainder; } diff --git a/cast/streaming/ntp_time_unittest.cc b/cast/streaming/ntp_time_unittest.cc index 5a865908..325e7587 100644 --- a/cast/streaming/ntp_time_unittest.cc +++ b/cast/streaming/ntp_time_unittest.cc @@ -4,7 +4,10 @@ #include "cast/streaming/ntp_time.h" +#include <chrono> + #include "gtest/gtest.h" +#include "util/chrono_helpers.h" namespace openscreen { namespace cast { @@ -18,8 +21,7 @@ TEST(NtpTimestampTest, SplitsIntoParts) { // 1 Jan 1900 plus 10 ms. timestamp = UINT64_C(0x00000000028f5c29); EXPECT_EQ(NtpSeconds::zero(), NtpSecondsPart(timestamp)); - EXPECT_EQ(milliseconds(10), - duration_cast<milliseconds>(NtpFractionPart(timestamp))); + EXPECT_EQ(milliseconds(10), to_microseconds(NtpFractionPart(timestamp))); // 1 Jan 1970 minus 2^-32 seconds. timestamp = UINT64_C(0x83aa7e80ffffffff); @@ -29,8 +31,7 @@ TEST(NtpTimestampTest, SplitsIntoParts) { // 2019-03-23 17:25:50.500. timestamp = UINT64_C(0xe0414d0e80000000); EXPECT_EQ(NtpSeconds(INT64_C(3762375950)), NtpSecondsPart(timestamp)); - EXPECT_EQ(milliseconds(500), - duration_cast<milliseconds>(NtpFractionPart(timestamp))); + EXPECT_EQ(milliseconds(500), to_microseconds(NtpFractionPart(timestamp))); } TEST(NtpTimestampTest, AssemblesFromParts) { @@ -39,13 +40,14 @@ TEST(NtpTimestampTest, AssemblesFromParts) { AssembleNtpTimestamp(NtpSeconds::zero(), NtpFraction::zero()); EXPECT_EQ(UINT64_C(0x0000000000000000), timestamp); - // 1 Jan 1900 plus 10 ms. Note that the duration_cast<NtpFraction>(10ms) - // truncates rather than rounds the 10ms value, so the resulting timestamp is - // one fractional tick less than the one found in the SplitsIntoParts test. - // The ~0.4 nanosecond error in the conversion is totally insignificant to a - // live system. + // 1 Jan 1900 plus 10 ms. Note that the + // std::chrono::duration_cast<NtpFraction>(10ms) truncates rather than rounds + // the 10ms value, so the resulting timestamp is one fractional tick less than + // the one found in the SplitsIntoParts test. The ~0.4 nanosecond error in the + // conversion is totally insignificant to a live system. timestamp = AssembleNtpTimestamp( - NtpSeconds::zero(), duration_cast<NtpFraction>(milliseconds(10))); + NtpSeconds::zero(), + std::chrono::duration_cast<NtpFraction>(milliseconds(10))); EXPECT_EQ(UINT64_C(0x00000000028f5c28), timestamp); // 1 Jan 1970 minus 2^-32 seconds. @@ -54,9 +56,9 @@ TEST(NtpTimestampTest, AssemblesFromParts) { EXPECT_EQ(UINT64_C(0x83aa7e7fffffffff), timestamp); // 2019-03-23 17:25:50.500. - timestamp = - AssembleNtpTimestamp(NtpSeconds(INT64_C(3762375950)), - duration_cast<NtpFraction>(milliseconds(500))); + timestamp = AssembleNtpTimestamp( + NtpSeconds(INT64_C(3762375950)), + std::chrono::duration_cast<NtpFraction>(milliseconds(500))); EXPECT_EQ(UINT64_C(0xe0414d0e80000000), timestamp); } diff --git a/cast/streaming/offer_messages.h b/cast/streaming/offer_messages.h index 319145bc..f5642495 100644 --- a/cast/streaming/offer_messages.h +++ b/cast/streaming/offer_messages.h @@ -5,7 +5,7 @@ #ifndef CAST_STREAMING_OFFER_MESSAGES_H_ #define CAST_STREAMING_OFFER_MESSAGES_H_ -#include <chrono> // NOLINT +#include <chrono> #include <string> #include <vector> diff --git a/cast/streaming/packet_receive_stats_tracker_unittest.cc b/cast/streaming/packet_receive_stats_tracker_unittest.cc index 5146cc8d..eb1b45c7 100644 --- a/cast/streaming/packet_receive_stats_tracker_unittest.cc +++ b/cast/streaming/packet_receive_stats_tracker_unittest.cc @@ -4,10 +4,12 @@ #include "cast/streaming/packet_receive_stats_tracker.h" +#include <chrono> #include <limits> #include "cast/streaming/constants.h" #include "gtest/gtest.h" +#include "util/chrono_helpers.h" namespace openscreen { namespace cast { @@ -74,8 +76,7 @@ TEST(PacketReceiveStatsTrackerTest, PopulatesReportWithOnePacketTracked) { constexpr uint16_t kSequenceNumber = 1234; constexpr RtpTimeTicks kRtpTimestamp = RtpTimeTicks() + RtpTimeDelta::FromTicks(42); - constexpr auto kArrivalTime = - Clock::time_point() + std::chrono::seconds(3600); + constexpr auto kArrivalTime = Clock::time_point() + seconds(3600); PacketReceiveStatsTracker tracker(kSomeRtpTimebase); tracker.OnReceivedValidRtpPacket(kSequenceNumber, kRtpTimestamp, @@ -96,8 +97,7 @@ TEST(PacketReceiveStatsTrackerTest, WhenReceivingAllPackets) { std::numeric_limits<uint16_t>::max() - 2; constexpr RtpTimeTicks kFirstRtpTimestamp = RtpTimeTicks() + RtpTimeDelta::FromTicks(42); - constexpr auto kFirstArrivalTime = - Clock::time_point() + std::chrono::seconds(3600); + constexpr auto kFirstArrivalTime = Clock::time_point() + seconds(3600); PacketReceiveStatsTracker tracker(kSomeRtpTimebase); @@ -107,7 +107,7 @@ TEST(PacketReceiveStatsTrackerTest, WhenReceivingAllPackets) { tracker.OnReceivedValidRtpPacket( kFirstSequenceNumber + i, kFirstRtpTimestamp + RtpTimeDelta::FromTicks(kSomeRtpTimebase) * i, - kFirstArrivalTime + std::chrono::seconds(i)); + kFirstArrivalTime + seconds(i)); } RtcpReportBlock report = GetSentinel(); @@ -131,8 +131,7 @@ TEST(PacketReceiveStatsTrackerTest, WhenReceivingAboutHalfThePackets) { constexpr uint16_t kFirstSequenceNumber = 3; constexpr RtpTimeTicks kFirstRtpTimestamp = RtpTimeTicks() + RtpTimeDelta::FromTicks(99); - constexpr auto kFirstArrivalTime = - Clock::time_point() + std::chrono::seconds(8888); + constexpr auto kFirstArrivalTime = Clock::time_point() + seconds(8888); PacketReceiveStatsTracker tracker(kSomeRtpTimebase); @@ -145,7 +144,7 @@ TEST(PacketReceiveStatsTrackerTest, WhenReceivingAboutHalfThePackets) { tracker.OnReceivedValidRtpPacket( kFirstSequenceNumber + (i * 2 + 1), kFirstRtpTimestamp + RtpTimeDelta::FromTicks(kSomeRtpTimebase) * i, - kFirstArrivalTime + std::chrono::seconds(i)); + kFirstArrivalTime + seconds(i)); } RtcpReportBlock report = GetSentinel(); @@ -163,14 +162,12 @@ TEST(PacketReceiveStatsTrackerTest, ComputesJitterCorrectly) { constexpr uint16_t kFirstSequenceNumber = 3; constexpr RtpTimeTicks kFirstRtpTimestamp = RtpTimeTicks() + RtpTimeDelta::FromTicks(99); - constexpr auto kFirstArrivalTime = - Clock::time_point() + std::chrono::seconds(8888); + constexpr auto kFirstArrivalTime = Clock::time_point() + seconds(8888); // Record 100 packet arrivals, one second apart, where each packet's RTP // timestamps are progressing 2 seconds forward. Thus, the jitter calculation // should gradually converge towards a difference of one second. - constexpr auto kTrueJitter = - std::chrono::duration_cast<Clock::duration>(std::chrono::seconds(1)); + constexpr auto kTrueJitter = Clock::to_duration(seconds(1)); PacketReceiveStatsTracker tracker(kSomeRtpTimebase); Clock::duration last_diff = Clock::duration::max(); for (int i = 0; i < 100; ++i) { @@ -178,7 +175,7 @@ TEST(PacketReceiveStatsTrackerTest, ComputesJitterCorrectly) { kFirstSequenceNumber + i, kFirstRtpTimestamp + RtpTimeDelta::FromTicks(kSomeRtpTimebase) * (i * 2), - kFirstArrivalTime + std::chrono::seconds(i)); + kFirstArrivalTime + seconds(i)); // Expect that the jitter is becoming closer to the actual value in each // iteration. @@ -198,8 +195,7 @@ TEST(PacketReceiveStatsTrackerTest, ComputesJitterCorrectly) { tracker.PopulateNextReport(&report); const auto diff = kTrueJitter - report.jitter.ToDuration<Clock::duration>(kSomeRtpTimebase); - constexpr auto kMaxDiffAtEnd = - std::chrono::duration_cast<Clock::duration>(std::chrono::milliseconds(2)); + constexpr auto kMaxDiffAtEnd = Clock::to_duration(milliseconds(2)); EXPECT_NEAR(0, diff.count(), kMaxDiffAtEnd.count()); } diff --git a/cast/streaming/receiver.cc b/cast/streaming/receiver.cc index 5c8babd1..d4c86da4 100644 --- a/cast/streaming/receiver.cc +++ b/cast/streaming/receiver.cc @@ -5,11 +5,13 @@ #include "cast/streaming/receiver.h" #include <algorithm> +#include <utility> #include "absl/types/span.h" #include "cast/streaming/constants.h" #include "cast/streaming/receiver_packet_router.h" #include "cast/streaming/session_config.h" +#include "util/chrono_helpers.h" #include "util/osp_logging.h" #include "util/std_util.h" @@ -144,14 +146,14 @@ EncodedFrame Receiver::ConsumeNextFrame(absl::Span<uint8_t> buffer) { frame.reference_time = *entry.estimated_capture_time + ResolveTargetPlayoutDelay(frame_id); - RECEIVER_VLOG - << "ConsumeNextFrame → " << frame.frame_id << ": " << frame.data.size() - << " payload bytes, RTP Timestamp " - << frame.rtp_timestamp.ToTimeSinceOrigin<microseconds>(rtp_timebase_) - .count() - << " µs, to play-out " - << duration_cast<microseconds>(frame.reference_time - now_()).count() - << " µs from now."; + RECEIVER_VLOG << "ConsumeNextFrame → " << frame.frame_id << ": " + << frame.data.size() << " payload bytes, RTP Timestamp " + << frame.rtp_timestamp + .ToTimeSinceOrigin<microseconds>(rtp_timebase_) + .count() + << " µs, to play-out " + << to_microseconds(frame.reference_time - now_()).count() + << " µs from now."; entry.Reset(); last_frame_consumed_ = frame_id; @@ -306,7 +308,7 @@ void Receiver::OnReceivedRtcpPacket(Clock::time_point arrival_time, smoothed_clock_offset_.Update(arrival_time, measured_offset); RECEIVER_VLOG << "Received Sender Report: Local clock is ahead of Sender's by " - << duration_cast<microseconds>(smoothed_clock_offset_.Current()).count() + << to_microseconds(smoothed_clock_offset_.Current()).count() << " µs (minus one-way network transit time)."; RtcpReportBlock report; diff --git a/cast/streaming/receiver.h b/cast/streaming/receiver.h index e63a9e4e..b4c53868 100644 --- a/cast/streaming/receiver.h +++ b/cast/streaming/receiver.h @@ -8,8 +8,9 @@ #include <stdint.h> #include <array> -#include <chrono> // NOLINT +#include <chrono> #include <memory> +#include <utility> #include <vector> #include "absl/types/optional.h" diff --git a/cast/streaming/receiver_session.cc b/cast/streaming/receiver_session.cc index 83ac0cf6..5d2e74bd 100644 --- a/cast/streaming/receiver_session.cc +++ b/cast/streaming/receiver_session.cc @@ -4,7 +4,7 @@ #include "cast/streaming/receiver_session.h" -#include <chrono> // NOLINT +#include <chrono> #include <string> #include <utility> diff --git a/cast/streaming/receiver_session.h b/cast/streaming/receiver_session.h index d41af31c..44cf864b 100644 --- a/cast/streaming/receiver_session.h +++ b/cast/streaming/receiver_session.h @@ -7,6 +7,7 @@ #include <memory> #include <string> +#include <utility> #include <vector> #include "cast/streaming/answer_messages.h" diff --git a/cast/streaming/receiver_session_unittest.cc b/cast/streaming/receiver_session_unittest.cc index ce9a0079..afedde2f 100644 --- a/cast/streaming/receiver_session_unittest.cc +++ b/cast/streaming/receiver_session_unittest.cc @@ -365,7 +365,7 @@ TEST_F(ReceiverSessionTest, CanNegotiateWithCustomConstraints) { AudioConstraints{1, 2, 3, 4}, VideoConstraints{3.14159, Dimensions{320, 240, SimpleFraction{24, 1}}, Dimensions{1920, 1080, SimpleFraction{144, 1}}, 3000, - 90000000, std::chrono::milliseconds{1000}}}}; + 90000000, std::chrono::milliseconds(1000)}}}; auto display = std::unique_ptr<DisplayDescription>{new DisplayDescription{ Dimensions{640, 480, SimpleFraction{60, 1}}, AspectRatio{16, 9}, diff --git a/cast/streaming/receiver_unittest.cc b/cast/streaming/receiver_unittest.cc index 19791bdb..d3c77178 100644 --- a/cast/streaming/receiver_unittest.cc +++ b/cast/streaming/receiver_unittest.cc @@ -35,6 +35,7 @@ #include "platform/base/udp_packet.h" #include "platform/test/fake_clock.h" #include "platform/test/fake_task_runner.h" +#include "util/chrono_helpers.h" #include "util/osp_logging.h" using testing::_; @@ -399,11 +400,10 @@ TEST_F(ReceiverTest, ReceivesAndSendsRtcpPackets) { // from the wire-format NtpTimestamps. See the unit tests in // ntp_time_unittest.cc for further discussion. constexpr auto kAllowedNtpRoundingError = microseconds(2); - EXPECT_NEAR(duration_cast<microseconds>(kOneWayNetworkDelay).count(), - duration_cast<microseconds>(receiver_reference_time - - sender_reference_time) - .count(), - kAllowedNtpRoundingError.count()); + EXPECT_NEAR( + to_microseconds(kOneWayNetworkDelay).count(), + to_microseconds(receiver_reference_time - sender_reference_time).count(), + kAllowedNtpRoundingError.count()); // Without the Sender doing anything, the Receiver should continue providing // RTCP reports at regular intervals. Simulate three intervals of time, diff --git a/cast/streaming/rtcp_common.cc b/cast/streaming/rtcp_common.cc index 696849bb..ce1e42d9 100644 --- a/cast/streaming/rtcp_common.cc +++ b/cast/streaming/rtcp_common.cc @@ -4,6 +4,7 @@ #include "cast/streaming/rtcp_common.h" +#include <algorithm> #include <limits> #include "cast/streaming/packet_util.h" @@ -187,7 +188,7 @@ void RtcpReportBlock::SetDelaySinceLastReport( // math (well, only for unusually large inputs). constexpr Delay kMaxValidReportedDelay{std::numeric_limits<uint32_t>::max()}; constexpr auto kMaxValidLocalClockDelay = - std::chrono::duration_cast<Clock::duration>(kMaxValidReportedDelay); + Clock::to_duration(kMaxValidReportedDelay); if (local_clock_delay > kMaxValidLocalClockDelay) { delay_since_last_report = kMaxValidReportedDelay; return; diff --git a/cast/streaming/rtcp_common_unittest.cc b/cast/streaming/rtcp_common_unittest.cc index d593e4f0..14aaa7ee 100644 --- a/cast/streaming/rtcp_common_unittest.cc +++ b/cast/streaming/rtcp_common_unittest.cc @@ -10,6 +10,7 @@ #include "absl/types/span.h" #include "gtest/gtest.h" #include "platform/api/time.h" +#include "util/chrono_helpers.h" namespace openscreen { namespace cast { @@ -280,28 +281,23 @@ TEST(RtcpCommonTest, ComputesDelayForReportBlocks) { // A duration less than or equal to zero should clamp to zero. EXPECT_EQ(Delay::zero(), ComputeDelay(Clock::duration::min())); - EXPECT_EQ(Delay::zero(), ComputeDelay(std::chrono::milliseconds(-1234))); + EXPECT_EQ(Delay::zero(), ComputeDelay(milliseconds{-1234})); EXPECT_EQ(Delay::zero(), ComputeDelay(Clock::duration::zero())); // Test conversion of various durations that should not clamp. EXPECT_EQ(Delay(32768 /* 1/2 second worth of ticks */), - ComputeDelay(std::chrono::milliseconds(500))); + ComputeDelay(milliseconds(500))); EXPECT_EQ(Delay(65536 /* 1 second worth of ticks */), - ComputeDelay(std::chrono::seconds(1))); + ComputeDelay(seconds(1))); EXPECT_EQ(Delay(655360 /* 10 seconds worth of ticks */), - ComputeDelay(std::chrono::seconds(10))); - EXPECT_EQ(Delay(4294967294), - ComputeDelay(std::chrono::microseconds(65535999983))); - EXPECT_EQ(Delay(4294967294), - ComputeDelay(std::chrono::microseconds(65535999984))); + ComputeDelay(seconds(10))); + EXPECT_EQ(Delay(4294967294), ComputeDelay(microseconds(65535999983))); + EXPECT_EQ(Delay(4294967294), ComputeDelay(microseconds(65535999984))); // A too-large duration should clamp to the maximum-possible Delay value. - EXPECT_EQ(Delay(4294967295), - ComputeDelay(std::chrono::microseconds(65535999985))); - EXPECT_EQ(Delay(4294967295), - ComputeDelay(std::chrono::microseconds(65535999986))); - EXPECT_EQ(Delay(4294967295), - ComputeDelay(std::chrono::microseconds(999999000000))); + EXPECT_EQ(Delay(4294967295), ComputeDelay(microseconds(65535999985))); + EXPECT_EQ(Delay(4294967295), ComputeDelay(microseconds(65535999986))); + EXPECT_EQ(Delay(4294967295), ComputeDelay(microseconds(999999000000))); EXPECT_EQ(Delay(4294967295), ComputeDelay(Clock::duration::max())); } diff --git a/cast/streaming/rtp_packetizer_unittest.cc b/cast/streaming/rtp_packetizer_unittest.cc index d99eefa0..8b471065 100644 --- a/cast/streaming/rtp_packetizer_unittest.cc +++ b/cast/streaming/rtp_packetizer_unittest.cc @@ -4,12 +4,16 @@ #include "cast/streaming/rtp_packetizer.h" +#include <chrono> +#include <memory> + #include "absl/types/optional.h" #include "cast/streaming/frame_crypto.h" #include "cast/streaming/rtp_defines.h" #include "cast/streaming/rtp_packet_parser.h" #include "cast/streaming/ssrc.h" #include "gtest/gtest.h" +#include "util/chrono_helpers.h" namespace openscreen { namespace cast { @@ -34,7 +38,7 @@ class RtpPacketizerTest : public testing::Test { EncryptedFrame CreateFrame(FrameId frame_id, bool is_key_frame, - std::chrono::milliseconds new_playout_delay, + milliseconds new_playout_delay, int payload_size) const { EncodedFrame frame; frame.dependency = is_key_frame ? EncodedFrame::KEY_FRAME @@ -102,7 +106,7 @@ class RtpPacketizerTest : public testing::Test { if (packet_id == FramePacketId{0}) { EXPECT_EQ(frame.new_playout_delay, result->new_playout_delay); } else { - EXPECT_EQ(std::chrono::milliseconds(0), result->new_playout_delay); + EXPECT_EQ(milliseconds(0), result->new_playout_delay); } // Check that the RTP payload is correct for this packet. @@ -141,8 +145,8 @@ TEST_F(RtpPacketizerTest, GeneratesPacketsForSequenceOfFrames) { const bool is_key_frame = (i == 0); const int frame_payload_size = is_key_frame ? 48269 : 10000; const EncryptedFrame frame = - CreateFrame(FrameId::first() + i, is_key_frame, - std::chrono::milliseconds(0), frame_payload_size); + CreateFrame(FrameId::first() + i, is_key_frame, milliseconds(0), + frame_payload_size); SCOPED_TRACE(testing::Message() << "frame_id=" << frame.frame_id); const int num_packets = packetizer()->ComputeNumberOfPackets(frame); ASSERT_EQ(is_key_frame ? 34 : 7, num_packets); @@ -160,9 +164,8 @@ TEST_F(RtpPacketizerTest, GeneratesPacketsForSequenceOfFrames) { // delay change. Only the first packet should mention the playout delay change. TEST_F(RtpPacketizerTest, GeneratesPacketsForFrameWithLatencyChange) { const int frame_payload_size = 38383; - const EncryptedFrame frame = - CreateFrame(FrameId::first() + 42, true, std::chrono::milliseconds(543), - frame_payload_size); + const EncryptedFrame frame = CreateFrame( + FrameId::first() + 42, true, milliseconds(543), frame_payload_size); const int num_packets = packetizer()->ComputeNumberOfPackets(frame); ASSERT_EQ(27, num_packets); @@ -179,9 +182,8 @@ TEST_F(RtpPacketizerTest, GeneratesPacketsForFrameWithLatencyChange) { // silence can be represented by an empty payload). TEST_F(RtpPacketizerTest, GeneratesOnePacketForFrameWithNoPayload) { const int frame_payload_size = 0; - const EncryptedFrame frame = - CreateFrame(FrameId::first() + 99, false, std::chrono::milliseconds(0), - frame_payload_size); + const EncryptedFrame frame = CreateFrame(FrameId::first() + 99, false, + milliseconds(0), frame_payload_size); ASSERT_EQ(1, packetizer()->ComputeNumberOfPackets(frame)); TestGeneratePacket(frame, FramePacketId{0}); } @@ -190,8 +192,8 @@ TEST_F(RtpPacketizerTest, GeneratesOnePacketForFrameWithNoPayload) { // a different sequence counter value in the packet each time. TEST_F(RtpPacketizerTest, GeneratesPacketForRetransmission) { const int frame_payload_size = 16384; - const EncryptedFrame frame = CreateFrame( - FrameId::first(), true, std::chrono::milliseconds(0), frame_payload_size); + const EncryptedFrame frame = + CreateFrame(FrameId::first(), true, milliseconds(0), frame_payload_size); const int num_packets = packetizer()->ComputeNumberOfPackets(frame); ASSERT_EQ(12, num_packets); diff --git a/cast/streaming/rtp_time_unittest.cc b/cast/streaming/rtp_time_unittest.cc index 89254372..54173a8b 100644 --- a/cast/streaming/rtp_time_unittest.cc +++ b/cast/streaming/rtp_time_unittest.cc @@ -4,7 +4,10 @@ #include "cast/streaming/rtp_time.h" +#include <chrono> + #include "gtest/gtest.h" +#include "util/chrono_helpers.h" namespace openscreen { namespace cast { diff --git a/cast/streaming/sender.cc b/cast/streaming/sender.cc index 56fc7b67..3713a199 100644 --- a/cast/streaming/sender.cc +++ b/cast/streaming/sender.cc @@ -5,9 +5,11 @@ #include "cast/streaming/sender.h" #include <algorithm> -#include <ratio> // NOLINT +#include <chrono> +#include <ratio> #include "cast/streaming/session_config.h" +#include "util/chrono_helpers.h" #include "util/osp_logging.h" #include "util/std_util.h" @@ -260,7 +262,7 @@ void Sender::OnReceiverReport(const RtcpReportBlock& receiver_report) { sender_report_builder_.GetRecentReportTime( receiver_report.last_status_report_id, rtcp_packet_arrival_time_); const auto non_network_delay = - duration_cast<Clock::duration>(receiver_report.delay_since_last_report); + Clock::to_duration(receiver_report.delay_since_last_report); // Round trip time measurement: This is the time elapsed since the Sender // Report was sent, minus the time the Receiver did other stuff before sending @@ -271,8 +273,7 @@ void Sender::OnReceiverReport(const RtcpReportBlock& receiver_report) { // true value is likely very close to zero (i.e., this is ideal network // behavior); and so just represent this as 75 µs, an optimistic // wired-Ethernet LAN ping time. - constexpr auto kNearZeroRoundTripTime = - duration_cast<Clock::duration>(microseconds(75)); + constexpr auto kNearZeroRoundTripTime = Clock::to_duration(microseconds(75)); static_assert(kNearZeroRoundTripTime > Clock::duration::zero(), "More precision in Clock::duration needed!"); const Clock::duration measurement = @@ -497,8 +498,8 @@ Sender::ChosenPacketAndWhen Sender::ChooseKickstartPacket() { // arrivals. using kWaitFraction = std::ratio<1, 20>; const Clock::duration desired_kickstart_interval = - duration_cast<Clock::duration>(target_playout_delay_) * - kWaitFraction::num / kWaitFraction::den; + Clock::to_duration(target_playout_delay_) * kWaitFraction::num / + kWaitFraction::den; // The actual interval used is increased, if current network performance // warrants waiting longer. Don't send a Kickstart packet until no NACKs // have been received for two network round-trip periods. diff --git a/cast/streaming/sender.h b/cast/streaming/sender.h index 48f651c0..33ea5227 100644 --- a/cast/streaming/sender.h +++ b/cast/streaming/sender.h @@ -8,7 +8,7 @@ #include <stdint.h> #include <array> -#include <chrono> // NOLINT +#include <chrono> #include <vector> #include "absl/types/span.h" diff --git a/cast/streaming/sender_packet_router.cc b/cast/streaming/sender_packet_router.cc index 71fb2991..c3fccd18 100644 --- a/cast/streaming/sender_packet_router.cc +++ b/cast/streaming/sender_packet_router.cc @@ -9,6 +9,7 @@ #include "cast/streaming/constants.h" #include "cast/streaming/packet_util.h" +#include "util/chrono_helpers.h" #include "util/osp_logging.h" #include "util/saturate_cast.h" #include "util/stringprintf.h" @@ -223,8 +224,7 @@ int SenderPacketRouter::SendJustTheRtpPackets(Clock::time_point send_time, namespace { constexpr int kBitsPerByte = 8; -constexpr auto kOneSecondInMilliseconds = - duration_cast<milliseconds>(seconds(1)); +constexpr auto kOneSecondInMilliseconds = to_microseconds(seconds(1)); } // namespace // static diff --git a/cast/streaming/sender_packet_router.h b/cast/streaming/sender_packet_router.h index e73e73ec..a6c161a9 100644 --- a/cast/streaming/sender_packet_router.h +++ b/cast/streaming/sender_packet_router.h @@ -7,7 +7,7 @@ #include <stdint.h> -#include <chrono> // NOLINT +#include <chrono> #include <memory> #include <vector> diff --git a/cast/streaming/sender_packet_router_unittest.cc b/cast/streaming/sender_packet_router_unittest.cc index 2ccbf241..d0b717c9 100644 --- a/cast/streaming/sender_packet_router_unittest.cc +++ b/cast/streaming/sender_packet_router_unittest.cc @@ -4,6 +4,8 @@ #include "cast/streaming/sender_packet_router.h" +#include <chrono> + #include "cast/streaming/constants.h" #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -11,6 +13,7 @@ #include "platform/test/fake_clock.h" #include "platform/test/fake_task_runner.h" #include "util/big_endian.h" +#include "util/chrono_helpers.h" #include "util/osp_logging.h" using testing::_; diff --git a/cast/streaming/sender_unittest.cc b/cast/streaming/sender_unittest.cc index 2ab64c59..7b162161 100644 --- a/cast/streaming/sender_unittest.cc +++ b/cast/streaming/sender_unittest.cc @@ -8,10 +8,11 @@ #include <algorithm> #include <array> -#include <chrono> // NOLINT +#include <chrono> #include <limits> #include <map> #include <set> +#include <utility> #include <vector> #include "absl/types/optional.h" @@ -36,6 +37,7 @@ #include "platform/test/fake_clock.h" #include "platform/test/fake_task_runner.h" #include "util/alarm.h" +#include "util/chrono_helpers.h" #include "util/yet_another_bit_vector.h" using testing::_; @@ -522,8 +524,7 @@ TEST_F(SenderTest, ComputesInFlightMediaDuration) { TEST_F(SenderTest, RespondsToNetworkLatencyChanges) { // The expected maximum error in time calculations is one tick of the RTCP // report block's delay type. - constexpr auto kEpsilon = - duration_cast<nanoseconds>(RtcpReportBlock::Delay(1)); + constexpr auto kEpsilon = to_nanoseconds(RtcpReportBlock::Delay(1)); // Before the Sender has the necessary information to compute the network // round-trip time, GetMaxInFlightMediaDuration() will return half the target @@ -566,8 +567,8 @@ TEST_F(SenderTest, RespondsToNetworkLatencyChanges) { // Create the Receiver Report "reply," and simulate it being sent across the // network, back to the Sender. receiver()->SetReceiverReport( - sender_report_id, - duration_cast<RtcpReportBlock::Delay>(kReceiverProcessingDelay)); + sender_report_id, std::chrono::duration_cast<RtcpReportBlock::Delay>( + kReceiverProcessingDelay)); receiver()->TransmitRtcpFeedbackPacket(); SimulateExecution(kInboundDelay); diff --git a/cast/streaming/session_config.h b/cast/streaming/session_config.h index 4d611b65..f1fc0299 100644 --- a/cast/streaming/session_config.h +++ b/cast/streaming/session_config.h @@ -6,7 +6,7 @@ #define CAST_STREAMING_SESSION_CONFIG_H_ #include <array> -#include <chrono> // NOLINT +#include <chrono> #include <cstdint> #include "cast/streaming/ssrc.h" diff --git a/cast/test/cast_socket_e2e_test.cc b/cast/test/cast_socket_e2e_test.cc index 293e6031..7e1441ea 100644 --- a/cast/test/cast_socket_e2e_test.cc +++ b/cast/test/cast_socket_e2e_test.cc @@ -114,7 +114,8 @@ class ReceiverSocketsClient final class CastSocketE2ETest : public ::testing::Test { public: void SetUp() override { - PlatformClientPosix::Create(milliseconds{10}, milliseconds{0}); + PlatformClientPosix::Create(std::chrono::milliseconds(10), + std::chrono::milliseconds(0)); task_runner_ = PlatformClientPosix::GetInstance()->GetTaskRunner(); sender_router_ = MakeSerialDelete<VirtualConnectionRouter>( diff --git a/discovery/dnssd/impl/dns_data_unittest.cc b/discovery/dnssd/impl/dns_data_unittest.cc index 45118ee8..414f69cc 100644 --- a/discovery/dnssd/impl/dns_data_unittest.cc +++ b/discovery/dnssd/impl/dns_data_unittest.cc @@ -4,7 +4,7 @@ #include "discovery/dnssd/impl/dns_data.h" -#include <chrono> // NOLINT +#include <chrono> #include "discovery/mdns/testing/mdns_test_util.h" #include "gmock/gmock.h" diff --git a/discovery/dnssd/testing/fake_dns_record_factory.h b/discovery/dnssd/testing/fake_dns_record_factory.h index 473ec68e..8c9a80fb 100644 --- a/discovery/dnssd/testing/fake_dns_record_factory.h +++ b/discovery/dnssd/testing/fake_dns_record_factory.h @@ -7,7 +7,7 @@ #include <stdint.h> -#include <chrono> // NOLINT +#include <chrono> #include "discovery/dnssd/impl/constants.h" #include "discovery/mdns/mdns_records.h" diff --git a/discovery/mdns/mdns_probe.cc b/discovery/mdns/mdns_probe.cc index dc911043..5e254aae 100644 --- a/discovery/mdns/mdns_probe.cc +++ b/discovery/mdns/mdns_probe.cc @@ -93,8 +93,7 @@ void MdnsProbeImpl::Postpone(std::chrono::seconds delay) { successful_probe_queries_ = 0; alarm_.Cancel(); - alarm_.ScheduleFromNow([this]() { ProbeOnce(); }, - std::chrono::duration_cast<Clock::duration>(delay)); + alarm_.ScheduleFromNow([this]() { ProbeOnce(); }, Clock::to_duration(delay)); } void MdnsProbeImpl::OnMessageReceived(const MdnsMessage& message) { diff --git a/discovery/mdns/mdns_publisher.cc b/discovery/mdns/mdns_publisher.cc index 51aa30e7..97a72a6c 100644 --- a/discovery/mdns/mdns_publisher.cc +++ b/discovery/mdns/mdns_publisher.cc @@ -371,8 +371,8 @@ void MdnsPublisher::ProcessRecordQueue() { } Clock::duration MdnsPublisher::RecordAnnouncer::GetNextAnnounceDelay() { - return std::chrono::duration_cast<Clock::duration>( - kMinAnnounceDelay * pow(kIntervalIncreaseFactor, attempts_)); + return Clock::to_duration(kMinAnnounceDelay * + pow(kIntervalIncreaseFactor, attempts_)); } } // namespace discovery diff --git a/discovery/mdns/mdns_publisher_unittest.cc b/discovery/mdns/mdns_publisher_unittest.cc index c05019f7..a739a36d 100644 --- a/discovery/mdns/mdns_publisher_unittest.cc +++ b/discovery/mdns/mdns_publisher_unittest.cc @@ -4,7 +4,7 @@ #include "discovery/mdns/mdns_publisher.h" -#include <chrono> // NOLINT +#include <chrono> #include <vector> #include "discovery/common/config.h" @@ -86,8 +86,7 @@ class MdnsPublisherTest : public testing::Test { ~MdnsPublisherTest() { // Clear out any remaining calls in the task runner queue. - clock_.Advance( - std::chrono::duration_cast<Clock::duration>(std::chrono::seconds(1))); + clock_.Advance(Clock::to_duration(std::chrono::seconds(1))); } protected: @@ -360,7 +359,7 @@ TEST_F(MdnsPublisherTest, RegistrationAnnouncesEightTimes) { EXPECT_CALL(probe_manager_, IsDomainClaimed(domain_)) .WillRepeatedly(Return(true)); constexpr Clock::duration kOneSecond = - std::chrono::duration_cast<Clock::duration>(std::chrono::seconds(1)); + Clock::to_duration(std::chrono::seconds(1)); // First announce, at registration. const MdnsRecord record = GetFakeARecord(domain_); diff --git a/discovery/mdns/mdns_records.h b/discovery/mdns/mdns_records.h index 0a1f76ab..b797f329 100644 --- a/discovery/mdns/mdns_records.h +++ b/discovery/mdns/mdns_records.h @@ -6,7 +6,7 @@ #define DISCOVERY_MDNS_MDNS_RECORDS_H_ #include <algorithm> -#include <chrono> // NOLINT +#include <chrono> #include <functional> #include <initializer_list> #include <string> diff --git a/discovery/mdns/mdns_responder.cc b/discovery/mdns/mdns_responder.cc index ebdf91dc..3627f2fd 100644 --- a/discovery/mdns/mdns_responder.cc +++ b/discovery/mdns/mdns_responder.cc @@ -43,7 +43,7 @@ std::chrono::seconds GetTtlForRecordType(DnsType type) { return kSrvRecordTtl; default: OSP_NOTREACHED(); - return std::chrono::seconds{0}; + return std::chrono::seconds(0); } } diff --git a/discovery/mdns/mdns_trackers.cc b/discovery/mdns/mdns_trackers.cc index e2505821..eb1e87fd 100644 --- a/discovery/mdns/mdns_trackers.cc +++ b/discovery/mdns/mdns_trackers.cc @@ -6,6 +6,7 @@ #include <array> #include <limits> +#include <utility> #include "discovery/common/config.h" #include "discovery/mdns/mdns_random.h" @@ -38,7 +39,7 @@ constexpr std::chrono::minutes kMaximumQueryInterval{60}; // A goodbye record is a record with TTL of 0. bool IsGoodbyeRecord(const MdnsRecord& record) { - return record.ttl() == std::chrono::seconds{0}; + return record.ttl() == std::chrono::seconds(0); } bool IsNegativeResponseForType(const MdnsRecord& record, DnsType dns_type) { @@ -284,7 +285,7 @@ Clock::time_point MdnsRecordTracker::GetNextSendTime() { } const Clock::duration delay = - std::chrono::duration_cast<Clock::duration>(record_.ttl() * ttl_fraction); + Clock::to_duration(record_.ttl() * ttl_fraction); return start_time_ + delay; } diff --git a/discovery/mdns/mdns_trackers_unittest.cc b/discovery/mdns/mdns_trackers_unittest.cc index bb80ceb1..0edd8259 100644 --- a/discovery/mdns/mdns_trackers_unittest.cc +++ b/discovery/mdns/mdns_trackers_unittest.cc @@ -22,8 +22,7 @@ namespace discovery { namespace { constexpr Clock::duration kOneSecond = - std::chrono::duration_cast<Clock::duration>(std::chrono::seconds(1)); - + Clock::to_duration(std::chrono::seconds(1)); } using testing::_; @@ -130,8 +129,7 @@ class MdnsTrackerTest : public testing::Test { constexpr double kTtlFractions[] = {0.83, 0.88, 0.93, 0.98, 1.00}; Clock::duration time_passed{0}; for (double fraction : kTtlFractions) { - Clock::duration time_till_refresh = - std::chrono::duration_cast<Clock::duration>(ttl * fraction); + Clock::duration time_till_refresh = Clock::to_duration(ttl * fraction); Clock::duration delta = time_till_refresh - time_passed; time_passed = time_till_refresh; clock_.Advance(delta); @@ -251,8 +249,7 @@ TEST_F(MdnsTrackerTest, RecordTrackerSendsMessage) { return Error::None(); }); - clock_.Advance( - std::chrono::duration_cast<Clock::duration>(a_record_.ttl() * 0.83)); + clock_.Advance(Clock::to_duration(a_record_.ttl() * 0.83)); } TEST_F(MdnsTrackerTest, RecordTrackerNoQueryAfterDestruction) { @@ -274,8 +271,7 @@ TEST_F(MdnsTrackerTest, RecordTrackerUpdateResetsTtl) { expiration_called_ = false; std::unique_ptr<MdnsRecordTracker> tracker = CreateRecordTracker(a_record_); // Advance time by 60% of record's TTL - Clock::duration advance_time = - std::chrono::duration_cast<Clock::duration>(a_record_.ttl() * 0.6); + Clock::duration advance_time = Clock::to_duration(a_record_.ttl() * 0.6); clock_.Advance(advance_time); // Now update the record, this must reset expiration time EXPECT_EQ(tracker->Update(a_record_).value(), @@ -317,17 +313,17 @@ TEST_F(MdnsTrackerTest, RecordTrackerExpirationCallbackAfterGoodbye) { std::unique_ptr<MdnsRecordTracker> tracker = CreateRecordTracker(a_record_); MdnsRecord goodbye_record(a_record_.name(), a_record_.dns_type(), a_record_.dns_class(), a_record_.record_type(), - std::chrono::seconds{0}, a_record_.rdata()); + std::chrono::seconds(0), a_record_.rdata()); // After a goodbye record is received, expiration is schedule in a second. EXPECT_EQ(tracker->Update(goodbye_record).value(), MdnsRecordTracker::UpdateType::kGoodbye); // Advance clock to just before the expiration time of 1 second. - clock_.Advance(std::chrono::microseconds{999999}); + clock_.Advance(std::chrono::microseconds(999999)); EXPECT_FALSE(expiration_called_); // Advance clock to exactly the expiration time. - clock_.Advance(std::chrono::microseconds{1}); + clock_.Advance(std::chrono::microseconds(1)); EXPECT_TRUE(expiration_called_); } @@ -356,7 +352,7 @@ TEST_F(MdnsTrackerTest, RecordTrackerInvalidPositiveRecordUpdate) { // RDATA must match the old RDATA for goodbye records MdnsRecord invalid_rdata(a_record_.name(), a_record_.dns_type(), a_record_.dns_class(), a_record_.record_type(), - std::chrono::seconds{0}, + std::chrono::seconds(0), ARecordRdata(IPAddress{172, 0, 0, 2})); EXPECT_EQ(tracker->Update(invalid_rdata).error(), Error::Code::kParameterInvalid); @@ -420,7 +416,7 @@ TEST_F(MdnsTrackerTest, RecordTrackerUpdateNegativeResponseWithPositive) { tracker = CreateRecordTracker(nsec_record_, DnsType::kA); MdnsRecord aaaa_record(a_record_.name(), DnsType::kAAAA, a_record_.dns_class(), a_record_.record_type(), - std::chrono::seconds{0}, + std::chrono::seconds(0), AAAARecordRdata(IPAddress{0, 0, 0, 0, 0, 0, 0, 1})); result = tracker->Update(aaaa_record); EXPECT_TRUE(result.is_error()); diff --git a/discovery/mdns/public/mdns_constants.h b/discovery/mdns/public/mdns_constants.h index 76a49d1b..fd5f00f4 100644 --- a/discovery/mdns/public/mdns_constants.h +++ b/discovery/mdns/public/mdns_constants.h @@ -429,7 +429,7 @@ constexpr uint8_t kTXTEmptyRdata = 0; // RFC 6762 section 8.1 specifies that a probe should wait 250 ms between // subsequent probe queries. constexpr Clock::duration kDelayBetweenProbeQueries = - std::chrono::duration_cast<Clock::duration>(std::chrono::milliseconds{250}); + Clock::to_duration(std::chrono::milliseconds(250)); // RFC 6762 section 8.1 specifies that the probing phase should send out probe // requests 3 times before treating the probe as completed. diff --git a/docs/style_guide.md b/docs/style_guide.md index db223adc..b3e8a120 100644 --- a/docs/style_guide.md +++ b/docs/style_guide.md @@ -19,18 +19,24 @@ https://chromium-cpp.appspot.com#core-whitelist) guidelines. library only needs to handle threading in very specific places; see [threading.md](threading.md). -## Interacting with std::chrono +## Interacting with `std::chrono` One of the trickier parts of the Open Screen Library is using time and clock functionality provided by `platform/api/time.h`. -- The platform defines aliases in the openscreen namespace for `std::chrono` - types, so they can just be referred to as `hours`, `milliseconds`, etc. +- When working extensively with `std::chrono` types in implementation code, + `util/chrono_helpers.h` header can be included for access to type aliases for + common `std::chrono` types, so they can just be referred to as `hours`, + `milliseconds`, etc. This header also includes helpful conversion functions, + such as `to_milliseconds` instead of + `std::chrono::duration_cast<std::chrono::milliseconds>`. + `util/chrono_helpers.h` cannot be used in headers exposed to embedders, and + this is enforced by DEPS. - `Clock::duration` is defined currently as `std::chrono::microseconds`, and thus is generally not suitable as a time type (developers generally think in - milliseconds). Prefer casting from explicit time types (e.g. - `Clock::duration foo = duration_cast<Clock::duration>(seconds(2))` instead - of using `Clock::duration` types directly. + milliseconds). Prefer casting from explicit time types using + `Clock::to_duration`, e.g. `Clock::to_duration(seconds(2))` + instead of using `Clock::duration` types directly. ## Open Screen Library Features diff --git a/osp/demo/osp_demo.cc b/osp/demo/osp_demo.cc index 9b7604e6..c81ce927 100644 --- a/osp/demo/osp_demo.cc +++ b/osp/demo/osp_demo.cc @@ -644,8 +644,8 @@ int main(int argc, char** argv) { // TODO(jophba): Mac on Mojave hangs on this command forever. openscreen::SetLogFifoOrDie(log_filename); - PlatformClientPosix::Create(std::chrono::milliseconds{50}, - std::chrono::milliseconds{50}); + PlatformClientPosix::Create(std::chrono::milliseconds(50), + std::chrono::milliseconds(50)); if (is_receiver_demo) { OSP_LOG_INFO << "Running publisher demo..."; diff --git a/osp/impl/discovery/mdns/mdns_demo.cc b/osp/impl/discovery/mdns/mdns_demo.cc index ddfd0742..8037a16c 100644 --- a/osp/impl/discovery/mdns/mdns_demo.cc +++ b/osp/impl/discovery/mdns/mdns_demo.cc @@ -361,8 +361,8 @@ int main(int argc, char** argv) { openscreen::osp::ServiceMap services; openscreen::osp::g_services = &services; - PlatformClientPosix::Create(std::chrono::milliseconds{50}, - std::chrono::milliseconds{50}); + PlatformClientPosix::Create(std::chrono::milliseconds(50), + std::chrono::milliseconds(50)); openscreen::osp::BrowseDemo( PlatformClientPosix::GetInstance()->GetTaskRunner(), labels[0], labels[1], diff --git a/osp/impl/presentation/presentation_controller_unittest.cc b/osp/impl/presentation/presentation_controller_unittest.cc index 7e0ca3f2..343ea4d8 100644 --- a/osp/impl/presentation/presentation_controller_unittest.cc +++ b/osp/impl/presentation/presentation_controller_unittest.cc @@ -76,8 +76,8 @@ class MockRequestDelegate final : public RequestDelegate { class ControllerTest : public ::testing::Test { public: ControllerTest() { - fake_clock_ = - std::make_unique<FakeClock>(Clock::time_point(seconds(11111))); + fake_clock_ = std::make_unique<FakeClock>( + Clock::time_point(std::chrono::seconds(11111))); task_runner_ = std::make_unique<FakeTaskRunner>(fake_clock_.get()); quic_bridge_ = std::make_unique<FakeQuicBridge>(task_runner_.get(), FakeClock::now); diff --git a/osp/impl/presentation/url_availability_requester_unittest.cc b/osp/impl/presentation/url_availability_requester_unittest.cc index c1a1fa2c..029ed6c6 100644 --- a/osp/impl/presentation/url_availability_requester_unittest.cc +++ b/osp/impl/presentation/url_availability_requester_unittest.cc @@ -4,7 +4,10 @@ #include "osp/impl/presentation/url_availability_requester.h" +#include <chrono> #include <memory> +#include <utility> +#include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -43,8 +46,8 @@ class MockReceiverObserver : public ReceiverObserver { class UrlAvailabilityRequesterTest : public Test { public: UrlAvailabilityRequesterTest() { - fake_clock_ = - std::make_unique<FakeClock>(Clock::time_point(milliseconds(1298424))); + fake_clock_ = std::make_unique<FakeClock>( + Clock::time_point(std::chrono::milliseconds(1298424))); task_runner_ = std::make_unique<FakeTaskRunner>(fake_clock_.get()); quic_bridge_ = std::make_unique<FakeQuicBridge>(task_runner_.get(), FakeClock::now); @@ -543,7 +546,7 @@ TEST_F(UrlAvailabilityRequesterTest, RefreshWatches) { EXPECT_CALL(mock_observer1, OnReceiverUnavailable(_, service_id_)).Times(0); quic_bridge_->RunTasksUntilIdle(); - fake_clock_->Advance(seconds(60)); + fake_clock_->Advance(std::chrono::seconds(60)); ExpectStreamMessage(&mock_callback_, &request); listener_.RefreshWatches(); @@ -664,7 +667,7 @@ TEST_F(UrlAvailabilityRequesterTest, RemoveObserverInSteps) { quic_bridge_->RunTasksUntilIdle(); EXPECT_EQ((std::vector<std::string>{url2_}), request.urls); - fake_clock_->Advance(seconds(60)); + fake_clock_->Advance(std::chrono::seconds(60)); listener_.RefreshWatches(); EXPECT_CALL(mock_callback_, OnStreamMessage(_, _, _, _, _, _)).Times(0); diff --git a/platform/api/task_runner.h b/platform/api/task_runner.h index e114db68..c061086f 100644 --- a/platform/api/task_runner.h +++ b/platform/api/task_runner.h @@ -5,7 +5,7 @@ #ifndef PLATFORM_API_TASK_RUNNER_H_ #define PLATFORM_API_TASK_RUNNER_H_ -#include <future> // NOLINT +#include <future> #include <utility> #include "platform/api/time.h" diff --git a/platform/api/time.h b/platform/api/time.h index e2b56c6d..dcf24acc 100644 --- a/platform/api/time.h +++ b/platform/api/time.h @@ -30,7 +30,7 @@ class Clock : public TrivialClockTraits { // Note that this is NOT necessarily the same time source as Clock::now() above, // and is NOT guaranteed to be monotonically non-decreasing; it is "calendar // time." -seconds GetWallTimeSinceUnixEpoch() noexcept; +std::chrono::seconds GetWallTimeSinceUnixEpoch() noexcept; } // namespace openscreen diff --git a/platform/api/time_unittest.cc b/platform/api/time_unittest.cc index f4d66fc6..c0328526 100644 --- a/platform/api/time_unittest.cc +++ b/platform/api/time_unittest.cc @@ -4,9 +4,11 @@ #include "platform/api/time.h" +#include <chrono> #include <thread> #include "gtest/gtest.h" +#include "util/chrono_helpers.h" namespace openscreen { namespace { diff --git a/platform/base/ip_address.cc b/platform/base/ip_address.cc index ce34e61a..702219fe 100644 --- a/platform/base/ip_address.cc +++ b/platform/base/ip_address.cc @@ -12,6 +12,7 @@ #include <cstring> #include <iomanip> #include <iterator> +#include <limits> #include <sstream> #include <utility> diff --git a/platform/base/trivial_clock_traits.h b/platform/base/trivial_clock_traits.h index b120e16a..3e5c1fbf 100644 --- a/platform/base/trivial_clock_traits.h +++ b/platform/base/trivial_clock_traits.h @@ -10,16 +10,6 @@ namespace openscreen { -// Common time types used throughout Open Screen. We should always use these -// types for time, if there is ever a namespace collision we have done something -// horribly wrong. -using std::chrono::duration_cast; -using std::chrono::hours; -using std::chrono::microseconds; -using std::chrono::milliseconds; -using std::chrono::nanoseconds; -using std::chrono::seconds; - // The Open Screen monotonic clock traits description, providing all the C++14 // requirements of a TrivialClock, for use with STL <chrono>. class TrivialClockTraits { @@ -34,8 +24,14 @@ class TrivialClockTraits { using time_point = std::chrono::time_point<TrivialClockTraits, duration>; static constexpr bool is_steady = true; + // Helper method for named requirements. + template <typename D> + static constexpr duration to_duration(D d) { + return std::chrono::duration_cast<duration>(d); + } + // Time point values from the clock use microsecond precision, as a reasonably - // high-resoulution clock is required. The time source must tick forward at + // high-resolution clock is required. The time source must tick forward at // least 10000 times per second. using kRequiredResolution = std::ratio<1, 10000>; diff --git a/platform/impl/socket_handle_waiter_posix.h b/platform/impl/socket_handle_waiter_posix.h index a0a1c7cb..ab3fddc3 100644 --- a/platform/impl/socket_handle_waiter_posix.h +++ b/platform/impl/socket_handle_waiter_posix.h @@ -8,7 +8,8 @@ #include <unistd.h> #include <atomic> -#include <mutex> // NOLINT +#include <mutex> +#include <vector> #include "platform/impl/socket_handle_waiter.h" diff --git a/platform/impl/task_runner.h b/platform/impl/task_runner.h index a44e1bd6..65dfbf5e 100644 --- a/platform/impl/task_runner.h +++ b/platform/impl/task_runner.h @@ -8,7 +8,7 @@ #include <condition_variable> // NOLINT #include <map> #include <memory> -#include <mutex> // NOLINT +#include <mutex> #include <thread> #include <utility> #include <vector> diff --git a/platform/impl/task_runner_unittest.cc b/platform/impl/task_runner_unittest.cc index e9810ccb..910cfedb 100644 --- a/platform/impl/task_runner_unittest.cc +++ b/platform/impl/task_runner_unittest.cc @@ -7,17 +7,18 @@ #include <unistd.h> #include <atomic> -#include <thread> // NOLINT +#include <chrono> +#include <string> +#include <thread> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "platform/api/time.h" #include "platform/test/fake_clock.h" - +#include "util/chrono_helpers.h" namespace openscreen { namespace { -using namespace ::testing; using ::testing::_; const auto kTaskRunnerSleepTime = milliseconds(1); diff --git a/platform/impl/text_trace_logging_platform.cc b/platform/impl/text_trace_logging_platform.cc index 1054cef4..e650fa1a 100644 --- a/platform/impl/text_trace_logging_platform.cc +++ b/platform/impl/text_trace_logging_platform.cc @@ -4,8 +4,10 @@ #include "platform/impl/text_trace_logging_platform.h" +#include <limits> #include <sstream> +#include "util/chrono_helpers.h" #include "util/osp_logging.h" namespace openscreen { @@ -32,9 +34,7 @@ void TextTraceLoggingPlatform::LogTrace(const char* name, Clock::time_point end_time, TraceIdHierarchy ids, Error::Code error) { - auto total_runtime = std::chrono::duration_cast<std::chrono::microseconds>( - end_time - start_time) - .count(); + auto total_runtime = to_microseconds(end_time - start_time).count(); constexpr auto microseconds_symbol = "\u03BCs"; // Greek Mu + 's' std::stringstream ss; ss << "TRACE [" << std::hex << ids.root << ":" << ids.parent << ":" diff --git a/platform/impl/time.cc b/platform/impl/time.cc index 33c99947..f4a3e85f 100644 --- a/platform/impl/time.cc +++ b/platform/impl/time.cc @@ -4,9 +4,11 @@ #include "platform/api/time.h" +#include <chrono> #include <ctime> #include <ratio> +#include "util/chrono_helpers.h" #include "util/osp_logging.h" using std::chrono::high_resolution_clock; @@ -36,10 +38,10 @@ Clock::time_point Clock::now() noexcept { // or significant math actually taking place here. if (can_use_steady_clock) { return Clock::time_point( - duration_cast<Clock::duration>(steady_clock::now().time_since_epoch())); + Clock::to_duration(steady_clock::now().time_since_epoch())); } - return Clock::time_point(duration_cast<Clock::duration>( - high_resolution_clock::now().time_since_epoch())); + return Clock::time_point( + Clock::to_duration(high_resolution_clock::now().time_since_epoch())); } std::chrono::seconds GetWallTimeSinceUnixEpoch() noexcept { @@ -55,7 +57,7 @@ std::chrono::seconds GetWallTimeSinceUnixEpoch() noexcept { if (sizeof(std::time_t) <= 4) { constexpr std::time_t a_year_before_overflow = std::numeric_limits<std::time_t>::max() - - duration_cast<seconds>(365 * hours(24)).count(); + to_seconds(365 * hours(24)).count(); OSP_DCHECK_LE(since_epoch, a_year_before_overflow); } diff --git a/platform/impl/time_unittest.cc b/platform/impl/time_unittest.cc index 6ab88560..0ab827a8 100644 --- a/platform/impl/time_unittest.cc +++ b/platform/impl/time_unittest.cc @@ -4,9 +4,11 @@ #include "platform/api/time.h" +#include <chrono> #include <ctime> #include "gtest/gtest.h" +#include "util/chrono_helpers.h" namespace openscreen { diff --git a/platform/impl/timeval_posix.cc b/platform/impl/timeval_posix.cc index 28c25ffe..2a79e681 100644 --- a/platform/impl/timeval_posix.cc +++ b/platform/impl/timeval_posix.cc @@ -6,16 +6,15 @@ #include <chrono> +#include "util/chrono_helpers.h" + namespace openscreen { struct timeval ToTimeval(const Clock::duration& timeout) { struct timeval tv; - const auto whole_seconds = - std::chrono::duration_cast<std::chrono::seconds>(timeout); + const auto whole_seconds = to_seconds(timeout); tv.tv_sec = whole_seconds.count(); - tv.tv_usec = std::chrono::duration_cast<std::chrono::microseconds>( - timeout - whole_seconds) - .count(); + tv.tv_usec = to_microseconds(timeout - whole_seconds).count(); return tv; } diff --git a/platform/impl/udp_socket_reader_posix.h b/platform/impl/udp_socket_reader_posix.h index 2291bd01..fdc06eac 100644 --- a/platform/impl/udp_socket_reader_posix.h +++ b/platform/impl/udp_socket_reader_posix.h @@ -6,7 +6,7 @@ #define PLATFORM_IMPL_UDP_SOCKET_READER_POSIX_H_ #include <map> -#include <mutex> // NOLINT +#include <mutex> #include <vector> #include "platform/api/task_runner.h" @@ -28,7 +28,7 @@ class UdpSocketReaderPosix : public SocketHandleWaiter::Subscriber { // Creates a new instance of this object. // NOTE: The provided NetworkWaiter must outlive this object. explicit UdpSocketReaderPosix(SocketHandleWaiter* waiter); - virtual ~UdpSocketReaderPosix() override; + ~UdpSocketReaderPosix() override; // Waits for |socket| to be readable and then calls the socket's // RecieveMessage(...) method to process the available packet. diff --git a/platform/test/fake_clock.h b/platform/test/fake_clock.h index ce21d250..58efcb4d 100644 --- a/platform/test/fake_clock.h +++ b/platform/test/fake_clock.h @@ -6,7 +6,7 @@ #define PLATFORM_TEST_FAKE_CLOCK_H_ #include <atomic> -#include <thread> // NOLINT +#include <thread> #include <vector> #include "platform/api/time.h" diff --git a/platform/test/trace_logging_helpers.h b/platform/test/trace_logging_helpers.h index 9e04b9b1..382333b6 100644 --- a/platform/test/trace_logging_helpers.h +++ b/platform/test/trace_logging_helpers.h @@ -7,8 +7,11 @@ #ifndef PLATFORM_TEST_TRACE_LOGGING_HELPERS_H_ #define PLATFORM_TEST_TRACE_LOGGING_HELPERS_H_ +#include <chrono> + #include "gmock/gmock.h" #include "platform/base/trace_logging_activation.h" +#include "util/chrono_helpers.h" #include "util/osp_logging.h" namespace openscreen { @@ -60,8 +63,7 @@ void ValidateTraceTimestampDiff(const char* name, Clock::time_point end_time, TraceIdHierarchy ids, Error error) { - const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( - end_time - start_time); + const auto elapsed = to_microseconds(end_time - start_time); ASSERT_GE(static_cast<uint64_t>(elapsed.count()), milliseconds); } diff --git a/util/BUILD.gn b/util/BUILD.gn index b2100346..52f18bd8 100644 --- a/util/BUILD.gn +++ b/util/BUILD.gn @@ -23,6 +23,7 @@ source_set("util") { "alarm.h", "big_endian.cc", "big_endian.h", + "chrono_helpers.h", "crypto/certificate_utils.cc", "crypto/certificate_utils.h", "crypto/digest_sign.cc", diff --git a/util/alarm_unittest.cc b/util/alarm_unittest.cc index 5fad74bf..094afc9c 100644 --- a/util/alarm_unittest.cc +++ b/util/alarm_unittest.cc @@ -5,10 +5,12 @@ #include "util/alarm.h" #include <algorithm> +#include <chrono> #include "gtest/gtest.h" #include "platform/test/fake_clock.h" #include "platform/test/fake_task_runner.h" +#include "util/chrono_helpers.h" namespace openscreen { namespace { @@ -26,7 +28,7 @@ class AlarmTest : public testing::Test { }; TEST_F(AlarmTest, RunsTaskAsClockAdvances) { - constexpr Clock::duration kDelay = std::chrono::milliseconds(20); + constexpr Clock::duration kDelay = milliseconds(20); const Clock::time_point alarm_time = FakeClock::now() + kDelay; Clock::time_point actual_run_time{}; @@ -61,12 +63,12 @@ TEST_F(AlarmTest, RunsTaskImmediately) { ASSERT_EQ(expected_run_time, actual_run_time); // Confirm the lambda is only run once. - clock()->Advance(std::chrono::seconds(2)); + clock()->Advance(seconds(2)); ASSERT_EQ(expected_run_time, actual_run_time); } TEST_F(AlarmTest, CancelsTaskWhenGoingOutOfScope) { - constexpr Clock::duration kDelay = std::chrono::milliseconds(20); + constexpr Clock::duration kDelay = milliseconds(20); constexpr Clock::time_point kNever{}; Clock::time_point actual_run_time{}; @@ -85,7 +87,7 @@ TEST_F(AlarmTest, CancelsTaskWhenGoingOutOfScope) { } TEST_F(AlarmTest, Cancels) { - constexpr Clock::duration kDelay = std::chrono::milliseconds(20); + constexpr Clock::duration kDelay = milliseconds(20); const Clock::time_point alarm_time = FakeClock::now() + kDelay; Clock::time_point actual_run_time{}; @@ -104,8 +106,8 @@ TEST_F(AlarmTest, Cancels) { } TEST_F(AlarmTest, CancelsAndRearms) { - constexpr Clock::duration kShorterDelay = std::chrono::milliseconds(10); - constexpr Clock::duration kLongerDelay = std::chrono::milliseconds(100); + constexpr Clock::duration kShorterDelay = milliseconds(10); + constexpr Clock::duration kLongerDelay = milliseconds(100); // Run the test twice: Once when scheduling first with a long delay, then a // shorter delay; and once when scheduling first with a short delay, then a diff --git a/util/chrono_helpers.h b/util/chrono_helpers.h new file mode 100644 index 00000000..a3711bbe --- /dev/null +++ b/util/chrono_helpers.h @@ -0,0 +1,50 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_CHRONO_HELPERS_H_ +#define UTIL_CHRONO_HELPERS_H_ + +#include <chrono> + +// This file is a collection of helpful utilities and using statement for +// working with std::chrono. In practice we previously defined these frequently, +// this header allows for a single set of convenience statements. +namespace openscreen { + +using hours = std::chrono::hours; +using microseconds = std::chrono::microseconds; +using milliseconds = std::chrono::milliseconds; +using nanoseconds = std::chrono::nanoseconds; +using seconds = std::chrono::seconds; + +// Casting statements. Note that duration_cast is not a type, it's a function, +// so its behavior is different than the using statements above. +template <typename D> +static constexpr hours to_hours(D d) { + return std::chrono::duration_cast<hours>(d); +} + +template <typename D> +static constexpr microseconds to_microseconds(D d) { + return std::chrono::duration_cast<microseconds>(d); +} + +template <typename D> +static constexpr milliseconds to_milliseconds(D d) { + return std::chrono::duration_cast<milliseconds>(d); +} + +template <typename D> +static constexpr nanoseconds to_nanoseconds(D d) { + return std::chrono::duration_cast<nanoseconds>(d); +} + +template <typename D> +static constexpr seconds to_seconds(D d) { + return std::chrono::duration_cast<seconds>(d); +} + +} // namespace openscreen + +#endif // UTIL_CHRONO_HELPERS_H_ |