[转]AMR音频编解码

目录
1.    概述
2.    AMR编码
3.    AMR解码
4.    AMR帧读取算法
5.    参考资料
 
1.      概述
现在很多智能手机都支持多媒体功能,特别是音频和视频播放功能,而AMR文件格式是手机端普遍支持的音频文件格式。
 
AMR,全称是:Adaptive Multi-Rate,自适应多速率,是一种音频编码文件格式,专用于有效地压缩语音频率。
 
AMR音频主要用于移动设备的音频压缩,压缩比非常高,但是音质比较差,主要用于语音类的音频压缩,不适合对音质要求较高的音乐类音频的压缩。
 
AMR的编解码是基于“3GPP AMR Floating-point Speech Codec”来做的,3GPP还专门开放了基于ANSI-C实现的编解码代码,便于我们在各种平台上进行移植。
 
#ifndef amrFileCodec_h
#define amrFileCodec_h
 
#define AMR_MAGIC_NUMBER "#!AMR\n"
 
#define PCM_FRAME_SIZE 160 // 8khz 8000*0.02=160
#define MAX_AMR_FRAME_SIZE 32
#define AMR_FRAME_COUNT_PER_SECOND 50
//int amrEncodeMode[] = {4750, 5150, 5900, 6700, 7400, 7950, 10200, 12200}; // amr 编码方式
 
typedef struct
{
         char chChunkID[4];
         int nChunkSize;
}XCHUNKHEADER;
 
typedef struct
{
         short nFormatTag;
         short nChannels;
         int nSamplesPerSec;
         int nAvgBytesPerSec;
         short nBlockAlign;
         short nBitsPerSample;
}WAVEFORMAT;
 
typedef struct
{
         short nFormatTag;
         short nChannels;
         int nSamplesPerSec;
         int nAvgBytesPerSec;
         short nBlockAlign;
         short nBitsPerSample;
         short nExSize;
}WAVEFORMATX;
 
typedef struct
{
         char chRiffID[4];
         int nRiffSize;
         char chRiffFormat[4];
}RIFFHEADER;
 
typedef struct
{
         char chFmtID[4];
         int nFmtSize;
         WAVEFORMAT wf;
}FMTBLOCK;
 
// WAVE音频采样频率是8khz
// 音频样本单元数 = 8000*0.02 = 160 (由采样频率决定)
// 声道数 1 : 160
//        2 : 160*2 = 320
// bps决定样本(sample)大小
// bps = 8 --> 8位 unsigned char
//       16 --> 16位 unsigned short
int EncodeWAVEFileToAMRFile(const char* pchWAVEFilename, const char* pchAMRFileName, int nChannels, int nBitsPerSample);
 
// 将AMR文件解码成WAVE文件
int DecodeAMRFileToWAVEFile(const char* pchAMRFileName, const char* pchWAVEFilename);
 
#endif
 


2.        AMR编码
3GPP提供了编码代码,并提供了一个encoder.c程序,该程序示范了如何对一个16位的单声道PCM数据进行压缩的。(采样频率必须是8khz)
 
我对该程序进行一定的拓展,数据位支持8位和16位,可以是单声道和双声道。
 
l         对于8位PCM只需要将每个采样的sample数据位扩展成16位,并左移7位。
l         对于双声道,可以只对左声道数据进行处理,也可以只对右声道数据进行处理,或者将左右声道数据求平均值就可。
 
这样两个小处理,就可以将PCM规范成3PGG的编码器需要的数据格式。
 
代码在 amrFileEncoder.c 中。
 
#include "amrFileCodec.h"
 
