Bug 1852754: part 9) Add tests for dynamically loading <link rel="prefetch"> elements...
[gecko.git] / dom / media / TimeUnits.h
blobd8dba4b8e6f17cf0d9e168955193e88b6fd9724e
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef TIME_UNITS_H
8 #define TIME_UNITS_H
10 #include <limits>
11 #include <type_traits>
13 #include "Intervals.h"
14 #include "mozilla/CheckedInt.h"
15 #include "mozilla/FloatingPoint.h"
16 #include "mozilla/Maybe.h"
17 #include "mozilla/TimeStamp.h"
18 #include "mozilla/IntegerPrintfMacros.h"
19 #include "nsPrintfCString.h"
21 namespace mozilla::media {
22 class TimeIntervals;
23 } // namespace mozilla::media
24 // CopyChooser specialization for nsTArray
25 template <>
26 struct nsTArray_RelocationStrategy<mozilla::media::TimeIntervals> {
27 using Type =
28 nsTArray_RelocateUsingMoveConstructor<mozilla::media::TimeIntervals>;
31 namespace mozilla {
33 // Number of milliseconds per second. 1e3.
34 static const int64_t MSECS_PER_S = 1000;
36 // Number of microseconds per second. 1e6.
37 static const int64_t USECS_PER_S = 1000000;
39 // Number of nanoseconds per second. 1e9.
40 static const int64_t NSECS_PER_S = 1000000000;
42 namespace media {
44 #ifndef PROCESS_DECODE_LOG
45 # define PROCESS_DECODE_LOG(sample) \
46 MOZ_LOG(sPDMLog, mozilla::LogLevel::Verbose, \
47 ("ProcessDecode: mDuration=%" PRIu64 "µs ; mTime=%" PRIu64 \
48 "µs ; mTimecode=%" PRIu64 "µs", \
49 (sample)->mDuration.ToMicroseconds(), \
50 (sample)->mTime.ToMicroseconds(), \
51 (sample)->mTimecode.ToMicroseconds()))
52 #endif // PROCESS_DECODE_LOG
54 // TimeUnit is a class that represents a time value, that can be negative or
55 // positive.
57 // Internally, it works by storing a numerator (the tick numbers), that uses
58 // checked arithmetics, and a denominator (the base), that is a regular integer
59 // on which arithmetics is never performed, and is only set at construction, or
60 // replaced.
62 // Dividing the tick count by the base always yields a value in seconds,
63 // but it's very useful to have a base that is dependant on the context: it can
64 // be the sample-rate of an audio stream, the time base of an mp4, that's often
65 // 90000 because it's divisible by 24, 25 and 30.
67 // Keeping time like this allows performing calculations on time values with
68 // maximum precision, without having to have to care about rounding errors or
69 // precision loss.
71 // If not specified, the base is 1e6, representing microseconds, for historical
72 // reasons. Users can gradually move to more precise representations when
73 // needed.
75 // INT64_MAX has the special meaning of being +∞, and INT64_MIN means -∞. Any
76 // other value corresponds to a valid time.
78 // If an overflow or other problem occurs, the underlying CheckedInt<int64_t> is
79 // invalid and a crash is triggered.
80 class TimeUnit final {
81 public:
82 constexpr TimeUnit(CheckedInt64 aTicks, int64_t aBase)
83 : mTicks(aTicks), mBase(aBase) {
84 MOZ_RELEASE_ASSERT(mBase > 0);
87 explicit constexpr TimeUnit(CheckedInt64 aTicks)
88 : mTicks(aTicks), mBase(USECS_PER_S) {}
90 // Return the maximum number of ticks that a TimeUnit can contain.
91 static constexpr int64_t MaxTicks() {
92 return std::numeric_limits<int64_t>::max() - 1;
95 // This is only precise up to a point, which is aValue * aBase <= 2^53 - 1
96 static TimeUnit FromSeconds(double aValue, int64_t aBase = USECS_PER_S);
97 static constexpr TimeUnit FromMicroseconds(int64_t aValue) {
98 return TimeUnit(aValue, USECS_PER_S);
100 static TimeUnit FromHns(int64_t aValue, int64_t aBase) {
101 // Truncating here would mean a loss of precision.
102 return TimeUnit::FromNanoseconds(aValue * 100).ToBase<RoundPolicy>(aBase);
104 static constexpr TimeUnit FromNanoseconds(int64_t aValue) {
105 return TimeUnit(aValue, NSECS_PER_S);
107 static TimeUnit FromInfinity();
108 static TimeUnit FromNegativeInfinity();
109 static TimeUnit FromTimeDuration(const TimeDuration& aDuration);
110 static constexpr TimeUnit Zero(int64_t aBase = USECS_PER_S) {
111 return TimeUnit(0, aBase);
113 static constexpr TimeUnit Zero(const TimeUnit& aOther) {
114 return TimeUnit(0, aOther.mBase);
116 static TimeUnit Invalid();
117 int64_t ToMilliseconds() const;
118 int64_t ToMicroseconds() const;
119 int64_t ToNanoseconds() const;
120 int64_t ToTicksAtRate(int64_t aRate) const;
121 double ToSeconds() const;
122 nsCString ToString() const;
123 TimeDuration ToTimeDuration() const;
124 bool IsInfinite() const;
125 bool IsPositive() const;
126 bool IsPositiveOrZero() const;
127 bool IsZero() const;
128 bool IsNegative() const;
130 // Returns true if the fractions are equal when converted to the smallest
131 // base.
132 bool EqualsAtLowestResolution(const TimeUnit& aOther) const;
133 // Strict equality -- the fractions must be exactly equal
134 bool operator==(const TimeUnit& aOther) const;
135 bool operator!=(const TimeUnit& aOther) const;
136 bool operator>=(const TimeUnit& aOther) const;
137 bool operator>(const TimeUnit& aOther) const;
138 bool operator<=(const TimeUnit& aOther) const;
139 bool operator<(const TimeUnit& aOther) const;
140 TimeUnit operator%(const TimeUnit& aOther) const;
141 TimeUnit operator+(const TimeUnit& aOther) const;
142 TimeUnit operator-(const TimeUnit& aOther) const;
143 TimeUnit& operator+=(const TimeUnit& aOther);
144 TimeUnit& operator-=(const TimeUnit& aOther);
145 template <typename T>
146 TimeUnit operator*(T aVal) const {
147 // See bug 853398 for the reason to block double multiplier.
148 // If required, use MultDouble below and with caution.
149 static_assert(std::is_integral_v<T>, "Must be an integral type");
150 return TimeUnit(mTicks * aVal, mBase);
152 TimeUnit MultDouble(double aVal) const;
153 friend TimeUnit operator/(const TimeUnit& aUnit, int64_t aVal) {
154 MOZ_DIAGNOSTIC_ASSERT(0 <= aVal && aVal <= UINT32_MAX);
155 return TimeUnit(aUnit.mTicks / aVal, aUnit.mBase);
157 friend TimeUnit operator%(const TimeUnit& aUnit, int64_t aVal) {
158 MOZ_DIAGNOSTIC_ASSERT(0 <= aVal && aVal <= UINT32_MAX);
159 return TimeUnit(aUnit.mTicks % aVal, aUnit.mBase);
162 struct TruncatePolicy {
163 template <typename T>
164 static T policy(T& aValue) {
165 return static_cast<T>(aValue);
169 struct RoundPolicy {
170 template <typename T>
171 static T policy(T& aValue) {
172 return std::round(aValue);
176 template <class RoundingPolicy = TruncatePolicy>
177 TimeUnit ToBase(int64_t aTargetBase) const {
178 double dummy = 0.0;
179 return ToBase<RoundingPolicy>(aTargetBase, dummy);
182 template <class RoundingPolicy = TruncatePolicy>
183 TimeUnit ToBase(const TimeUnit& aTimeUnit) const {
184 double dummy = 0.0;
185 return ToBase<RoundingPolicy>(aTimeUnit, dummy);
188 // Allow returning the same value, in a base that matches another TimeUnit.
189 template <class RoundingPolicy = TruncatePolicy>
190 TimeUnit ToBase(const TimeUnit& aTimeUnit, double& aOutError) const {
191 int64_t targetBase = aTimeUnit.mBase;
192 return ToBase<RoundingPolicy>(targetBase, aOutError);
195 template <class RoundingPolicy = TruncatePolicy>
196 TimeUnit ToBase(int64_t aTargetBase, double& aOutError) const {
197 aOutError = 0.0;
198 CheckedInt<int64_t> ticks = mTicks * aTargetBase;
199 if (ticks.isValid()) {
200 imaxdiv_t rv = imaxdiv(ticks.value(), mBase);
201 if (!rv.rem) {
202 return TimeUnit(rv.quot, aTargetBase);
205 double approx = static_cast<double>(mTicks.value()) *
206 static_cast<double>(aTargetBase) /
207 static_cast<double>(mBase);
208 double integer;
209 aOutError = modf(approx, &integer);
210 return TimeUnit(AssertedCast<int64_t>(RoundingPolicy::policy(approx)),
211 aTargetBase);
214 bool IsValid() const;
216 constexpr TimeUnit() = default;
218 TimeUnit(const TimeUnit&) = default;
220 TimeUnit& operator=(const TimeUnit&) = default;
222 bool IsPosInf() const;
223 bool IsNegInf() const;
225 // Allow serializing a TimeUnit via IPC
226 friend IPC::ParamTraits<mozilla::media::TimeUnit>;
228 #ifndef VISIBLE_TIMEUNIT_INTERNALS
229 private:
230 #endif
231 int64_t ToCommonUnit(int64_t aRatio) const;
232 // Reduce a TimeUnit to the smallest possible ticks and base. This is useful
233 // to comparison with big time values that can otherwise overflow.
234 TimeUnit Reduced() const;
236 CheckedInt64 mTicks{0};
237 // Default base is microseconds.
238 int64_t mBase{USECS_PER_S};
241 using NullableTimeUnit = Maybe<TimeUnit>;
243 using TimeInterval = Interval<TimeUnit>;
245 // A set of intervals, containing TimeUnit.
246 class TimeIntervals : public IntervalSet<TimeUnit> {
247 public:
248 using BaseType = IntervalSet<TimeUnit>;
249 using InnerType = TimeUnit;
251 // We can't use inherited constructors yet. So we have to duplicate all the
252 // constructors found in IntervalSet base class.
253 // all this could be later replaced with:
254 // using IntervalSet<TimeUnit>::IntervalSet;
256 // MOZ_IMPLICIT as we want to enable initialization in the form:
257 // TimeIntervals i = ... like we would do with IntervalSet<T> i = ...
258 MOZ_IMPLICIT TimeIntervals(const BaseType& aOther) : BaseType(aOther) {}
259 MOZ_IMPLICIT TimeIntervals(BaseType&& aOther) : BaseType(std::move(aOther)) {}
260 explicit TimeIntervals(const BaseType::ElemType& aOther) : BaseType(aOther) {}
261 explicit TimeIntervals(BaseType::ElemType&& aOther)
262 : BaseType(std::move(aOther)) {}
264 static TimeIntervals Invalid() {
265 return TimeIntervals(TimeInterval(TimeUnit::FromNegativeInfinity(),
266 TimeUnit::FromNegativeInfinity()));
268 bool IsInvalid() const {
269 return Length() == 1 && Start(0).IsNegInf() && End(0).IsNegInf();
272 // Returns the same interval, with a given base resolution.
273 TimeIntervals ToBase(const TimeUnit& aBase) const {
274 TimeIntervals output;
275 for (const auto& interval : mIntervals) {
276 TimeInterval convertedInterval{interval.mStart.ToBase(aBase),
277 interval.mEnd.ToBase(aBase),
278 interval.mFuzz.ToBase(aBase)};
279 output += convertedInterval;
281 return output;
284 // Returns the same interval, with a microsecond resolution. This is used to
285 // compare TimeUnits internal to demuxers (that use a base from the container)
286 // to floating point numbers in seconds from content.
287 TimeIntervals ToMicrosecondResolution() const {
288 TimeIntervals output;
290 for (const auto& interval : mIntervals) {
291 TimeInterval reducedPrecision{interval.mStart.ToBase(USECS_PER_S),
292 interval.mEnd.ToBase(USECS_PER_S),
293 interval.mFuzz.ToBase(USECS_PER_S)};
294 output += reducedPrecision;
296 return output;
299 nsCString ToString() const {
300 nsCString dump;
301 for (const auto& interval : mIntervals) {
302 dump += nsPrintfCString("[%s],", interval.ToString().get());
304 return dump;
307 TimeIntervals() = default;
310 using TimeRange = Interval<double>;
312 // A set of intervals, containing doubles that are seconds.
313 class TimeRanges : public IntervalSet<double> {
314 public:
315 using BaseType = IntervalSet<double>;
316 using InnerType = double;
317 using nld = std::numeric_limits<double>;
319 // We can't use inherited constructors yet. So we have to duplicate all the
320 // constructors found in IntervalSet base class.
321 // all this could be later replaced with:
322 // using IntervalSet<TimeUnit>::IntervalSet;
324 // MOZ_IMPLICIT as we want to enable initialization in the form:
325 // TimeIntervals i = ... like we would do with IntervalSet<T> i = ...
326 MOZ_IMPLICIT TimeRanges(const BaseType& aOther) : BaseType(aOther) {}
327 MOZ_IMPLICIT TimeRanges(BaseType&& aOther) : BaseType(std::move(aOther)) {}
328 explicit TimeRanges(const BaseType::ElemType& aOther) : BaseType(aOther) {}
329 explicit TimeRanges(BaseType::ElemType&& aOther)
330 : BaseType(std::move(aOther)) {}
332 static TimeRanges Invalid() {
333 return TimeRanges(TimeRange(-nld::infinity(), nld::infinity()));
335 bool IsInvalid() const {
336 return Length() == 1 && Start(0) == -nld::infinity() &&
337 End(0) == nld::infinity();
339 // Convert from TimeUnit-based intervals to second-based TimeRanges.
340 explicit TimeRanges(const TimeIntervals& aIntervals) {
341 for (const auto& interval : aIntervals) {
342 Add(TimeRange(interval.mStart.ToSeconds(), interval.mEnd.ToSeconds()));
346 TimeRanges ToMicrosecondResolution() const;
348 TimeRanges() = default;
351 } // namespace media
352 } // namespace mozilla
354 #endif // TIME_UNITS_H