# Simplified understanding of CMTime

Posted by Farooq Nasim Ahmad on January 11, 2019

Floating point arithmetic requires more processing than integer arithmetic on embedded processors even when floating point units are available. Simpler embedded processor supports only integer math and to emulate floating point requires significant processing overhead. The alternative is fixed point math.

A very simple concept is that you can convert any given floating point number into a corresponding integer number by multiplying it with a large number. Example: We want to add two numbers 0.1 and 0.33. We may multiply both numbers with 100 and obtain 10 and 33. The output after addition is 43. After doing all required arithmetic operations on 10 and 33 we can convert final result back by dividing it again by 100. In above example 43/100 = 0.43. In short we can define a fractional number in form of an integer by defining a combination of an integer value like 10 and 33 and a timescale in this case it is 100.

This is just an over simplified example to get the bigger concept. Fixed-point math typically takes the form of a larger integer number, for instance 16 bits, where the most significant eight bits are the integer part and the least significant eight bits are the fractional part.

There is no fixed-point library available in C. However, Apple has provided CMTime structure. It is usually used in developing video and audio applications. Similar to fixed point numbers a CMTime is represented as a rational number, with a numerator (an int64_t value), and a denominator (an int32_t timescale). AVFoundation objects such as AVPlayer and AVAssetReader use CMTime to talk about time, and there's plenty more where that came from.

``````CMTime CMTimeMakeWithSeconds (
Float64 seconds,
int32_t preferredTimeScale
);
``````

With above function, any time value given in seconds can be represented as ratio of a scaled value and given time scale. If time in second is 5 and time scale is 1000.

``CMTimeMakeWithSeconds(5,1000)``

The output will be (5000,1000) in CMTime that will make 5000/1000 = 5 seconds. Same value of CMTime can be generated by another function.

``````CMTime CMTimeMake(int64_t value, int32_t timescale)
``````
``````CMTimeMake (5000,1000)
``````

A smaller time scale will result in low precision while performing addition and subtraction operations. In order to perform high precision calculations, the time scale should be significantly large value. Apple recommends time scale of 600 for videos. A good time scale for audio files is equal to audio frequency like 441000 in case of 44.1 KHz file.