test_05:JPEG file decode

一:实验原理

1.JPEG编码原理

JPEG 是Joint Photographic Experts Group(联合图像专家小组)的缩写,是第一个国际图像压缩标准。
.jpeg/.jpg是最常用的图像文件格式,是一种有损压缩格式。JPEG 编码框图如下图所示:

(1)零偏置level offset

对于灰度级是2n的像素,通过减去2n-1,将无符号的整数值变成有符号数;
对于n=8,即将0~255的值域,通过减去128,转换为值域在-128~127之间的值。这样做的目的是: 使像素的绝对值出现3位10进制的概率大大减少。

(2)8x8 DCT变换

DCT变换是指 对每个单独的彩色图像分量,把整个分量图像分成8×8的图像块,再以8x8的图像块为一个单位进行量化和编码处理。我们可以利用DCT变换去相关的特性,去除冗余信息,提高编码效率。

(3)量化

我们可以通过量化减少数据的编码位数,提高编码效率;
因为人眼对亮度信号比对色差信号更敏感,因此使用了两种量化表:亮度量化值和色差量化值;   
根据人眼的视觉特性 (对低频敏感,对高频不太敏感)对低频分量采取较细的量化,对高频分量采取较粗的量化

(4)DC系数差分编码

8×8图像块经过DCT变换之后得到的DC直流系数有两个特点:系数的数值比较大和相邻8×8图像块的DC系数值变化不大:冗余;
根据这个特点, JPEG算法使用了差分脉冲调制编码(DPCM)技术,对相邻图像块之间量化DC系数的差值DIFF进行编码:
对DIFF进行Huffman编码。

5AC系数的之字形扫描

由于经DCT变换后,系数大多数集中在左上角,即低频分量区,因此采用Z字形按频率的高低顺序读出,可以出现很多连零的机会。可以使用游程编码。尤其在最后,如果都是零,给出EOB (End of Block)即可。zigzag扫描如下图:

(6)AC系数游程编码

在经过之字形扫描排序后的AC系数,存在很多连0。为了进一步提高编码效率,因此对AC系数进行游程编码(RLC)处理之后,再进一步进行Huffman编码。

(7)将进行处理之后的AC和DC系数,送到Huffman编码器分别进行Huffman编码

JPEG中共采用了四张Huffman码表:亮度DC、亮度AC、色度DC、色度AC,即分别对图像的亮度和色度,直流和交流数据进行编码处理。


2.JPEG文件格式分析

(1)segment的组织形式

EG 在文件中以 Segment 的形式组织,它具有以下特点:
均以 0xFF 开始,后跟 1 byte 的 Marker 和 2 byte 的 Segment length(包含表示Length 本身所占用的 2 byte,不含“ 0xFF” + “ Marker” 所占用的 2 byte);
采用 Motorola 序(相对于 Intel 序),即保存时高位在前,低位在后;
Data 部分中, 0xFF 后若为 0x00,则跳过此字节不予处理;

(2)文件格式分析

下面,我们通过对一个具体的JPEG文件格式的分析,来了解相关marker:


FFD8:SOI, Start of Image,图像开始 
所有的JPEG文件都必须以SOI开始。


FFE0:Application,应用程序保留标记 0
length: 16 byte (2 byte)----00 10
标识符: JFIF (5 byte)----4A 46 49 46 00
Version: 0101 (2 byte)----01 01
Units: 01 (1 byte) X and Y are dots per inch----01
Xdensity: 96 (2 bytes) Horizontal pixel density(水平方向点密度)----00 60
Ydensity:96 (2 bytes) Vertical pixel density(垂直方向点密度)---- 00 60
缩略图水平像素数目: 00 (1 byte)----00
缩略图垂直像素数目: 00 (1 byte)----00
缩略图 24bitRGB 点数目: 缩略图水平像素数目 * 缩略图垂直像素数目 = 00


FFDB:DQT, Define Quantization Table,定义量化表
length: 67 byte (2 byte)----00 43
QT information - precision: 00 (Higher 4 bit) (8 bit)
QT information - index: 00 (Lower 4 bit)----00
qt_table:从08一直到下一个FFDB之前,为量化表的64个量化值

下一个 FFDB定义了第二个量化表,这里不再赘述。

FFC0 : SOF0 , Start of Frame, 基线离散余弦变换
length: 17 byte (2 byte)----0 0 11
图像精度(每个数据样本的位数) : 8----08
Image Height: 900 (2 byte)----03 84
Image Width: 1440 (2 byte)----05 A0
颜色分量数: 03( YCrCb) (1 byte)----03
颜色分量 ID: 01 (1 byte) (Y)----01
SampRate_Y_H: 10 (Higher 4 bit)
SampRate_Y_V: 10 (Lower 4 bit)----22
Y QtTableID: 00 (1 byte)----00
颜色分量 ID: 02 (1 byte) (U)----02
SampRate_U_H: 01 (Higher 4 bit)
SampRate_U_V: 01 (Lower 4 bit)----11
U QtTableID: 01 (1 byte)----01
颜色分量 ID: 03 (1 byte) (V)----03
SampRate_V_H: 01 (Higher 4 bit)
SampRate_V_V: 01 (Lower 4 bit)----11
V QtTableID: 01 (1 byte)----01


FFC4: DHT, Define Huffman Table,定义 Huffman 树表
length: 31byte (2 byte)----00 1F
Huffman 表类型: 0 (Higher 4 bit) (DC)
Huffman 表 ID: 0 (Lower 4 bit) (0 号表)----00
HuffmanTableIndex: 0
code_len_table:16bytes
剩下的是各码字对应的权值。
后面的三个FFC4分别为AC0号表,DC1号表,AC1号表,这里不再赘述。

FFDA: SOS, Start of Scan,扫描开始
length: 12 byte (2 byte)----00 0C
颜色分量数:3(1byte)----03
颜色分量 ID: 1 (1 byte) (Y)----01
Y Dc HuffmanTreeIndex: 0 (Higher 4 bit)
Y Ac HuffmanTreeIndex: 0(Lower 4 bit)----00
颜色分量 ID: 2 (1 byte) (U or V)----02
UV Dc HuffmanTreeIndex: 1 (Higher 4 bit)
UV Ac HuffmanTreeIndex: 1 (Lower 4 bit)----11
颜色分量 ID: 3 (1 byte) (U or V)----03
UV Dc HuffmanTreeIndex: 1 (Higher 4 bit)
UV Ac HuffmanTreeIndex: 1(Lower 4 bit)----11
谱选择开始 1 byte---- 固定值 0x00
谱选择结束 1 byte---- 固定值 0x3F
谱选择 1 byte---- 在基本 JPEG 中总为 00


二:JPEG解码流程

JPEG解码流程为编码的逆过程,具体流程如下所示:
1 .读取文件

2. 解析 Segment Marker
2.1 解析 SOI
2.2 解析 APP0
 检查标识“ JFIF”及版本
 得到一些参数
2.3 解析 DQT
 得到量化表长度(可能包含多张量化表)
 得到量化表的精度
 得到及检查量化表的序号(只能是 0 —— 3)
 得到量化表内容( 64 个数据)
2.4 解析 SOF0
 得到每个 sample 的比特数、长宽、颜色分量数
 得到每个颜色分量的 ID、水平采样因子、垂直采样因子、使用的量化表序号(与 DQT 中序号对应)
2.5 解析 DHT
 得到 Huffman 表的类型( AC、 DC)、序号
 依据数据重建 Huffman 表
2.6 解析 SOS
 得到解析每个颜色分量的 DC、 AC 值所使用的 Huffman 表序号(与 DHT中序号对应)

3.依据每个分量的水平、垂直采样因子计算 MCU 的大小,并得到每个 MCU 中 8*8宏块的个数

4 .对每个 MCU 解码(依照各分量水平、垂直采样因子对 MCU 中每个分量宏块解码)
4.1 对每个宏块进行 Huffman 解码,得到 DCT 系数
4.2 对每个宏块的 DCT 系数进行 IDCT,得到 Y、 Cb、 Cr
4.3 遇到 Segment Marker RST 时,清空之前的 DC DCT 系数

