/*
    Project  : H.264 encoder test    
    Module   : PSNR functions

    Author   : Marko 'Fador' Viitanen

    Date     : 29/6/2009
    Modified : 29/6/2009

*/

#include <math.h>
#include "common.h"

#define MAX (255*255)

//Calculates image PSNR value
double imagePSNR(uint8 *frame1, uint8 *frame2, uint32 x, uint32 y)
{   
    double MSE=0.0;
    double MSEtemp=0.0;
    double psnr=0.0;
    uint32 index;

    //Calculate MSE
    for(index=0;index<x*y;index++)
    {
        MSEtemp=abs(frame1[index]-frame2[index]);
        MSE+=MSEtemp*MSEtemp;
    }
    MSE/=x*y;

    //Avoid division by zero
    if(MSE==0) return 99.0;

    //The PSNR
    psnr=10*log10(MAX/MSE);

    //Thats it.
    return psnr;
}

//Sum of Absolute Difference for block
uint32 SAD(uint8 *block,uint8* block2, uint32 x, uint32 y)
{
    uint32 i;
    uint32 sum=0;
    for(i=0;i<x*y;i+=4)
    {
        sum+=abs(block[i]-block2[i]);
        sum+=abs(block[i+1]-block2[i+1]);
        sum+=abs(block[i+2]-block2[i+2]);
        sum+=abs(block[i+3]-block2[i+3]);
    }

    return sum;    
}

