1 // Copyright 2019 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "cast/streaming/ntp_time.h" 6 7 #include "util/osp_logging.h" 8 9 namespace openscreen { 10 namespace cast { 11 12 namespace { 13 14 // The number of seconds between 1 January 1900 and 1 January 1970. 15 constexpr NtpSeconds kTimeBetweenNtpEpochAndUnixEpoch{INT64_C(2208988800)}; 16 17 } // namespace 18 NtpTimeConverter(Clock::time_point now,std::chrono::seconds since_unix_epoch)19NtpTimeConverter::NtpTimeConverter(Clock::time_point now, 20 std::chrono::seconds since_unix_epoch) 21 : start_time_(now), 22 since_ntp_epoch_( 23 std::chrono::duration_cast<NtpSeconds>(since_unix_epoch) + 24 kTimeBetweenNtpEpochAndUnixEpoch) {} 25 26 NtpTimeConverter::~NtpTimeConverter() = default; 27 ToNtpTimestamp(Clock::time_point time_point) const28NtpTimestamp NtpTimeConverter::ToNtpTimestamp( 29 Clock::time_point time_point) const { 30 const Clock::duration time_since_start = time_point - start_time_; 31 const auto whole_seconds = 32 std::chrono::duration_cast<NtpSeconds>(time_since_start); 33 const auto remainder = 34 std::chrono::duration_cast<NtpFraction>(time_since_start - whole_seconds); 35 return AssembleNtpTimestamp(since_ntp_epoch_ + whole_seconds, remainder); 36 } 37 ToLocalTime(NtpTimestamp timestamp) const38Clock::time_point NtpTimeConverter::ToLocalTime(NtpTimestamp timestamp) const { 39 auto ntp_seconds = NtpSecondsPart(timestamp); 40 // Year 2036 wrap-around check: If the NTP timestamp appears to be a 41 // point-in-time before 1970, assume the 2036 wrap-around has occurred, and 42 // adjust to compensate. 43 if (ntp_seconds <= kTimeBetweenNtpEpochAndUnixEpoch) { 44 constexpr NtpSeconds kNtpSecondsPerEra{INT64_C(1) << 32}; 45 ntp_seconds += kNtpSecondsPerEra; 46 } 47 48 const auto whole_seconds = ntp_seconds - since_ntp_epoch_; 49 const auto seconds_since_start = 50 Clock::to_duration(whole_seconds) + start_time_; 51 const auto remainder = Clock::to_duration(NtpFractionPart(timestamp)); 52 return seconds_since_start + remainder; 53 } 54 55 } // namespace cast 56 } // namespace openscreen 57