// 从WAVE文件中跳过WAVE文件头,直接到PCM音频数据
void SkipToPCMAudioData(FILE* fpwave)
{
         RIFFHEADER riff;
         FMTBLOCK fmt;
         XCHUNKHEADER chunk;
         WAVEFORMATX wfx;
         int bDataBlock = 0;
 
         // 1. 读RIFF头
         fread(&riff, 1, sizeof(RIFFHEADER), fpwave);
 
         // 2. 读FMT块 - 如果 fmt.nFmtSize>16 说明需要还有一个附属大小没有读
         fread(&chunk, 1, sizeof(XCHUNKHEADER), fpwave);
         if ( chunk.nChunkSize>16 )
         {
                   fread(&wfx, 1, sizeof(WAVEFORMATX), fpwave);
         }
         else
         {
                   memcpy(fmt.chFmtID, chunk.chChunkID, 4);
                   fmt.nFmtSize = chunk.nChunkSize;
                   fread(&fmt.wf, 1, sizeof(WAVEFORMAT), fpwave);
         }
 
         // 3.转到data块 - 有些还有fact块等。
         while(!bDataBlock)
         {
                   fread(&chunk, 1, sizeof(XCHUNKHEADER), fpwave);
                   if ( !memcmp(chunk.chChunkID, "data", 4) )
                   {
                            bDataBlock = 1;
                            break;
                   }
                   // 因为这个不是data块,就跳过块数据
                   fseek(fpwave, chunk.nChunkSize, SEEK_CUR);
         }
}
 
// 从WAVE文件读一个完整的PCM音频帧
// 返回值: 0-错误 >0: 完整帧大小
int ReadPCMFrame(short speech[], FILE* fpwave, int nChannels, int nBitsPerSample)
{
         int nRead = 0;
         int x = 0, y=0;
         unsigned short ush1=0, ush2=0, ush=0;
 
         // 原始PCM音频帧数据
         unsigned char pcmFrame_8b1[PCM_FRAME_SIZE];
         unsigned char pcmFrame_8b2[PCM_FRAME_SIZE<<1];
         unsigned short pcmFrame_16b1[PCM_FRAME_SIZE];
         unsigned short pcmFrame_16b2[PCM_FRAME_SIZE<<1];
 
         if (nBitsPerSample==8 && nChannels==1)
         {
                   nRead = fread(pcmFrame_8b1, (nBitsPerSample/8), PCM_FRAME_SIZE*nChannels, fpwave);
                   for(x=0; x<PCM_FRAME_SIZE; x++)
                   {
                            speech[x] =(short)((short)pcmFrame_8b1[x] << 7);
                   }
         }
         else
         if (nBitsPerSample==8 && nChannels==2)
         {
                   nRead = fread(pcmFrame_8b2, (nBitsPerSample/8), PCM_FRAME_SIZE*nChannels, fpwave);
                   for( x=0, y=0; y<PCM_FRAME_SIZE; y++,x+=2 )
                   {
                            // 1 - 取两个声道之左声道
                            speech[y] =(short)((short)pcmFrame_8b2[x+0] << 7);
                            // 2 - 取两个声道之右声道
                            //speech[y] =(short)((short)pcmFrame_8b2[x+1] << 7);
                            // 3 - 取两个声道的平均值
                            //ush1 = (short)pcmFrame_8b2[x+0];
                            //ush2 = (short)pcmFrame_8b2[x+1];
                            //ush = (ush1 + ush2) >> 1;
                            //speech[y] = (short)((short)ush << 7);
                   }
         }
         else
         if (nBitsPerSample==16 && nChannels==1)
         {
                   nRead = fread(pcmFrame_16b1, (nBitsPerSample/8), PCM_FRAME_SIZE*nChannels, fpwave);
                   for(x=0; x<PCM_FRAME_SIZE; x++)
                   {
                            speech[x] = (short)pcmFrame_16b1[x+0];
                   }
         }
         else
         if (nBitsPerSample==16 && nChannels==2)
         {
                   nRead = fread(pcmFrame_16b2, (nBitsPerSample/8), PCM_FRAME_SIZE*nChannels, fpwave);
                   for( x=0, y=0; y<PCM_FRAME_SIZE; y++,x+=2 )
                   {
                            //speech[y] = (short)pcmFrame_16b2[x+0];
                            speech[y] = (short)((int)((int)pcmFrame_16b2[x+0] + (int)pcmFrame_16b2[x+1])) >> 1;
                   }
         }
 
         // 如果读到的数据不是一个完整的PCM帧, 就返回0
         if (nRead<PCM_FRAME_SIZE*nChannels) return 0;
 
         return nRead;
}
 
