该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
这里给出具体的区间变换公式(假设原区间为a..b,0和1的概率分别为p和1-p):
左边区间: a..[(b - a) * p]
右边区间: [(b - a) * p + 1]..b
使用这两个公式替换掉上面代码中的等分区间部分,就得到了算术编码的算法,下面我们给出一个完整的算术编码的源代码,里面世包含了一个上下文长度为3字节的0-1概率预测模型:
(为了代码编写方便,我将计算区间的代码放在了预测模型中,也就是说现在的预测模型功能是:输入区间的上下边界,模型根据预测计算出区间的划分点)
#include
#include
#include
// # prediction model
// #############################################################################
typedef struct model_type_struct
{
unsigned char* m_count[2];
unsigned int m_context;
} model_type;
void model_init(model_type* model)
{
model->m_count[0] = malloc(sizeof(unsigned char) * (1 <
model->m_count[1] = malloc(sizeof(unsigned char) * (1 <
memset(model->m_count[0], 0, sizeof(unsigned char) * (1 <
memset(model->m_count[1], 0, sizeof(unsigned char) * (1 <
return;
}
void model_destroy(model_type* model)
{
free(model->m_count[0]);
free(model->m_count[1]);
return;
}
unsigned short model_predict(model_type* model, unsigned short lo_val, unsigned short hi_val)
{
unsigned char count[2] =
{
1 + model->m_count[0][model->m_context % (1 <
1 + model->m_count[1][model->m_context % (1 <
};
return lo_val + (hi_val - lo_val) * count[0] / (count[0] + count[1]);
}
void model_update(model_type* model, int bit)
{
if((model->m_count[bit][model->m_context % (1 <= 255)
{
// avoid overflow
model->m_count[0][model->m_context % (1 <
model->m_count[1][model->m_context % (1 <