AAC 到 PCM 音頻解碼

最近遇到在 iOS 平臺(tái)上實(shí)時(shí)播放 AAC 音頻數(shù)據(jù)流, 一開始嘗試用 AudioQueue 直接解 AAC 未果, 轉(zhuǎn)而將 AAC 解碼為 PCM, 最終實(shí)現(xiàn)了 AAC 實(shí)時(shí)流在 iOS 平臺(tái)下的播放問(wèn)題.

AAC 轉(zhuǎn) PCM 需要借助解碼庫(kù)來(lái)實(shí)現(xiàn), 目前了解到有兩個(gè)庫(kù)能干這個(gè)事 : faadffmpeg.

  • faad 算是輕量級(jí)的解碼庫(kù), 編譯出來(lái)全平臺(tái)靜態(tài)庫(kù)文件大小 2M 左右, API 也比較簡(jiǎn)單, 缺點(diǎn)是功能單一只處理 AAC , 它還有一個(gè)對(duì)應(yīng)的編碼庫(kù)叫 faac.
  • ffmpeg 體積龐大, 功能豐富, API 略顯復(fù)雜.

下面分別梳理使用這兩個(gè)庫(kù)完成解碼的過(guò)程.

faad


  • 下載源碼
#下載
wget http://downloads.sourceforge.net/faac/faad2-2.7.tar.gz
#解壓縮
tar xvzf faad2-2.7.tar.gz
#重命名
mv faad2-2.7 faad
  • 寫編譯腳本, vi build-faad.sh
#!/bin/sh

CONFIGURE_FLAGS="--enable-static --with-pic"

ARCHS="arm64 armv7s armv7 x86_64 i386"

# directories
SOURCE="faad"
FAT="fat-faad"

SCRATCH="scratch-faad"
# must be an absolute path
THIN=`pwd`/"thin-faad"

COMPILE="y"
LIPO="y"

