Search This Blog

Tuesday, May 26, 2015

Convert Video Frames To Milliseconds


convert frames to milliseconds

those familiar with video are also likely familiar with frame rates (number of frames per second) and timecode. sometimes, it is necessary to convert a certain number of frames value and/or a timecode value into standard seconds and milliseconds values for stream conditioning via NPT values, etc. 

let's take a look at the math required to do this sort of conversion. i like to use python, but you can use a calculator or maybe another repl for your favorite programming language to follow along.

in the following example, our video source file has a frame rate commonly referred to as "60 FPS", but more technically referred to as 59.94. we would like to calculate a more exact frame rate, determine how many milliseconds each frame occupies, and then see how many milliseconds are occupied by 3 frames as a simple usage example.

here we go!

Python 2.7.3 (default, Feb 13 2013, 16:44:35) 
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.24)] on darwin.
Type "help", "copyright", "credits" or "%magic" for more information.

>>> 60/1.001 # calculate more exact frames per second more on this here:
59.940059940059946

>>> # there are 1000 milliseconds in 1 second

>>> # so how many milliseconds does each frame occupy?

>>> 1000 / (60 / 1.001) # milliseconds in 1 second divided by frames per second
16.68333333333333

>>> # so how many milliseconds are occupied by 3 frames?

>>> 3 * (1000/(60 / 1.001))
50.04999999999999

>>> # convert the above value back to seconds (underscore in python refers to last output)

>>> _ * .001
0.05004999999999999

>>> # now that we have the understanding, let's wrap this up into a simple function:

>>> def ftoms(f, r):
...    return (f * (1000 / (r / 1.001))) * .001

>>> # now let's run some tests with our new frames to milliseconds converter:

>>> ftoms(1, 60)
0.016683333333333331

>>> ftoms(3, 60)
0.05004999999999999

>>> ftoms(1, 30)
0.033366666666666663

>>> ftoms(1, 24)
0.041708333333333326

>>> ftoms(24, 24)
1.0009999999999999

>>> ftoms(30, 30)
1.0009999999999999

>>> ftoms(60, 60)
1.0009999999999999

>>> exit

and there you have it. granted, the function above is only applicable to 59.94, 29.97, and 23.98 frame rates, but it could easily be modified to account for 25, 24, and 30 frame rates. 
i hope this helps someone else in videoland!
cheers!
ryanlmcmurray