1. 程式人生 > >Speex Acoustic Echo Cancellation (AEC) 回聲消除模組的使用

Speex Acoustic Echo Cancellation (AEC) 回聲消除模組的使用

從程式碼分析,下邊是Speex test demo

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "speex/speex_echo.h"
#include "speex/speex_preprocess.h"


#define NN 128
#define TAIL 1024

int main(int argc, char **argv)
{
   FILE *echo_fd, *ref_fd, *e_fd;
   short echo_buf[NN], ref_buf[NN], e_buf[NN];
   SpeexEchoState *st;
   SpeexPreprocessState *den;
   int sampleRate = 8000;

   if (argc != 4)
   {
      fprintf(stderr, "testecho mic_signal.sw speaker_signal.sw output.sw\n");
      exit(1);
   }
   echo_fd = fopen(argv[2], "rb");
   ref_fd  = fopen(argv[1],  "rb");
   e_fd    = fopen(argv[3], "wb");
   // Step1: 初始化結構
     st = speex_echo_state_init(NN, TAIL);
   den = speex_preprocess_state_init(NN, sampleRate);

   //Step2: 設定相關引數
   speex_echo_ctl(st, SPEEX_ECHO_SET_SAMPLING_RATE, &sampleRate);
   speex_preprocess_ctl(den, SPEEX_PREPROCESS_SET_ECHO_STATE, st);

   while (!feof(ref_fd) && !feof(echo_fd))
   {
      fread(ref_buf, sizeof(short), NN, ref_fd);
      fread(echo_buf, sizeof(short), NN, echo_fd);
      
      //Step3: 呼叫Api回聲消除,ref_buf是麥克採集到的資料
      // echo_buf:是從speaker處獲取到的資料
      // e_buf: 是回聲消除後的資料
      speex_echo_cancellation(st, ref_buf, echo_buf, e_buf);
      speex_preprocess_run(den, e_buf);
      fwrite(e_buf, sizeof(short), NN, e_fd);
   }

   //Step4: 銷燬結構 釋放資源
   speex_echo_state_destroy(st);
   speex_preprocess_state_destroy(den);
   fclose(e_fd);
   fclose(echo_fd);
   fclose(ref_fd);
   return 0;
}

Speex 原始碼中附帶的這個例子,只適合於序列的鏈式媒體流,當媒體播放、媒體採集、媒體網路資料介面分屬在不同現成時,就會存在同步問題,非同步執行緒會導致訊號延遲加大,回聲消除收斂效果不好。其中Speex 回聲消除必須按照建議的流程:
write_to_soundcard(echo_frame, frame_size);     //播放音訊資料,並從音效卡獲得播放的資料echo_frame.
read_from_soundcard(input_frame, frame_size);   //在資料播放後,從音效卡麥克獲取採集到的資料input_frame.
speex_echo_cancellation(echo_state, input_frame, echo_frame, output_frame); //呼叫Api消除噪聲,輸入input_frame,echo_frame,輸出out_frame

在典型的VOIP型別應用中:

echo_frame: 從RTP接收的資料包解碼後,送入音效卡播放,獲取的資料。

input_frame: 本地麥克採集到的資料

output_frame: 回聲消除後的資料,送入encodec,並構造rtp資料包,傳輸到遠端。

典型的應用模式: 

Thread A:  接收audio rtp -> decodec -----> sound card 

                                                                    |__> echo_frame queue

Thread B

: 獲取麥克資料input_frame --> speex_echo_cancellation( speex_state, input_frame, echo_frame,out_frame ) -> rtp packet -> network 

也可以將rtp packet 與network 傳輸放到另外一個執行緒。