Search code examples
objective-cios8cmtime

CMTimeClampToRange() doesn't seem to return a CMTime that's inside the given range


I have the following code in my project:

CMTimeRange clipRange = clip.range;
CMTime clipTime = CMTimeClampToRange(editor.currentClipTime, clipRange);

According to the documentation, CMTimeClampToRange() should behave like:

For a given CMTime and CMTimeRange, returns the nearest CMTime inside that time range.

However, when I add this:

assert(CMTimeRangeContainsTime(clipRange, clipTime));

The assertion fails. The documentation for CMTimeRangeContainsTime() states:

Indicates whether a time is contained within a time range.

I would assume that inside and within mean the same, but apparently it doesn't; is there an elegant way to clamp a CMTime in a range so that it satisfies CMTimeRangeContainsTime()?


Solution

  • I've worked out the following hack:

    clipTime = CMTimeMaximum(clipRange.start, CMTimeSubtract(clipTime, CMTimeMake(1, clipTime.timescale)));
    

    Basically, it subtracts the smallest non-empty timespan within the same timescale from the clamped time and makes sure we don't yield a negative value.