// WAVE音频采样频率是8khz
// 音频样本单元数 = 8000*0.02 = 160 (由采样频率决定)
// 声道数 1 : 160
//        2 : 160*2 = 320
// bps决定样本(sample)大小
// bps = 8 --> 8位 unsigned char
//       16 --> 16位 unsigned short
int EncodeWAVEFileToAMRFile(const char* pchWAVEFilename, const char* pchAMRFileName, int nChannels, int nBitsPerSample)
{
         FILE* fpwave;
         FILE* fpamr;
 
         /* input speech vector */
         short speech[160];
 
         /* counters */
         int byte_counter, frames = 0, bytes = 0;
 
         /* pointer to encoder state structure */
         int *enstate;
        
         /* requested mode */
         enum Mode req_mode = MR122;
         int dtx = 0;
 
         /* bitstream filetype */
         unsigned char amrFrame[MAX_AMR_FRAME_SIZE];
 
         fpwave = fopen(pchWAVEFilename, "rb");
         if (fpwave == NULL)
         {
                   return 0;
         }
 
         // 创建并初始化amr文件
         fpamr = fopen(pchAMRFileName, "wb");
         if (fpamr == NULL)
         {
                   fclose(fpwave);
                   return 0;
         }
         /* write magic number to indicate single channel AMR file storage format */
         bytes = fwrite(AMR_MAGIC_NUMBER, sizeof(char), strlen(AMR_MAGIC_NUMBER), fpamr);
 
         /* skip to pcm audio data*/
         SkipToPCMAudioData(fpwave);
 
         enstate = Encoder_Interface_init(dtx);
 
         while(1)
         {
                   // read one pcm frame
                   if (!ReadPCMFrame(speech, fpwave, nChannels, nBitsPerSample)) break;
 
                   frames++;
 
                   /* call encoder */
                   byte_counter = Encoder_Interface_Encode(enstate, req_mode, speech, amrFrame, 0);
 
                   bytes += byte_counter;
                   fwrite(amrFrame, sizeof (unsigned char), byte_counter, fpamr );
         }
 
         Encoder_Interface_exit(enstate);
 
         fclose(fpamr);
         fclose(fpwave);
 
         return frames;
}


3.      AMR解码
3GPP提供了解码代码,并提供了一个decoder.c程序,该程序示范了如何对amr音频进行解码。解码成一个wave文件(8khz 16位单声道)。
 
解码是需要注意AMR坏帧的处理。在AMR读帧算法中有说明。
 
文件解码器代码在 amrFileDecoder.c 中。
 
#include "amrFileCodec.h"
 
void WriteWAVEFileHeader(FILE* fpwave, int nFrame)
{
         char tag[10] = "";
 
         // 1. 写RIFF头
         strcpy(tag, "RIFF");
         memcpy(riff.chRiffID, tag, 4);
         riff.nRiffSize = 4                                     // WAVE
                   + sizeof(XCHUNKHEADER)               // fmt
                   + sizeof(WAVEFORMATX)           // WAVEFORMATX
                   + sizeof(XCHUNKHEADER)               // DATA
                   + nFrame*160*sizeof(short);    //
         strcpy(tag, "WAVE");
         memcpy(riff.chRiffFormat, tag, 4);
         fwrite(&riff, 1, sizeof(RIFFHEADER), fpwave);
 
         // 2. 写FMT块
         strcpy(tag, "fmt ");
         memcpy(chunk.chChunkID, tag, 4);
         chunk.nChunkSize = sizeof(WAVEFORMATX);
         fwrite(&chunk, 1, sizeof(XCHUNKHEADER), fpwave);
         memset(&wfx, 0, sizeof(WAVEFORMATX));
         wfx.nFormatTag = 1;
         wfx.nChannels = 1; // 单声道
         wfx.nSamplesPerSec = 8000; // 8khz
         wfx.nAvgBytesPerSec = 16000;
         wfx.nBlockAlign = 2;
         wfx.nBitsPerSample = 16; // 16位
         fwrite(&wfx, 1, sizeof(WAVEFORMATX), fpwave);
 
         // 3. 写data块头
         strcpy(tag, "data");
         memcpy(chunk.chChunkID, tag, 4);
         chunk.nChunkSize = nFrame*160*sizeof(short);
         fwrite(&chunk, 1, sizeof(XCHUNKHEADER), fpwave);
}
 
