Optimal code/algorithm to convert frame count to timecode?

4.3k Views Asked by At

I am searching for optimal sourcecode/algorithm in c++ to convert frames count into time code hh:mm:ss:ff in given fps, ex. 25fps...

this code is preety good - http://www.andrewduncan.ws/Timecodes/Timecodes.html (bottom of page) but it is expensive - it contains 4 mod and 6 div operations

I need to show time code on every frame, so calculating this algorithm could take some time.

I can of course store evaluated timecode to avoid calculations.

But it would be very helpful to know better algorithm...

thanks in advance yours m.

4

There are 4 best solutions below

0
perreal On

First of all, the question might better be optimal code for conversion between seconds to hours, minutes, seconds. At this point, if frames come in order, you can simply use addition to increase the previous time.

0
Evgeny Kluev On

Mod and div operations (to a small constant value) may be effectively performed with multiplication to some precalculated reciprocal. So they are not expensive.

0
Derek On

First off, I agree with everyone else that you probably don't need to optimize this, unless you are specifically seeing problems. However, since it's entertaining to try to find ways to, I'll give you something I saw at first glance to reduce the number of divides.

seconds = framenumber div 30
minutes = seconds div 60
hours = minutes div 60
frames = frameNumber mod 30
seconds = seconds mod 60
minutes = minutes mod 60
hours = hours mod 24

It's more lines of code, but fewer divides. Basically, since seconds, minutes and hours use some of the same math, I use the results from one in the formula for the next.

0
John R. Strohm On

General rule of thumb: In image-processing systems, which include video players, you sweat blood over the operations that run once per pixel, then you sweat over the operations that run once per image "patch" (typically a line of pixels), and you don't sweat the stuff that runs once per frame.

The reason is that the per-pixel stuff will run hundreds, maybe thousands, of times as often as the per-patch stuff, and the per-patch stuff will run hundreds, maybe thousands, of times as often as the per-frame stuff.

This means that the per-pixel stuff may run millions of times as often as the per-frame stuff. One instruction per pixel may cost millions of instructions per frame, and a few hundred, or even a few thousand, instructions per frame is lost in the noise floor against the per-pixel instruction counts.

In other words, you can probably afford the mods and divs.

Having said that, it MIGHT be reasonable to run custom counters instead of doing mods and divs.