5 .解析到 EOI,解码结束

6.将 Y、 Cb、 Cr 转化为需要的色彩空间并保存。

三:关键代码分析

JPEG解码程序工程文件目录如下:

该JPEG解码系统,是按照分层设计的思想组织。因此这里我们按照调试的顺序,通过数据流的走向对整个系统的各个模块进行分析。因此为了更好地描述整个系统,我们在tinyjpeg_internal文件中定义了三个结构体:

struct huffman_table(Huffman码表结构体)

[cpp]  view plain  copy
  1. struct huffman_table  
  2. {  
  3.   /* Fast look up table, using HUFFMAN_HASH_NBITS bits we can have directly the symbol, 
  4.    * if the symbol is <0, then we need to look into the tree table */  
  5.   short int lookup[HUFFMAN_HASH_SIZE];//快速查找到权值对应的码字  
  6.   /* code size: give the number of bits of a symbol is encoded */  
  7.   unsigned char code_size[HUFFMAN_HASH_SIZE];//码长对应的权值  
  8.   /* some place to store value that is not encoded in the lookup table 
  9.    * FIXME: Calculate if 256 value is enough to store all values 
  10.    */  
  11.   uint16_t slowtable[16-HUFFMAN_HASH_NBITS][256];  
  12. };  


struct component (8*8宏块结构体)

[cpp]  view plain  copy
  1. <span style="font-weight: normal;">struct component   
  2.   
  3. {  
  4.   unsigned int Hfactor;//水平采样因子  
  5.   unsigned int Vfactor;//垂直采样因子  
  6.   float *Q_table; //指向该宏块使用的量化表  
  7.   struct huffman_table *AC_table;//指向该宏块直流系数的Huffman码表  
  8.   struct huffman_table *DC_table;//指向该宏块交流系数的Huffman码表  
  9.   short int previous_DC; /* Previous DC coefficient *///前一个块的DC系数  
  10.   short int DCT[64]; /* DCT coef *///该块的DCT系数,其中DCT[0]为该块直流,其他为交流  
  11. #if SANITY_CHECK  
  12.   unsigned int cid;  
  13. #endif  
  14. };</span>  

struct jdec_private(文件解码信息结构体)

[cpp]  view plain  copy
  1. struct jdec_private(文件解码信息结构体)  
  2.   
  3. {  
  4.   /* Public variables */  
  5.   uint8_t *components[COMPONENTS];//分别指向YUV分量结构体的指针数组  
  6.   unsigned int width, height; /* Size of the image *///图像的宽高  
  7.   unsigned int flags;  
  8.    
  9.   /* Private variables */  
  10.   const unsigned char *stream_begin, *stream_end;//文件流的开始和结束  
  11.   unsigned int stream_length;//文件流的长度  
  12.    
  13.   const unsigned char *stream; /* Pointer to the current stream *///指向当前文件流的指针  
  14.   unsigned int reservoir, nbits_in_reservoir;  
  15.    
  16.   struct component component_infos[COMPONENTS];//  
  17.   float Q_tables[COMPONENTS][64]; //对YUV进行量化的量化表  
  18.   struct huffman_table HTDC[HUFFMAN_TABLES]; //DC系数编码的Huffman码表  
  19.   struct huffman_table HTAC[HUFFMAN_TABLES]; //AC系数编码的Huffman码表  
  20.   int default_huffman_table_initialized;  
  21.   int restart_interval;  
  22.   int restarts_to_go; /* MCUs left in this restart interval */  
  23.   int last_rst_marker_seen; /* Rst marker is incremented each time *///固定增长  
  24.    
  25.   /* Temp space used after the IDCT to store each components */  
  26.   uint8_t Y[64*4], Cr[64], Cb[64];//反DCT之后存三个分量的数组  
  27.    
  28.   jmp_buf jump_state;  
  29.   /* Internal Pointer use for colorspace conversion, do not modify it !!! */  
  30.   uint8_t *plane[COMPONENTS];  
  31.    
  32. };  


1.读取文件

