Showing posts with label Video. Show all posts
Showing posts with label Video. Show all posts

Sunday, August 14, 2011

Rounding up!

Right shifting of positive integers leads to truncation:

9 >> 1
4
9 >> 2
2

Interestingly, right shift for negative integers also leads to truncation:

-9 >> 1
-5
-9 >> 2
-3

If we combine the effects, we can get rounding up during right shift for positive integers:

-(-9 >> 1)
5
-(-9 >> 2)
3

So here is a C function for rounding up while shifting:

int rightShiftRoundUp(int x, int n){
    return - ( -x >> n);
}

Voila!

Monday, August 8, 2011

Clamping short to unsigned char

Here is a standard video processing problems. Your 8-bit pixel values are typically in the range 0-255. If you do some processing on them which lead their values of this range you need to bring them down to this range. Negative values are clamped to 0 while positive values greater than 255 are clamped to 255.

A typical unoptimized implementation looks like follows.

  1: unsigned char clamp(short value){
  2:   if (value < 0) return 0;
  3:   if (value > 0xff) return 0xff;
  4:   return value;
  5: }


After long time, today I ended up seeing a much nicer implementation in FFmpeg code base which basically looks like:.






  1: const unsigned char clamp(int a)
  2: {
  3:   if (a&(~0xFF)) return (-a)>>31;
  4:   else return a;
  5: } 






And I think, with a single if statement, its wonderful!