哪些CMTime为无效类型?CMTime无效的定义与判定方式
Great question—this is a super common pitfall when working with Core Media's CMTime struct, so let's break it down thoroughly.
What does "invalid" mean for a CMTime?
An invalid CMTime is any instance that cannot represent a valid, usable time value. This isn't just one scenario—it covers:
- Uninitialized instances (like the all-zero
kCMTimeInvalid) - Values that represent infinite time (which can't be used in standard time calculations)
- Instances where the internal fields create a mathematically invalid state (like a zero timescale, which would cause division by zero when calculating the actual time value)
- Numeric overflow cases where the
valueandtimescalecombination can't resolve to a meaningful time.
Other Invalid CMTime Types Beyond kCMTimeInvalid
While kCMTimeInvalid is the most well-known invalid instance, there are several others you need to be aware of:
kCMTimePositiveInfinity: Represents a positive infinite time value—this can't be used as a valid, finite time in most Core Media operations.kCMTimeNegativeInfinity: The negative counterpart of the above, also an invalid finite time.- CMTime instances with a
timescaleof 0: SinceCMTimecalculates time asvalue / timescale, a zero timescale makes this calculation mathematically impossible, so these instances are considered invalid. - Overflowed CMTime values: If the combination of
valueandtimescaleresults in a value that's outside the range of what can be represented (e.g., a value that's too large to fit in the underlying integer type), this also counts as invalid.
Why You Can't Use time == kCMTimeInvalid for Validity Checks
As you noted, kCMTimeInvalid has all its fields set to 0—you can create batches of these with calloc or by zero-filling a struct. However, this is only one specific invalid state. The other invalid instances we listed have completely different field values, so a direct equality check will miss them entirely. For example, kCMTimePositiveInfinity doesn't match kCMTimeInvalid at all, but it's still an invalid time that your code needs to handle.
The Correct Way to Check for Invalid CMTime
Apple explicitly recommends using the CMTIME_IS_INVALID(time) macro for validity checks. This macro internally checks all the conditions that define an invalid CMTime—including all the cases we covered above—so it's the only reliable way to determine if a CMTime instance is usable.
内容的提问来源于stack exchange,提问作者allenlinli