在命令行中,我们设置了输入的JPEG文件,输出的文件和输出格式:
主函数main函数中,我们打开对输入输出文件,并解析了输出格式:
[cpp]  view plain  copy
  1. int main(int argc, char *argv[])  
  2. {  
  3.   int output_format = TINYJPEG_FMT_YUV420P;//将输出格式初始化为yuv420P  
  4.   char *output_filename, *input_filename;//定义输入文件和输出文件指针  
  5.   clock_t start_time, finish_time;  
  6.   unsigned int duration;  
  7.   int current_argument;  
  8.   int benchmark_mode = 0;  
  9.   
  10. #if TRACE//TRACE=1,则中间代码会编译,TRACE=0,则会忽略  
  11.   p_trace=fopen(TRACEFILE,"w");  
  12.   if (p_trace==NULL)  
  13.   {  
  14.       printf("trace file open error!");  
  15.   }  
  16. #endif  
  17.   if (argc < 3)  
  18.     usage();  
  19.   
  20.   current_argument = 1;  
  21.   while (1)  
  22.    {  
  23.      if (strcmp(argv[current_argument], "--benchmark")==0)//字符比较,若输入了基准模式benchmark,则加1  
  24.        benchmark_mode = 1;  
  25.      else  
  26.        break;//否则跳出  
  27.      current_argument++;  
  28.    }  
  29.   
  30.   if (argc < current_argument+2)  
  31.     usage();  
  32.   
  33.   input_filename = argv[current_argument];//输入文件指针指向第一个文件  
  34.   if (strcmp(argv[current_argument+1],"yuv420p")==0)  
  35.     output_format = TINYJPEG_FMT_YUV420P;  
  36.   else if (strcmp(argv[current_argument+1],"rgb24")==0)  
  37.     output_format = TINYJPEG_FMT_RGB24;  
  38.   else if (strcmp(argv[current_argument+1],"bgr24")==0)  
  39.     output_format = TINYJPEG_FMT_BGR24;  
  40.   else if (strcmp(argv[current_argument+1],"grey")==0)  
  41.     output_format = TINYJPEG_FMT_GREY;//确认文件输出格式  
  42.   /*add by yangyulan*/  
  43.   else if (strcmp(argv[current_argument+1],"yuvone")==0)  
  44.     output_format =TINYJPEG_FMT_YUV420one;  
  45.   /*end by yangyulan*/  
  46.   else  
  47.     exitmessage("Bad format: need to be one of yuv420p, rgb24, bgr24, grey,yuvone\n");  
  48.   output_filename = argv[current_argument+2];//输出文件指针指向第三个文件  
其中通过在系统各处添加trace,通过初始化trace的值,可以在需要的时候输出一些中间结果。

根据数据走向,整个JPEG解码过程,都是由下面的covert_one函数实现:
[cpp]  view plain  copy
  1. if (benchmark_mode)  
  2.    load_multiple_times(input_filename, output_filename, output_format);  
  3.  else  
  4.    convert_one_image(input_filename, output_filename, output_format);//调用convert函数  
在convert_one_image函数中,我们进行了以下解码处理。
[cpp]  view plain  copy
  1. int convert_one_image(const char *infilename, const char *outfilename, int output_format)  
  2. {  
  3.   FILE *fp;//定义了一个文件指针  
  4.   unsigned int length_of_file;//保存文件大小  
  5.   unsigned int width, height;//保存图像宽高  
  6.   unsigned char *buf;//缓冲区  
  7.   struct jdec_private *jdec;  
  8.   unsigned char *components[3];//定义三个字符数组  
  9.   
  10.   /* 把文件中的数据读如缓存中*/  
  11.   fp = fopen(infilename, "rb");//以只读的形式读取输入文件  
  12.   if (fp == NULL)  
  13.     exitmessage("Cannot open filename\n");  
  14.   length_of_file = filesize(fp);//得到文件大小  
  15.   buf = (unsigned char *)malloc(length_of_file + 4);//为存文件数据申请内存  
  16.   if (buf == NULL)  
  17.     exitmessage("Not enough memory for loading file\n");  
  18.   fread(buf, length_of_file, 1, fp);//将文件里面的jpg数据读到buf中  
  19.   fclose(fp);//关闭文件指针  
  20.   
  21.   /* 解压缩*/  
  22.   jdec = tinyjpeg_init();//初始化解压缩成一块表和数组的结构体  
  23.   if (jdec == NULL)  
  24.     exitmessage("Not enough memory to alloc the structure need for decompressing\n");  
  25.   
  26.   if (<strong><span style="color:#ff0000;">tinyjpeg_parse_header(jdec, buf, length_of_file</span></strong>)<0)//tinyjpeg_parse_header函数在tinyjpeg.c中  
  27.     exitmessage(tinyjpeg_get_errorstring(jdec));  
  28.   
  29.   /* Get the size of the image */  
  30.   tinyjpeg_get_size(jdec, &width, &height);//获取图像的大小  
  31.   
  32.   snprintf(error_string, sizeof(error_string),"Decoding JPEG image...\n");  
  33.   if (<strong><span style="color:#ff0000;">tinyjpeg_decode</span></strong>(jdec, output_format) < 0)  
  34.     exitmessage(tinyjpeg_get_errorstring(jdec));  
  35.   
  36.   /*  
  37.    * Get address for each plane (not only max 3 planes is supported), and 
  38.    * depending of the output mode, only some components will be filled  
  39.    * RGB: 1 plane, YUV420P: 3 planes, GREY: 1 plane 
  40.    */  
  41.   tinyjpeg_get_components(jdec, components);  
  42.   
  43.   /* 按所要求的个数输出文件*/  
  44.   switch (output_format)  
  45.    {  
  46.     case TINYJPEG_FMT_RGB24:  
  47.     case TINYJPEG_FMT_BGR24:  
  48.       write_tga(outfilename, output_format, width, height, components);  
  49.       break;  
  50.     case TINYJPEG_FMT_YUV420P:  
  51.       write_yuv(outfilename, width, height, components);  
  52.       break;  
  53.     case TINYJPEG_FMT_GREY:  
  54.       write_pgm(outfilename, width, height, components);  
  55.       break;  
  56.    }  
  57.   
  58.   /* Only called this if the buffers were allocated by tinyjpeg_decode() */  
  59.   tinyjpeg_free(jdec);  
  60.   /* else called just free(jdec); */  
  61.   
  62.   free(buf);  
  63.   return 0;  
[cpp]  view plain  copy
  1. }  
任务一:将输出文件保存为可供YUVViewer观看的YUV文件。
1.在命令行将输出格式设为要求的格式(yuv),格式名称自定义。

2.在main函数中,条件判断属于哪一格式输出。
[cpp]  view plain  copy
  1. if (strcmp(argv[current_argument+1],"yuv420p")==0)  
  2.    output_format = TINYJPEG_FMT_YUV420P;  
  3.  else if (strcmp(argv[current_argument+1],"rgb24")==0)  
  4.    output_format = TINYJPEG_FMT_RGB24;  
  5.  else if (strcmp(argv[current_argument+1],"bgr24")==0)  
  6.    output_format = TINYJPEG_FMT_BGR24;  
  7.  else if (strcmp(argv[current_argument+1],"grey")==0)  
  8.    output_format = TINYJPEG_FMT_GREY;//确认文件输出格式  
3.在convert_one_image函数中,进行格式判断,并调用相应的输出函数。
[cpp]  view plain  copy
  1. /* Save it */  
  2. switch (output_format)  
  3.  {  
  4.   case TINYJPEG_FMT_RGB24:  
  5.   case TINYJPEG_FMT_BGR24:  
  6.     write_tga(outfilename, output_format, width, height, components);  
  7.     break;  
  8.   case TINYJPEG_FMT_YUV420P:  
  9.     write_yuv(outfilename, width, height, components);  
  10.     break;  
  11.   case TINYJPEG_FMT_GREY:  
  12.     write_pgm(outfilename, width, height, components);  
  13.     break;  
  14.  }  
4.这里输出为yuv,调用write_yuv函数
[cpp]  view plain  copy
  1. static void write_yuv(const char *filename, int width, int height, unsigned char **components)  
  2. {  
  3. FILE *F;  
  4.  char temp[1024];  
  5.   
  6.  snprintf(temp, 1024, "%s.yuv", filename);  
  7.  F = fopen(temp, "ab");  
  8.  fwrite(components[0], width, height, F);  
  9.  fclose(F);  
  10.  snprintf(temp, 1024, "%s.yuv", filename);  
  11.  F = fopen(temp, "ab");   
  12.  fwrite(components[1], width*height/4, 1, F);  
  13.  fclose(F);  
  14.  snprintf(temp, 1024, "%s.yuv", filename);  
  15.  F = fopen(temp, "ab");  
  16.  fwrite(components[2], width*height/4, 1, F);  
  17.  fclose(F);  
  18.  printf("ok");  
  19. }  

2.解析 Segment Marker(tinyjpeg_parse_header中)

tinyjpeg_parse_header函数:

[cpp]  view plain  copy
  1. int tinyjpeg_parse_header(struct jdec_private *priv, const unsigned char *buf, unsigned int size)  
  2. {  
  3.   int ret;  
  4.   
  5.   /* Identify the file */  
  6.   if ((buf[0] != 0xFF) || (buf[1] != SOI))//文件开头是0xFF,D8即SOI文件开始标志,开始不是FFD8则报错  
  7.     snprintf(error_string, sizeof(error_string),"Not a JPG file ?\n");  
  8.   
  9.   priv->stream_begin = buf+2;//没错则将文件流的开始向后移两个字节  
  10.   priv->stream_length = size-2;//将剩余长度也减两个字节  
  11.   priv->stream_end = priv->stream_begin + priv->stream_length;//定位到文件最后  
  12.   
  13.   ret = <strong><span style="color:#ff0000;">parse_JFIF</span></strong>(priv, priv->stream_begin);  
  14.   
  15.   return ret;  
  16. }  

其中的parse_JFIF函数的作用便是解析文件头:

[cpp]  view plain  copy
  1. static int parse_JFIF(struct jdec_private *priv, const unsigned char *stream)//解析JFIF  
  2. {  
  3.   int chuck_len;  
  4.   int marker;  
  5.   int sos_marker_found = 0;  
  6.   int dht_marker_found = 0;  
  7.   const unsigned char *next_chunck;  
  8.   
  9.   
  10.   /* Parse marker */  
  11.   while (!sos_marker_found)//循环一直读到扫描开始,即编码数据块  
  12.    {  
  13.      if (*stream++ != 0xff)  
  14.        goto bogus_jpeg_format;  
  15.      /* Skip any padding ff byte (this is normal) */  
  16.      while (*stream == 0xff)  
  17.        stream++;  
  18.   
  19.      marker = *stream++;//E0赋值给marker,E0==APP0  
  20.      chuck_len = be16_to_cpu(stream);  
  21.      next_chunck = stream + chuck_len;  
  22.      switch (marker)  
  23.       {  
  24.        case SOF:  
  25.      if (<strong><span style="color:#ff0000;">parse_SOF</span></strong>(priv, stream) < 0)  
  26.        return -1;  
  27.      break;  
  28.        case DQT:  
  29.      if (<strong><span style="color:#ff0000;">parse_DQT</span></strong>(priv, stream) < 0)  
  30.        return -1;  
  31.      break;  
  32.        case SOS:  
  33.      if (<span style="color:#ff0000;"><strong>parse_SOS</strong></span>(priv, stream) < 0)  
  34.        return -1;  
  35.      sos_marker_found = 1;  
  36.      break;  
  37.        case DHT:  
  38.      if (<span style="color:#ff0000;"><strong>parse_DHT</strong></span>(priv, stream) < 0)  
  39.        return -1;  
  40.      dht_marker_found = 1;  
  41.      break;  
  42.        case DRI:  
  43.      if (parse_DRI(priv, stream) < 0)  
  44.        return -1;  
  45.      break;  
  46.        default:  
  47. #if TRACE  
  48.     fprintf(p_trace,"> Unknown marker %2.2x\n", marker);  
  49.     fflush(p_trace);  
  50. #endif  
  51.      break;  
  52.       }  
  53.   
  54.      stream = next_chunck;//跳到下一个数据块,再判断  
  55.    }  
  56.   
  57.   if (!dht_marker_found) {  
  58. #if TRACE  
  59.       fprintf(p_trace,"No Huffman table loaded, using the default one\n");  
  60.       fflush(p_trace);  
  61. #endif  
  62.     build_default_huffman_tables(priv);  
  63.   }  
  64.   
  65. #ifdef SANITY_CHECK  
  66.   if (   (priv->component_infos[cY].Hfactor < priv->component_infos[cCb].Hfactor)  
  67.       || (priv->component_infos[cY].Hfactor < priv->component_infos[cCr].Hfactor))  
  68.     snprintf(error_string, sizeof(error_string),"Horizontal sampling factor for Y should be greater than horitontal sampling factor for Cb or Cr\n");  
  69.   if (   (priv->component_infos[cY].Vfactor < priv->component_infos[cCb].Vfactor)  
  70.       || (priv->component_infos[cY].Vfactor < priv->component_infos[cCr].Vfactor))  
  71.     snprintf(error_string, sizeof(error_string),"Vertical sampling factor for Y should be greater than vertical sampling factor for Cb or Cr\n");  
  72.   if (   (priv->component_infos[cCb].Hfactor!=1)   
  73.       || (priv->component_infos[cCr].Hfactor!=1)  
  74.       || (priv->component_infos[cCb].Vfactor!=1)  
  75.       || (priv->component_infos[cCr].Vfactor!=1))  
  76.     snprintf(error_string, sizeof(error_string),"Sampling other than 1x1 for Cr and Cb is not supported");  
  77. #endif  
  78.   
  79.   return 0;  
  80. bogus_jpeg_format:  
  81. #if TRACE  
  82.   fprintf(p_trace,"Bogus jpeg format\n");  
  83.   fflush(p_trace);  
  84. #endif  
  85.   return -1;  
  86. }  
parse SOI:
[cpp]  view plain  copy
  1. if ((buf[0] != 0xFF) || (buf[1] != SOI))//文件开头是0xFF,D8即SOI文件开始标志,开始不        是FFD8则报错  
  2.    snprintf(error_string, sizeof(error_string),"Not a JPG file ?\n");  

parse_DQT函数:定义量化表

得到量化表长度(可能包含多张量化表)
得到量化表的精度
得到及检查量化表的序号(只能是 0 —— 3)
得到量化表内容( 64 个数据)
[cpp]  view plain  copy
  1. //解析量化表  
  2. static int parse_DQT(struct jdec_private *priv, const unsigned char *stream)  
  3. {  
  4.   int qi;  
  5.   /*add by yangyulan*/  
  6.   
  7.   /*end by yangyulan*/  
  8.   float *table;//定义了用于指向量化表的指针  
  9.   const unsigned char *dqt_block_end;//指向量化表的结束地址  
  10. #if TRACE  
  11.   fprintf(p_trace,"> DQT marker\n");  
  12.   fflush(p_trace);  
  13. #endif  
  14.   dqt_block_end = stream + be16_to_cpu(stream);//量化块结束的位置  
  15.   stream += 2;  /* Skip length */  //跳过两字节的存储长度,如00 43  
  16.   
  17.   while (stream < dqt_block_end)//当还在表内  
  18.    {  
  19.      qi = *stream++;//将量化表中的值逐个赋给qi  
  20. #if SANITY_CHECK  
  21.      if (qi>>4)  
  22.        snprintf(error_string, sizeof(error_string),"16 bits quantization table is not supported\n");  
  23.      if (qi>4)  
  24.        snprintf(error_string, sizeof(error_string),"No more 4 quantization table is supported (got %d)\n", qi);  
  25. #endif  
  26.      table = priv->Q_tables[qi];//初始化量化表  
  27.      build_quantization_table(table, stream);//得到量化表内容,将文档数据流赋值给量化表  
  28.      stream += 64;//指向下一块  
  29.    }  

build_quantization_table函数:

[cpp]  view plain  copy
  1. static void build_quantization_table(float *qtable, const unsigned char *ref_table)  
  2. {  
  3.   int i, j;  
  4.   static const double aanscalefactor[8] = {//比例因子  
  5.      1.0, 1.387039845, 1.306562965, 1.175875602,  
  6.      1.0, 0.785694958, 0.541196100, 0.275899379  
  7.   };  
  8.   const unsigned char *zz = zigzag;//zigzag为之字形扫描顺序系数  
  9.   for (i=0; i<8; i++) {  
  10.      for (j=0; j<8; j++) {  
  11.        *qtable++ = ref_table[*zz++] * aanscalefactor[i] * aanscalefactor[j];  
  12.      }  
  13.    }  
  14. }  

Zigzag数组:

[cpp]  view plain  copy
  1. static const unsigned char zigzag[64] = //定义之字形扫描顺序  
  2. {  
  3.    0,  1,  5,  6, 14, 15, 27, 28,  
  4.    2,  4,  7, 13, 16, 26, 29, 42,  
  5.    3,  8, 12, 17, 25, 30, 41, 43,  
  6.    9, 11, 18, 24, 31, 40, 44, 53,  
  7.   10, 19, 23, 32, 39, 45, 52, 54,  
  8.   20, 22, 33, 38, 46, 51, 55, 60,  
  9.   21, 34, 37, 47, 50, 56, 59, 61,  
  10.   35, 36, 48, 49, 57, 58, 62, 63  
  11. };  
任务二:输出量化表到TXT文件:
在解析量化表之后,我们可以中间输出量化表到txt文件中:即在parse_DQT函数的后面添加如下代码:
[cpp]  view plain  copy
  1. /*add by yangyulan*/  
  2.   /*for--print DQT into qfile.txt*/  
  3.   qfile=fopen("q_file.txt","ab");  
  4.   fputs("量化表",qfile);  
  5.   fputc(10,qfile);  
  6.   for( i=0;i<8;i++)  
  7.   {  
  8.       for(j=0;j<8;j++)  
  9.       {  
  10.             fprintf(qfile,"%f",*table);  
  11.             table++;  
  12.       }  
  13.       fputc(10,qfile);  
  14.         
  15.   }  
  16.     
  17.   fclose(qfile);  
  18.   /*end by yangyulan*/  



parse_SOF函数:

得到每个 sample 的比特数、长宽、颜色分量数;得到每个颜色分量的 ID、水平采样因子、垂直采样因子、使用的量化表序号(与 DQT 中序号对应)。

[cpp]  view plain  copy
  1. static int parse_SOF(struct jdec_private *priv, const unsigned char *stream)//基线余弦变换  
  2. {  
  3.   int i, width, height, nr_components, cid, sampling_factor;  
  4.   int Q_table;  
  5.   struct component *c;  
  6. #if TRACE  
  7.   fprintf(p_trace,"> SOF marker\n");  
  8.   fflush(p_trace);  
  9. #endif  
  10.   print_SOF(stream);//打印SOF,即获得图像宽高和图像精度,并打印出来  
  11.   
  12.   height = be16_to_cpu(stream+3);//获得图像高度  
  13.   width  = be16_to_cpu(stream+5);//获得图像宽度  
  14.   nr_components = stream[7];//获得图像精度  
  15. #if SANITY_CHECK  
  16.   if (stream[2] != 8)  
  17.     snprintf(error_string, sizeof(error_string),"Precision other than 8 is not supported\n");  
  18.   if (width>JPEG_MAX_WIDTH || height>JPEG_MAX_HEIGHT)  
  19.     snprintf(error_string, sizeof(error_string),"Width and Height (%dx%d) seems suspicious\n", width, height);  
  20.   if (nr_components != 3)  
  21.     snprintf(error_string, sizeof(error_string),"We only support YUV images\n");  
  22.   if (height%16)  
  23.     snprintf(error_string, sizeof(error_string),"Height need to be a multiple of 16 (current height is %d)\n", height);  
  24.   if (width%16)  
  25.     snprintf(error_string, sizeof(error_string),"Width need to be a multiple of 16 (current Width is %d)\n", width);  
  26. #endif  
  27.   stream += 8;//分别解析YUV分量  
  28.   for (i=0; i<nr_components; i++) {  
  29.      cid = *stream++;//该分量ID  
  30.      sampling_factor = *stream++;//该分量的采样率  
  31.      Q_table = *stream++;//该分量的量化表  
  32.      c = &priv->component_infos[i];//指向该分量的结构体指针  
  33. #if SANITY_CHECK  
  34.      c->cid = cid;  
  35.      if (Q_table >= COMPONENTS)  
  36.        snprintf(error_string, sizeof(error_string),"Bad Quantization table index (got %d, max allowed %d)\n", Q_table, COMPONENTS-1);  
  37. #endif  
  38.      c->Vfactor = sampling_factor&0xf;//该分量的垂直采样率  
  39.      c->Hfactor = sampling_factor>>4;//水平采样率  
  40.      c->Q_table = priv->Q_tables[Q_table];//该分量使用的量化表  
  41. #if TRACE  
  42.      fprintf(p_trace,"Component:%d  factor:%dx%d  Quantization table:%d\n",  
  43.            cid, c->Hfactor, c->Hfactor, Q_table );  
  44.      fflush(p_trace);  
  45. #endif  
  46.   
  47.   }  
  48.   priv->width = width;//宽高的信息  
  49.   priv->height = height;  
  50. #if TRACE  
  51.   fprintf(p_trace,"< SOF marker\n");  
  52.   fflush(p_trace);  
  53. #endif  
  54.   
  55.   return 0;  
  56. }  


解析DHT的函数 parse_DHT:得到 Huffman 表的类型( AC、 DC)、序号

[cpp]  view plain  copy
  1. static int parse_DHT(struct jdec_private *priv, const unsigned char *stream)//解析Huffman码表  
  2. {  
  3.   unsigned int count, i;  
  4.   unsigned char huff_bits[17];//码长从1到16的数目数组  
  5.   int length, index;  
  6.   /*add by yangyulan*/  
  7.   FILE *hufftable;  
  8.   hufftable=fopen("huffmantable_file.txt","ab");   
  9.   /*end by yangyulan*/  
  10.   
  11.   length = be16_to_cpu(stream) - 2;//得到码长(可能包含多张表)  
  12.   stream += 2;  /* Skip length */  
  13. #if TRACE  
  14.   fprintf(p_trace,"> DHT marker (length=%d)\n", length);  
  15.   fflush(p_trace);  
  16. #endif  
  17.   
  18.   while (length>0) {//如果码长大于0  
  19.      index = *stream++;//把该块赋值给index  
  20.   
  21.      /* We need to calculate the number of bytes 'vals' will takes */  
  22.      huff_bits[0] = 0;//码长为0的为0个,下标与码长相对应  
  23.      count = 0;//总码字数  
  24.      for (i=1; i<17; i++) {  
  25.     huff_bits[i] = *stream++;//各码长的个数分别赋值  
  26.     count += huff_bits[i];//总的码字数  
  27.      }  
  28. #if SANITY_CHECK  
  29.      if (count >= HUFFMAN_BITS_SIZE)  
  30.        snprintf(error_string, sizeof(error_string),"No more than %d bytes is allowed to describe a huffman table", HUFFMAN_BITS_SIZE);  
  31.      if ( (index &0xf) >= HUFFMAN_TABLES)  
  32.        snprintf(error_string, sizeof(error_string),"No more than %d Huffman tables is supported (got %d)\n", HUFFMAN_TABLES, index&0xf);  
  33. #if TRACE  
  34.      fprintf(p_trace,"Huffman table %s[%d] length=%d\n", (index&0xf0)?"AC":"DC", index&0xf, count);  
  35.      fflush(p_trace);  
  36.      /*add by yangyulan*/  
  37.      fprintf(hufftable,"Huffman table %s[%d] length=%d\n", (index&0xf0)?"AC":"DC", index&0xf, count);  
  38.      fflush(hufftable);  
  39.      /*end by yangyulan*/  
  40.        
  41. #endif  
  42. #endif  
  43.   
  44.      if (index & 0xf0 )//高位为1则为AC表  
  45.      {    
  46.          build_huffman_table(huff_bits, stream, &priv->HTAC[index&0xf]);  
  47.      }  
  48.         
  49.      else//否则为DC表  
  50.      {  
  51.          build_huffman_table(huff_bits, stream, &priv->HTDC[index&0xf]);  
  52.   
  53.      }  
  54.         
  55.      length -= 1;  
  56.      length -= 16;  
  57.      length -= count;  
  58.      stream += count;  
  59.   }  
  60. #if TRACE  
  61.   fprintf(p_trace,"< DHT marker\n");  
  62.   fflush(p_trace);  
  63. #endif  
  64.   return 0;  
  65. }  
build_huffman_table:依据数据重建 Huffman 表 

[cpp]  view plain  copy
  1. static void build_huffman_table(const unsigned char *bits, const unsigned char *vals, struct huffman_table *table)//创建码表  
  2. {  
  3.   unsigned int i, j, code, code_size, val, nbits;  
  4.   unsigned char huffsize[HUFFMAN_BITS_SIZE+1], *hz;  
  5.   unsigned int huffcode[HUFFMAN_BITS_SIZE+1], *hc;  
  6.   int next_free_entry;  
  7.   /*add by yangyulan*/  
  8.     FILE *hufftable;  
  9.      hufftable=fopen("huffmantable_file.txt","ab");   
  10.   /*end by yangyulan*/  
  11.   
  12.   /* 
  13.    * Build a temp array  
  14.    *   huffsize[X] => numbers of bits to write vals[X] 
  15.    */  
  16.   hz = huffsize;  
  17.   for (i=1; i<=16; i++)//码长为1~16  
  18.    {  
  19.      for (j=1; j<=bits[i]; j++)//码长为1~16的个数  
  20.        *hz++ = i;//第1~bits[1]的码长都为1...  
  21.    }  
  22.   *hz = 0;//最后码长赋为0  
  23.    
  24.   memset(table->lookup, 0xff, sizeof(table->lookup));  
  25.   for (i=0; i<(16-HUFFMAN_HASH_NBITS); i++)  
  26.     table->slowtable[i][0] = 0;//都初始化为0  
  27.   
  28.   /* Build a temp array 
  29.    *   huffcode[X] => code used to write vals[X] 
  30.    */  
  31.   code = 0;  
  32.   hc = huffcode;//指向码字  
  33.   hz = huffsize;//重新指向  
  34.   nbits = *hz;//从第一个开始,码长赋值  
  35.   while (*hz)//码长大于0 时  
  36.    {  
  37.      while (*hz == nbits)//码长未改变时  
  38.       {  
  39.     *hc++ = code++;//码字加1  
  40.     hz++;//指向下一个码字  
  41.       }  
  42.      code <<= 1;//否则码字加1补0  
  43.      nbits++;  
  44.    }  
  45.   
  46.   /* 
  47.    * Build the lookup table, and the slowtable if needed. 
  48.    */  
  49.   next_free_entry = -1;  
  50.   for (i=0; huffsize[i]; i++)//当各码长码字数不为0 时  
  51.    {  
  52.      val = vals[i];//vals[i]表示i码长码字个数  
  53.      code = huffcode[i];//码字  
  54.      code_size = huffsize[i];///码长  
  55.     #if TRACE  
  56.      fprintf(p_trace,"val=%2.2x code=%8.8x codesize=%2.2d\n", val, code, code_size);  
  57.      fflush(p_trace);  
  58.      /*add by yangyulan*/  
  59.       fprintf(hufftable,"val=%2.2x code=%8.8x codesize=%2.2d\n", val, code, code_size);  
  60.       fflush(hufftable);  
  61.      /*end by yangyulan*/  
  62.       
  63.     #endif  
  64.        
  65.      table->code_size[val] = code_size;  
  66.      if (code_size <= HUFFMAN_HASH_NBITS)  
  67.       {  
  68.     /* 
  69.      * Good: val can be put in the lookup table, so fill all value of this 
  70.      * column with value val  
  71.      */  
  72.     int repeat = 1UL<<(HUFFMAN_HASH_NBITS - code_size);  
  73.     code <<= HUFFMAN_HASH_NBITS - code_size;  
  74.     while ( repeat-- )  
  75.       table->lookup[code++] = val;  
  76.   
  77.       }  
  78.      else  
  79.       {  
  80.     /* Perhaps sorting the array will be an optimization */  
  81.     uint16_t *slowtable = table->slowtable[code_size-HUFFMAN_HASH_NBITS-1];  
  82.     while(slowtable[0])  
  83.       slowtable+=2;  
  84.     slowtable[0] = code;  
  85.     slowtable[1] = val;  
  86.     slowtable[2] = 0;  
  87.     /* TODO: NEED TO CHECK FOR AN OVERFLOW OF THE TABLE */  
  88.       }  
  89.   
  90.    }  
  91.   
  92. }  
任务三:输出Huffman码表到txt文件:
在解析重建Huffman表之后,我们可以中间输出Huffman表到txt文件中:即在trace中添加如下代码:
[cpp]  view plain  copy
  1. #if TRACE  
  2.      fprintf(p_trace,"Huffman table %s[%d] length=%d\n", (index&0xf0)?"AC":"DC", index&0xf, count);  
  3.      fflush(p_trace);  
  4.      /*add by yangyulan*/  
  5.      fprintf(hufftable,"Huffman table %s[%d] length=%d\n", (index&0xf0)?"AC":"DC", index&0xf, count);  
  6.      fflush(hufftable);  
  7.      /*end by yangyulan*/  
  8.        
  9. #endif  

parse_SOS函数:

得到解析每个颜色分量的 DC、 AC 值所使用的 Huffman 表序号(与 DHT中序号对应)
[cpp]  view plain  copy
  1. static int parse_SOS(struct jdec_private *priv, const unsigned char *stream)  
  2. {  
  3.   unsigned int i, cid, table;  
  4.   unsigned int nr_components = stream[2];//获得分量数  
  5. #if TRACE  
  6.   fprintf(p_trace,"> SOS marker\n");  
  7.   fflush(p_trace);  
  8. #endif  
  9.   
  10. #if SANITY_CHECK  
  11.   if (nr_components != 3)  
  12.     snprintf(error_string, sizeof(error_string),"We only support YCbCr image\n");  
  13. #endif  
  14.   
  15.   stream += 3;//指向Y分量ID  
  16.   for (i=0;i<nr_components;i++) {  
  17.      cid = *stream++;//ID赋值给cid  
  18.      table = *stream++;//对应的量化和Huffman码表  
  19. #if SANITY_CHECK  
  20.      if ((table&0xf)>=4)  
  21.     snprintf(error_string, sizeof(error_string),"We do not support more than 2 AC Huffman table\n");  
  22.      if ((table>>4)>=4)  
  23.     snprintf(error_string, sizeof(error_string),"We do not support more than 2 DC Huffman table\n");  
  24.      if (cid != priv->component_infos[i].cid)  
  25.         snprintf(error_string, sizeof(error_string),"SOS cid order (%d:%d) isn't compatible with the SOF marker (%d:%d)\n",  
  26.           i, cid, i, priv->component_infos[i].cid);  
  27. #if TRACE  
  28.      fprintf(p_trace,"ComponentId:%d  tableAC:%d tableDC:%d\n", cid, table&0xf, table>>4);  
  29.      fflush(p_trace);  
  30. #endif  
  31. #endif  
  32.      priv->component_infos[i].AC_table = &priv->HTAC[table&0xf];//得到每个颜色分量的ACHuffman码表  
  33.      priv->component_infos[i].DC_table = &priv->HTDC[table>>4];//得到每个颜色分量的DCHuffman码表  
  34.   }  
  35.   priv->stream = stream+3;//指向熵编码数据流的开始  
  36. #if TRACE  
  37.   fprintf(p_trace,"< SOS marker\n");  
  38.   fflush(p_trace);  
  39. #endif  
  40.   return 0;  
  41. }  
分析完文件头的各个marker后,我们开始对熵编码数据进行解码,这部分在tinyjpeg_decode函数中实现:

3.依据每个分量的水平、垂直采样因子计算 MCU 的大小,并得到每个 MCU 中 8*8宏块的个数

[cpp]  view plain  copy
  1.  xstride_by_mcu = ystride_by_mcu = 8;//初始化为4:4:4的情况,即MCU的宽和高都为8像素  
  2.   if ((priv->component_infos[cY].Hfactor | priv->component_infos[cY].Vfactor) == 1) {//Y分量的垂直和水平采样因子相等  
  3.      decode_MCU = decode_mcu_table[0];//每个MCU就包括1个Y分量  
  4.      convert_to_pixfmt = colorspace_array_conv[0];  
  5. #if TRACE  
  6.      fprintf(p_trace,"Use decode 1x1 sampling\n");  
  7.      fflush(p_trace);  
  8. #endif  
  9.   } else if (priv->component_infos[cY].Hfactor == 1) {//如果水平采样因子为1,垂直为2,  
  10.      decode_MCU = decode_mcu_table[1];//每个MCU 包含2个Y分量  
  11.      convert_to_pixfmt = colorspace_array_conv[1];  
  12.      ystride_by_mcu = 16;//一个MCU的高为16像素  
  13. #if TRACE  
  14.      fprintf(p_trace,"Use decode 1x2 sampling (not supported)\n");  
  15.      fflush(p_trace);  
  16. #endif  
  17.   } else if (priv->component_infos[cY].Vfactor == 2) {//如果水平采样因子为2,垂直为2,  
  18.      decode_MCU = decode_mcu_table[3];//每个MCU 包含4个Y分量  
  19.      convert_to_pixfmt = colorspace_array_conv[3];  
  20.      xstride_by_mcu = 16;//一个mcu的宽为16像素  
  21.      ystride_by_mcu = 16;//一个mcu的高为16像素  
  22. #if TRACE   
  23.      fprintf(p_trace,"Use decode 2x2 sampling\n");  
  24.      fflush(p_trace);  
  25. #endif  
  26.   } else {//如果水平采样因子为2,垂直为1  
  27.      decode_MCU = decode_mcu_table[2];//每个MCU 包含2个Y分量  
  28.      convert_to_pixfmt = colorspace_array_conv[2];  
  29.      xstride_by_mcu = 16;//一个mcu的宽为16  
  30. #if TRACE  
  31.      fprintf(p_trace,"Use decode 2x1 sampling\n");  
  32.      fflush(p_trace);  
  33. #endif  
  34.   }  

4.对每个 MCU 解码(依照各分量水平、垂直采样因子对 MCU 中每个分量宏块解码)

对每个宏块进行 Huffman 解码,得到 DCT 系数
对每个宏块的 DCT 系数进行 IDCT,得到 Y、 Cb、 Cr
遇到 Segment Marker RST 时,清空之前的 DC DCT 系数
[cpp]  view plain  copy
  1. /* 
  2.  * Decode all the 3 components for 1x1  
  3.  */  
  4. static void decode_MCU_1x1_3planes(struct jdec_private *priv)  
  5. {  
  6.   // Y  
  7.   process_Huffman_data_unit(priv, cY);  
  8.   IDCT(&priv->component_infos[cY], priv->Y, 8);  
  9.     
  10.   // Cb  
  11.   process_Huffman_data_unit(priv, cCb);  
  12.   IDCT(&priv->component_infos[cCb], priv->Cb, 8);  
  13.   
  14.   // Cr  
  15.   process_Huffman_data_unit(priv, cCr);  
  16.   IDCT(&priv->component_infos[cCr], priv->Cr, 8);  
  17. }  
  18.   
  19. /* 
  20.  * Decode a 1x1 directly in 1 color 
  21.  */  
  22. static void decode_MCU_1x1_1plane(struct jdec_private *priv)//采样格式为1:1:1  
  23. {  
  24.   // Y  
  25.   process_Huffman_data_unit(priv, cY);  
  26.   IDCT(&priv->component_infos[cY], priv->Y, 8);  
  27.     
  28.   // Cb  
  29.   process_Huffman_data_unit(priv, cCb);  
  30.   IDCT(&priv->component_infos[cCb], priv->Cb, 8);  
  31.   
  32.   // Cr  
  33.   process_Huffman_data_unit(priv, cCr);  
  34.   IDCT(&priv->component_infos[cCr], priv->Cr, 8);  
  35. }  
  36.   
  37.   
  38. /* 
  39.  * Decode a 2x1 
  40.  *  .-------. 
  41.  *  | 1 | 2 | 
  42.  *  `-------' 
  43.  */  
  44. static void decode_MCU_2x1_3planes(struct jdec_private *priv)//采样格式为2:1:1  
  45. {  
  46.   // Y  
  47.   process_Huffman_data_unit(priv, cY);  
  48.   IDCT(&priv->component_infos[cY], priv->Y, 16);  
  49.   process_Huffman_data_unit(priv, cY);  
  50.   IDCT(&priv->component_infos[cY], priv->Y+8, 16);  
  51.   
  52.   // Cb  
  53.   process_Huffman_data_unit(priv, cCb);  
  54.   IDCT(&priv->component_infos[cCb], priv->Cb, 8);  
  55.   
  56.   // Cr  
  57.   process_Huffman_data_unit(priv, cCr);  
  58.   IDCT(&priv->component_infos[cCr], priv->Cr, 8);  
  59. }  
  60.   
  61. /* 
  62.  * Decode a 2x1 
  63.  *  .-------. 
  64.  *  | 1 | 2 | 
  65.  *  `-------' 
  66.  */  
  67. static void decode_MCU_2x1_1plane(struct jdec_private *priv)  
  68. {  
  69.   // Y  
  70.   process_Huffman_data_unit(priv, cY);  
  71.   IDCT(&priv->component_infos[cY], priv->Y, 16);  
  72.   process_Huffman_data_unit(priv, cY);  
  73.   IDCT(&priv->component_infos[cY], priv->Y+8, 16);  
  74.   
  75.   // Cb  
  76.   process_Huffman_data_unit(priv, cCb);  
  77.   
  78.   // Cr  
  79.   process_Huffman_data_unit(priv, cCr);  
  80. }  
  81.   
  82.   
  83. /* 
  84.  * Decode a 2x2 
  85.  *  .-------. 
  86.  *  | 1 | 2 | 
  87.  *  |---+---| 
  88.  *  | 3 | 4 | 
  89.  *  `-------' 
  90.  */  
  91. static void decode_MCU_2x2_3planes(struct jdec_private *priv)  
  92. {  
  93.   // Y  
  94.   process_Huffman_data_unit(priv, cY);  
  95.   IDCT(&priv->component_infos[cY], priv->Y, 16);  
  96.   process_Huffman_data_unit(priv, cY);  
  97.   IDCT(&priv->component_infos[cY], priv->Y+8, 16);  
  98.   process_Huffman_data_unit(priv, cY);  
  99.   IDCT(&priv->component_infos[cY], priv->Y+64*2, 16);  
  100.   process_Huffman_data_unit(priv, cY);  
  101.   IDCT(&priv->component_infos[cY], priv->Y+64*2+8, 16);  
  102.   
  103.   // Cb  
  104.   process_Huffman_data_unit(priv, cCb);  
  105.   IDCT(&priv->component_infos[cCb], priv->Cb, 8);  
  106.   
  107.   // Cr  
  108.   process_Huffman_data_unit(priv, cCr);  
  109.   IDCT(&priv->component_infos[cCr], priv->Cr, 8);  
  110. }  
  111.   
  112. /* 
  113.  * Decode a 2x2 directly in GREY format (8bits) 
  114.  *  .-------. 
  115.  *  | 1 | 2 | 
  116.  *  |---+---| 
  117.  *  | 3 | 4 | 
  118.  *  `-------' 
  119.  */  
  120. static void decode_MCU_2x2_1plane(struct jdec_private *priv)  
  121. {  
  122.   // Y  
  123.   process_Huffman_data_unit(priv, cY);  
  124.   IDCT(&priv->component_infos[cY], priv->Y, 16);  
  125.   process_Huffman_data_unit(priv, cY);  
  126.   IDCT(&priv->component_infos[cY], priv->Y+8, 16);  
  127.   process_Huffman_data_unit(priv, cY);  
  128.   IDCT(&priv->component_infos[cY], priv->Y+64*2, 16);  
  129.   process_Huffman_data_unit(priv, cY);  
  130.   IDCT(&priv->component_infos[cY], priv->Y+64*2+8, 16);  
  131.   
  132.   // Cb  
  133.   process_Huffman_data_unit(priv, cCb);  
  134.   
  135.   // Cr  
  136.   process_Huffman_data_unit(priv, cCr);  
  137. }  
  138.   
  139. /* 
  140.  * Decode a 1x2 mcu 
  141.  *  .---. 
  142.  *  | 1 | 
  143.  *  |---| 
  144.  *  | 2 | 
  145.  *  `---' 
  146.  */  
  147. static void decode_MCU_1x2_3planes(struct jdec_private *priv)  
  148. {  
  149.   // Y  
  150.   process_Huffman_data_unit(priv, cY);  
  151.   IDCT(&priv->component_infos[cY], priv->Y, 8);  
  152.   process_Huffman_data_unit(priv, cY);  
  153.   IDCT(&priv->component_infos[cY], priv->Y+64, 8);  
  154.   
  155.   // Cb  
  156.   process_Huffman_data_unit(priv, cCb);  
  157.   IDCT(&priv->component_infos[cCb], priv->Cb, 8);  
  158.   
  159.   // Cr  
  160.   process_Huffman_data_unit(priv, cCr);  
  161.   IDCT(&priv->component_infos[cCr], priv->Cr, 8);  
  162. }  
  163.   
  164. /* 
  165.  * Decode a 1x2 mcu 
  166.  *  .---. 
  167.  *  | 1 | 
  168.  *  |---| 
  169.  *  | 2 | 
  170.  *  `---' 
  171.  */  
  172. static void decode_MCU_1x2_1plane(struct jdec_private *priv)  
  173. {  
  174.   // Y  
  175.   process_Huffman_data_unit(priv, cY);  
  176.   IDCT(&priv->component_infos[cY], priv->Y, 8);  
  177.   process_Huffman_data_unit(priv, cY);  
  178.   IDCT(&priv->component_infos[cY], priv->Y+64, 8);  
  179.   
  180.   // Cb  
  181.   process_Huffman_data_unit(priv, cCb);  
  182.   
  183.   // Cr  
  184.   process_Huffman_data_unit(priv, cCr);  
  185. }  
process_Huffman_data_unit函数:对一个8*8的彩色分量单元进行解码:
[cpp]  view plain  copy
  1. static void process_Huffman_data_unit(struct jdec_private *priv, int component)  
  2. {  
  3.   unsigned char j;  
  4.   unsigned int huff_code;  
  5.   unsigned char size_val, count_0;  
  6.   
  7.   
  8.   struct component *c = &priv->component_infos[component];  
  9.   short int DCT[64];  
  10.   
  11.   
  12.   /* 初始化DCT系数表*/  
  13.   memset(DCT, 0, sizeof(DCT));  
  14.   
  15.   /* DC系数解码*/  
  16.   huff_code = get_next_huffman_code(priv, c->DC_table);  
  17.   //trace("+ %x\n", huff_code);  
  18.   if (huff_code) {  
  19.      get_nbits(priv->reservoir, priv->nbits_in_reservoir, priv->stream, huff_code, DCT[0]);// 查表的 DC DCT 系数(残值)<span style="text-align: -webkit-auto;"><br style="orphans: 2; text-align: -webkit-auto; widows: 2;"></span>  
[cpp]  view plain  copy
  1.      DCT[0] += c->previous_DC;  
  2.      c->previous_DC = DCT[0];// DC 系数采用差分编码, 恢复原值<span style="font-family:宋体;color:#008000;"><span style="font-size: 10pt; text-align: -webkit-auto;"><br style="orphans: 2; text-align: -webkit-auto; widows: 2;"></span></span>  
  3.   } else {  
  4.      DCT[0] = c->previous_DC;  
  5.   }  
  6.   
  7.   
  8.   /* AC系数解码 */  
  9.   j = 1;  
  10.   while (j<64)  
  11.    {  
  12.      huff_code = get_next_huffman_code(priv, c->AC_table);  
  13.      //trace("- %x\n", huff_code);  
  14.   
  15.      size_val = huff_code & 0xF;// Amplitude 幅度  
  16.      count_0 = huff_code >> 4;// 零游程长度  
  17.      if (size_val == 0)// 0 不是一个有效的 Amplitude 值,这里做零游程标志  
  18.       { /* 零游程 */  
  19.     if (count_0 == 0)  
  20.       break;    /* EOB found, go out */  
  21.     else if (count_0 == 0xF)  
  22.       j += 16;  /* skip 16 zeros */  
  23.       }  
  24.      else  
  25.       {  
  26.     j += count_0;   /* 忽略零游程 */  
  27.     if (__unlikely(j >= 64))//出错了  
  28.      {  
  29.        snprintf(error_string, sizeof(error_string), "Bad huffman data (buffer overflow)");  
  30.        break;  
  31.      }  
  32.     get_nbits(priv->reservoir, priv->nbits_in_reservoir, priv->stream, size_val, DCT[j]);// 查表得到 AC DCT 系数  
  33.     j++;  
  34.       }  
  35.    }  
  36.   
  37.   for (j = 0; j < 64; j++)  
  38.     c->DCT[j] = DCT[zigzag[j]];  
  39.   
  40.   
  41.   
  42. }  

5.解完所有 MCU,解码结束

[cpp]  view plain  copy
  1. for (y=0; y < priv->height/ystride_by_mcu; y++) // 行循环  
  2. {  
  3. //trace("Decoding row %d\n", y);  
  4. priv->plane[0] = priv->components[0] + (y * bytes_per_blocklines[0]);  
  5. priv->plane[1] = priv->components[1] + (y * bytes_per_blocklines[1]);  
  6. priv->plane[2] = priv->components[2] + (y * bytes_per_blocklines[2]);  
  7. for (x=0; x < priv->width; x+=xstride_by_mcu) // 列循环  
  8. {  
  9. decode_MCU(priv); // 解码( Huffman 解码 + IDCT)  
  10. convert_to_pixfmt(priv);  
  11. priv->plane[0] += bytes_per_mcu[0];  
  12. priv->plane[1] += bytes_per_mcu[1];  
  13. priv->plane[2] += bytes_per_mcu[2];  
  14. if (priv->restarts_to_go>0)  
  15. {  
  16. priv->restarts_to_go--;  
  17. if (priv->restarts_to_go == 0)  
  18. {  
  19. priv->stream -= (priv->nbits_in_reservoir/8);  
  20. resync(priv); // 清空 preDC(所有颜色分量)  
  21. if (find_next_rst_marker(priv) < 0) // 查找 RST 标记  
  22. return -1;  
  23. }  
  24. }  
  25. }  
  26. }  
任务四:输出DC图像,AC图像并经过huffman统计其概率分布
1.在结构体中创建两个int指针和两个char型指针;int型便于计算,char型用于输出
[cpp]  view plain  copy
  1. /*add by yangyulan for DCimage and ACimage*/  
  2. int  *dcimg,*acimg;  
  3. unsigned char *dcimg_ch,*acimg_ch;  
  4. /*end by yangyulan for DCimage and ACimage*/  
2.定义两个文件指针分别打开两个yuv文件:DC图像和AC图像
 由于DCT变换的能量守恒和要求DC系数和AC系数均为有效的数据(0~255),我们定义了用于后面作归一化处理的4个变量:acmax,dcmax,acmin,dcmin。
[cpp]  view plain  copy
  1.  /*add by yangyulan for DCimage and ACimage*/  
  2.  FILE *DCimg=fopen("DCimage.yuv","wb");  
  3.  FILE *ACimg=fopen("ACimage.yuv","wb");  
  4.    static int ida=0;  
  5. int acmax, dcmax, acmin, dcmin;  
  6.  /*end by yangyulan for DCimage and ACimage*/  
3.为创建的指针分配空间:(注意数据类型)
[cpp]  view plain  copy
  1. /*add by yangyulan for DCimage and ACimage*/  
  2.     priv->dcimg = (int *)malloc(sizeof(int)*priv->width * priv->height/64);//每个8*8的块只有一个直流系数  
  3.     priv->acimg = (int*)malloc(sizeof(int)*priv->width * priv->height / 64);//  
  4.     priv->dcimg_ch = (unsigned char *)malloc(sizeof(unsigned char)*priv->width * priv->height/64);  
  5.     priv->acimg_ch = (unsigned char*)malloc(sizeof(unsigned char)*priv->width * priv->height / 64);//  
  6.   
  7.   /*end by yangyulan for DCimage and ACimage*/  
4.每解一个8*8的块,将DC(DCT[0])和AC(这里是DCT[1])写入内存
[cpp]  view plain  copy
  1. /*add by yangyulan*/  
  2. if(ida<priv->width*priv->height/64)  
  3. {  
  4. priv->dcimg[ida] = priv->component_infos[cY].DCT[0];  
  5. priv->acimg[ida] = priv->component_infos[cY].DCT[1];  
  6. ida++;  
  7. }  
  8. /*end by yangyulan*/  
5.归一化处理
根据DCT的能量守恒特性,反DCT之后的DC取值最大可达到8*256,且反差分编码后数据可能为负数。因此需要对得到的DC系数进行归一化处理,使其值分布在[0,255]之间, AC系数亦是如此。
[cpp]  view plain  copy
  1. /*add by yangyulan for DCimage and ACimage*/  
  2.   
  3.     
  4.   acmax = priv->acimg[0];  
  5.   acmin = priv->acimg[0];  
  6.   dcmax = priv->dcimg[0];  
  7.   dcmin = priv->dcimg[0];  
  8.   for (ida = 0; ida < priv->width*priv->height / 64; ida++)  
  9.   {  
  10.       if (priv->acimg[ida] >=acmax)  
  11.           acmax = priv->acimg[ida];  
  12.       if (priv->dcimg[ida] >= dcmax)  
  13.           dcmax = priv->dcimg[ida];  
  14.       if (priv->acimg[ida] <= acmin)  
  15.           acmin = priv->acimg[ida];  
  16.       if (priv->dcimg[ida] <=dcmin)  
  17.           dcmin = priv->dcimg[ida];  
  18.   }  
  19.   for (ida = 0; ida < priv->width*priv->height / 64; ida++)  
  20.   {  
  21.       priv->acimg_ch[ida] = (unsigned char)(255 *(priv->acimg[ida]-acmin)/ (acmax - acmin));  
  22.   }  
  23.   
  24.   for (ida= 0; ida < priv->width*priv->height / 64; ida++)  
  25.   {  
  26.       priv->dcimg_ch[ida] =(unsigned char)(255 *(priv->dcimg[ida]-dcmin)/ (dcmax - dcmin));  
  27.   }  
  28.   
  29.   
  30.     fwrite(priv->dcimg_ch, 1, priv->width*priv->height / 64, DCimg);  
  31.     fwrite(priv->acimg_ch, 1, priv->width*priv->height / 64, ACimg);  
  32.   
  33.   /*end by yangyulan for DCimage and ACimage*/  
6.再将输出的DC图像和AC图像经过Huffman编码器,得到其概率分布函数。Huffman编码器的程序前面实验已经给出,这里不再赘述。

四:实验结果

1.任务一实验结果:



2.任务二实验结果:

3.任务三实验结果:


4.任务四实验结果:

输出的DC和AC图像;

DC和AC图像的概率分布:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值