if [ "$*" ]
then
if [ "$*" = "lipo" ]
then
# skip compile
COMPILE=
else
ARCHS="$*"
if [ $# -eq 1 ]
then
# skip lipo
LIPO=
fi
fi
fi

if [ "$COMPILE" ]
then
CWD=`pwd`
for ARCH in $ARCHS
do
echo "building $ARCH..."
mkdir -p "$SCRATCH/$ARCH"
cd "$SCRATCH/$ARCH"

if [ "$ARCH" = "i386" -o "$ARCH" = "x86_64" ]
then
PLATFORM="iPhoneSimulator"
CPU=
if [ "$ARCH" = "x86_64" ]
then
SIMULATOR="-mios-simulator-version-min=7.0"
HOST=
else
SIMULATOR="-mios-simulator-version-min=5.0"
HOST="--host=i386-apple-darwin"
fi
else
PLATFORM="iPhoneOS"
if [ $ARCH = "armv7s" ]
then
CPU="--cpu=swift"
else
CPU=
fi
SIMULATOR=
HOST="--host=arm-apple-darwin"
fi

XCRUN_SDK=`echo $PLATFORM | tr '[:upper:]' '[:lower:]'`
CC="xcrun -sdk $XCRUN_SDK clang -Wno-error=unused-command-line-argument-hard-error-in-future"
AS="$CWD/$SOURCE/extras/gas-preprocessor.pl $CC"
CFLAGS="-arch $ARCH $SIMULATOR"
CXXFLAGS="$CFLAGS"
LDFLAGS="$CFLAGS"

CC=$CC CFLAGS=$CXXFLAGS LDFLAGS=$LDFLAGS CPPFLAGS=$CXXFLAGS CXX=$CC CXXFLAGS=$CXXFLAGS  $CWD/$SOURCE/configure \
$CONFIGURE_FLAGS \
$HOST \
--prefix="$THIN/$ARCH" \
--disable-shared \
--without-mp4v2

make clean && make && make install-strip
cd $CWD
done
fi

if [ "$LIPO" ]
then
echo "building fat binaries..."
mkdir -p $FAT/lib
set - $ARCHS
CWD=`pwd`
cd $THIN/$1/lib
for LIB in *.a
do
cd $CWD
lipo -create `find $THIN -name $LIB` -output $FAT/lib/$LIB
done

cd $CWD
cp -rf $THIN/$1/include $FAT
fi

保存編譯腳本到解壓出的 faad 目錄同一級(jí)目錄下, 并添加可執(zhí)行權(quán)限
chmod a+x build-faad.sh

  • 編譯
    ./build-faad.sh
    當(dāng)前目錄下 fat-faad 即為編譯結(jié)果所在位置, 里面有頭文件和支持全平臺(tái)(armv7, armv7s ,i386, x86_64, arm64)的靜態(tài)庫(kù)

  • 添加靜態(tài)庫(kù)到工程依賴 (鼠標(biāo)拖 fat-faad 目錄到 xcode 工程目錄下), 創(chuàng)建解碼文件FAACDecoder.h,FAACDecoder.m

  • FAACDecoder.h

//
//  FAACDecoder.h
//  EasyClient
//
//  Created by 吳鵬 on 16/9/3.
//  Copyright ? 2016年 EasyDarwin. All rights reserved.
//

#ifndef FAACDecoder_h
#define FAACDecoder_h

typedef struct {
    NeAACDecHandle handle;
    int sample_rate;
    int channels;
    int bit_rate;
}FAADContext;

FAADContext* faad_decoder_create(int sample_rate, int channels, int bit_rate);
int faad_decode_frame(FAADContext *pParam, unsigned char *pData, int nLen, unsigned char *pPCM, unsigned int *outLen);
void faad_decode_close(FAADContext *pParam);

#endif /* FAACDecoder_h */
  • FAACDecoder.m
//
//  FAACDecoder.m
//  EasyClient
//
//  Created by 吳鵬 on 16/9/3.
//  Copyright ? 2016年 EasyDarwin. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "FAACDecoder.h"
#import "faad.h"

uint32_t _get_frame_length(const unsigned char *aac_header)
{
    uint32_t len = *(uint32_t *)(aac_header + 3);
    len = ntohl(len); //Little Endian
    len = len << 6;
    len = len >> 19;
    return len;
}

FAADContext* faad_decoder_create(int sample_rate, int channels, int bit_rate)
{
    NeAACDecHandle handle = NeAACDecOpen();
    if(!handle){
        printf("NeAACDecOpen failed\n");
        goto error;
    }
    NeAACDecConfigurationPtr conf = NeAACDecGetCurrentConfiguration(handle);
    if(!conf){
        printf("NeAACDecGetCurrentConfiguration failed\n");
        goto error;
    }
    conf->defSampleRate = sample_rate;
    conf->outputFormat = FAAD_FMT_16BIT;
    conf->dontUpSampleImplicitSBR = 1;
    NeAACDecSetConfiguration(handle, conf);
    
    FAADContext* ctx = malloc(sizeof(FAADContext));
    ctx->handle = handle;
    ctx->sample_rate = sample_rate;
    ctx->channels = channels;
    ctx->bit_rate = bit_rate;
    return ctx;
    
error:
    if(handle){
        NeAACDecClose(handle);
    }
    return NULL;
}

int faad_decode_frame(FAADContext *p, unsigned char *pData, int nLen, unsigned char *pPCM, unsigned int *outLen)
{
    FAADContext* pCtx = (FAADContext*)pParam;
    NeAACDecHandle handle = pCtx->handle;
    long res = NeAACDecInit(handle, pData, nLen, (unsigned long*)&pCtx->sample_rate, (unsigned char*)&pCtx->channels);
    if (res < 0) {
        printf("NeAACDecInit failed\n");
        return -1;
    }
    NeAACDecFrameInfo info;
    uint32_t framelen = _get_frame_length(pData);
    unsigned char *buf = (unsigned char *)NeAACDecDecode(handle, &info, pData, framelen);
    if (buf && info.error == 0) {
        if (info.samplerate == 44100) {
            //src: 2048 samples, 4096 bytes
            //dst: 2048 samples, 4096 bytes
            int tmplen = (int)info.samples * 16 / 8;
            memcpy(pPCM,buf,tmplen);
            *outLen = tmplen;
        } else if (info.samplerate == 22050) {
            //src: 1024 samples, 2048 bytes
            //dst: 2048 samples, 4096 bytes
            short *ori = (short*)buf;
            short tmpbuf[info.samples * 2];
            int tmplen = (int)info.samples * 16 / 8 * 2;
            for (int32_t i = 0, j = 0; i < info.samples; i += 2) {
                tmpbuf[j++] = ori[i];
                tmpbuf[j++] = ori[i + 1];
                tmpbuf[j++] = ori[i];
                tmpbuf[j++] = ori[i + 1];
            }
            memcpy(pPCM,tmpbuf,tmplen);
            *outLen = tmplen;
        }else if(info.samplerate == 8000){
            //從雙聲道的數(shù)據(jù)中提取單通道
            for(int i=0,j=0; i<4096 && j<2048; i+=4, j+=2)
            {
                pPCM[j]= buf[i];
                pPCM[j+1]=buf[i+1];
            }
            *outLen = (unsigned int)info.samples;
        }
    } else {
        printf("NeAACDecDecode failed\n");
        return -1;
    }
    return 0;
}

void faad_decode_close(void *pParam)
{
    if(!pParam){
        return;
    }
    FAADContext* pCtx = (FAADContext*)pParam;
    if(pCtx->handle){
        NeAACDecClose(pCtx->handle);
    }
    free(pCtx);
}

幾個(gè)主要 API :

  1. NeAACDecOpen
  2. NeAACDecGetCurrentConfiguration
  3. NeAACDecSetConfiguration
  4. NeAACDecInit
  5. NeAACDecDecode
  6. NeAACDecClose

ffmpeg


#ifndef _AACDecoder_h
#define _AACDecoder_h

void *aac_decoder_create(int sample_rate, int channels, int bit_rate);
int aac_decode_frame(void *pParam, unsigned char *pData, int nLen, unsigned char *pPCM, unsigned int *outLen);
void aac_decode_close(void *pParam);

#endif
  • AACDecoder.m
#include "AACDecoder.h"
#include "libavformat/avformat.h"
#include "libswresample/swresample.h"
#include "libavcodec/avcodec.h"

typedef struct AACDFFmpeg {
    AVCodecContext *pCodecCtx;
    AVFrame *pFrame;
    struct SwrContext *au_convert_ctx;
    int out_buffer_size;
} AACDFFmpeg;

void *aac_decoder_create(int sample_rate, int channels, int bit_rate)
{
    AACDFFmpeg *pComponent = (AACDFFmpeg *)malloc(sizeof(AACDFFmpeg));
    AVCodec *pCodec = avcodec_find_decoder(AV_CODEC_ID_AAC);
    if (pCodec == NULL)
    {
        printf("find aac decoder error\r\n");
        return 0;
    }
    // 創(chuàng)建顯示contedxt
    pComponent->pCodecCtx = avcodec_alloc_context3(pCodec);
    pComponent->pCodecCtx->channels = channels;
    pComponent->pCodecCtx->sample_rate = sample_rate;
    pComponent->pCodecCtx->bit_rate = bit_rate;
    if(avcodec_open2(pComponent->pCodecCtx, pCodec, NULL) < 0)
    {
        printf("open codec error\r\n");
        return 0;
    }
    
    pComponent->pFrame = av_frame_alloc();
    

    uint64_t out_channel_layout = channels < 2 ? AV_CH_LAYOUT_MONO:AV_CH_LAYOUT_STEREO;
    int out_nb_samples = 1024;
    enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
    
    pComponent->au_convert_ctx = swr_alloc();
    pComponent->au_convert_ctx = swr_alloc_set_opts(pComponent->au_convert_ctx, out_channel_layout, out_sample_fmt, sample_rate,
                                      out_channel_layout, AV_SAMPLE_FMT_FLTP, sample_rate, 0, NULL);
    swr_init(pComponent->au_convert_ctx);
    int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);
    pComponent->out_buffer_size = av_samples_get_buffer_size(NULL, out_channels, out_nb_samples, out_sample_fmt, 1);

    return (void *)pComponent;
}