const int round(const double x)
{
         return((int)(x+0.5));
}
 
// 根据帧头计算当前帧大小
int caclAMRFrameSize(unsigned char frameHeader)
{
         int mode;
         int temp1 = 0;
         int temp2 = 0;
         int frameSize;
 
         temp1 = frameHeader;
 
         // 编码方式编号 = 帧头的3-6位
         temp1 &= 0x78; // 0111-1000
         temp1 >>= 3;
 
         mode = amrEncodeMode[temp1];
 
         // 计算amr音频数据帧大小
         // 原理: amr 一帧对应20ms,那么一秒有50帧的音频数据
         temp2 = round((double)(((double)mode / (double)AMR_FRAME_COUNT_PER_SECOND) / (double)8));
 
         frameSize = round((double)temp2 + 0.5);
         return frameSize;
}
 
// 读第一个帧 - (参考帧)
// 返回值: 0-出错; 1-正确
int ReadAMRFrameFirst(FILE* fpamr, unsigned char frameBuffer[], int* stdFrameSize, unsigned char* stdFrameHeader)
{
         memset(frameBuffer, 0, sizeof(frameBuffer));
 
         // 先读帧头
         fread(stdFrameHeader, 1, sizeof(unsigned char), fpamr);
         if (feof(fpamr)) return 0;
 
         // 根据帧头计算帧大小
         *stdFrameSize = caclAMRFrameSize(*stdFrameHeader);
 
         // 读首帧
         frameBuffer[0] = *stdFrameHeader;
         fread(&(frameBuffer[1]), 1, (*stdFrameSize-1)*sizeof(unsigned char), fpamr);
         if (feof(fpamr)) return 0;
 
         return 1;
}
 
// 返回值: 0-出错; 1-正确
int ReadAMRFrame(FILE* fpamr, unsigned char frameBuffer[], int stdFrameSize, unsigned char stdFrameHeader)
{
         int bytes = 0;
         unsigned char frameHeader; // 帧头
 
         memset(frameBuffer, 0, sizeof(frameBuffer));
 
         // 读帧头
         // 如果是坏帧(不是标准帧头),则继续读下一个字节,直到读到标准帧头
         while(1)
         {
                   bytes = fread(&frameHeader, 1, sizeof(unsigned char), fpamr);
                   if (feof(fpamr)) return 0;
                   if (frameHeader == stdFrameHeader) break;
         }
 
         // 读该帧的语音数据(帧头已经读过)
         frameBuffer[0] = frameHeader;
         bytes = fread(&(frameBuffer[1]), 1, (stdFrameSize-1)*sizeof(unsigned char), fpamr);
         if (feof(fpamr)) return 0;
 
         return 1;
}
 