int aac_decode_frame(void *pParam, unsigned char *pData, int nLen, unsigned char *pPCM, unsigned int *outLen)
{
    AACDFFmpeg *pAACD = (AACDFFmpeg *)pParam;
    AVPacket packet;
    av_init_packet(&packet);
    
    packet.size = nLen;
    packet.data = pData;
    
    int got_frame = 0;
    int nRet = 0;
    if (packet.size > 0)
    {
        nRet = avcodec_decode_audio4(pAACD->pCodecCtx, pAACD->pFrame, &got_frame, &packet);
        if (nRet < 0)
        {
   printf("avcodec_decode_audio4:%d\r\n",nRet);
            printf("avcodec_decode_audio4 %d  sameles = %d  outSize = %d\r\n", nRet, pAACD->pFrame->nb_samples, pAACD->out_buffer_size);
            return nRet;
        }

        if(got_frame)
        {
            swr_convert(pAACD->au_convert_ctx, &pPCM, pAACD->out_buffer_size, (const uint8_t **)pAACD->pFrame->data, pAACD->pFrame->nb_samples);
            *outLen = pAACD->out_buffer_size;
        }
    }

    av_free_packet(&packet);
    if (nRet > 0)
    {
        return 0;
    }
    return -1;
}

void aac_decode_close(void *pParam)
{
    AACDFFmpeg *pComponent = (AACDFFmpeg *)pParam;
    if (pComponent == NULL)
    {
        return;
    }
    
    swr_free(&pComponent->au_convert_ctx);
    
    if (pComponent->pFrame != NULL)
    {
        av_frame_free(&pComponent->pFrame);
        pComponent->pFrame = NULL;
    }
    
    if (pComponent->pCodecCtx != NULL)
    {
        avcodec_close(pComponent->pCodecCtx);
        avcodec_free_context(&pComponent->pCodecCtx);
        pComponent->pCodecCtx = NULL;
    }
    
    free(pComponent);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末昔穴,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子提前,更是在濱河造成了極大的恐慌吗货,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,723評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件狈网,死亡現(xiàn)場(chǎng)離奇詭異卿操,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)孙援,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門害淤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人拓售,你說(shuō)我怎么就攤上這事窥摄。” “怎么了础淤?”我有些...
    開封第一講書人閱讀 152,998評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵崭放,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我鸽凶,道長(zhǎng)币砂,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,323評(píng)論 1 279
  • 正文 為了忘掉前任玻侥,我火速辦了婚禮决摧,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘凑兰。我一直安慰自己掌桩,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,355評(píng)論 5 374
  • 文/花漫 我一把揭開白布姑食。 她就那樣靜靜地躺著波岛,像睡著了一般。 火紅的嫁衣襯著肌膚如雪音半。 梳的紋絲不亂的頭發(fā)上则拷,一...
    開封第一講書人閱讀 49,079評(píng)論 1 285
  • 那天,我揣著相機(jī)與錄音曹鸠,去河邊找鬼煌茬。 笑死,一個(gè)胖子當(dāng)著我的面吹牛物延,可吹牛的內(nèi)容都是我干的宣旱。 我是一名探鬼主播,決...
    沈念sama閱讀 38,389評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼叛薯,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼浑吟!你這毒婦竟也來(lái)了笙纤?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,019評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤组力,失蹤者是張志新(化名)和其女友劉穎省容,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體燎字,經(jīng)...
    沈念sama閱讀 43,519評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡腥椒,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,971評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了候衍。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片笼蛛。...
    茶點(diǎn)故事閱讀 38,100評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖蛉鹿,靈堂內(nèi)的尸體忽然破棺而出滨砍,到底是詐尸還是另有隱情,我是刑警寧澤妖异,帶...
    沈念sama閱讀 33,738評(píng)論 4 324
  • 正文 年R本政府宣布惋戏,位于F島的核電站,受9級(jí)特大地震影響他膳,放射性物質(zhì)發(fā)生泄漏响逢。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,293評(píng)論 3 307
  • 文/蒙蒙 一棕孙、第九天 我趴在偏房一處隱蔽的房頂上張望舔亭。 院中可真熱鬧,春花似錦散罕、人聲如沸分歇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,289評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至葬燎,卻和暖如春误甚,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背谱净。 一陣腳步聲響...
    開封第一講書人閱讀 31,517評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工窑邦, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人壕探。 一個(gè)月前我還...
    沈念sama閱讀 45,547評(píng)論 2 354
  • 正文 我出身青樓冈钦,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親李请。 傳聞我的和親對(duì)象是個(gè)殘疾皇子瞧筛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,834評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容