// 将AMR文件解码成WAVE文件
int DecodeAMRFileToWAVEFile(const char* pchAMRFileName, const char* pchWAVEFilename)
{
         FILE* fpamr = NULL;
         FILE* fpwave = NULL;
         char magic[8];
         int * destate;
         int nFrameCount = 0;
         int stdFrameSize;
         unsigned char stdFrameHeader;
 
         unsigned char amrFrame[MAX_AMR_FRAME_SIZE];
         short pcmFrame[PCM_FRAME_SIZE];
 
         fpamr = fopen(pchAMRFileName, "rb");
         if ( fpamr==NULL ) return 0;
 
         // 检查amr文件头
         fread(magic, sizeof(char), strlen(AMR_MAGIC_NUMBER), fpamr);
         if (strncmp(magic, AMR_MAGIC_NUMBER, strlen(AMR_MAGIC_NUMBER)))
         {
                   fclose(fpamr);
                   return 0;
         }
 
         // 创建并初始化WAVE文件
         fpwave = fopen(pchWAVEFilename, "wb");
         WriteWAVEFileHeader(fpwave, nFrameCount);
 
         /* init decoder */
         destate = Decoder_Interface_init();
 
         // 读第一帧 - 作为参考帧
         memset(amrFrame, 0, sizeof(amrFrame));
         memset(pcmFrame, 0, sizeof(pcmFrame));
         ReadAMRFrameFirst(fpamr, amrFrame, &stdFrameSize, &stdFrameHeader);
 
         // 解码一个AMR音频帧成PCM数据
         Decoder_Interface_Decode(destate, amrFrame, pcmFrame, 0);
         nFrameCount++;
         fwrite(pcmFrame, sizeof(short), PCM_FRAME_SIZE, fpwave);
 
         // 逐帧解码AMR并写到WAVE文件里
         while(1)
         {
                   memset(amrFrame, 0, sizeof(amrFrame));
                   memset(pcmFrame, 0, sizeof(pcmFrame));
                   if (!ReadAMRFrame(fpamr, amrFrame, stdFrameSize, stdFrameHeader)) break;
 
                   // 解码一个AMR音频帧成PCM数据 (8k-16b-单声道)
                   Decoder_Interface_Decode(destate, amrFrame, pcmFrame, 0);
                   nFrameCount++;
                   fwrite(pcmFrame, sizeof(short), PCM_FRAME_SIZE, fpwave);
         }
 
         Decoder_Interface_exit(destate);
 
         fclose(fpwave);
 
         // 重写WAVE文件头
         fpwave = fopen(pchWAVEFilename, "r+");
         WriteWAVEFileHeader(fpwave, nFrameCount);
         fclose(fpwave);
 
         return nFrameCount;
}
 


4.      AMR帧读取算法
因为可能存在异常帧,所以不一定所有的语音帧大小一致,对于跟正常帧大小不一致的,或者帧头跟正常帧头不一致的,就不交给解码器,直接抛弃该坏帧。
 
读取帧的算法,用C语言来编写,readAMRFrame.c,JAVA可以用类似的方法。
下面是算法描述流程图。
读首帧(标准帧)
ReadFirstAMRFrame
根据帧头计算标准帧的大小
caclAMRFrameSize
AMR音频文件流
读帧头(字节)
frameHeader
判断是否为坏帧?
Y
N
读本帧音频数据
帧头 + 音频数据 = 当前帧数据


5.      参考资料
l         rfc3267
http://www.rfc-editor.org/rfc/rfc3267.txt
http://ietfreport.isoc.org/rfc/PDF/rfc3267.pdf
l         3GPP TS 26.104 V 6.1.0 (2004-03)
http://www.3gpp.org/ftp/Specs/html-info/26104-CRs.htm
l         3GPP AMR Floating-point Speech Codec
http://www.3gpp.org/ftp/Specs/html-info/26104.htm
l         “amr编程汇总”
http://blog.csdn.net/windcao/archive/2006/01/04/570348.aspx
l         关于AMR文件格式的解释
http://www.mcublog.com/blog/user1/11409/archives/2006/16832.html
l         


本文来自:我爱研发网(52RD.com) 详细出处:http://www.52rd.com/bbs/Archive_Thread.asp?SID=115539&TID=2

posted @ 2009-06-19 18:04  一根神棍研古今  阅读(15992)  评论(0编辑  收藏  举报
Web Counter