Android中使用FFmpeg得到視頻中的PCM和YUV數(shù)據(jù)

使用FFmpeg獲取PCM和YUV數(shù)據(jù)的流程基本上一樣的询刹,下面就以獲取YUV數(shù)據(jù)的流程為例,說明這個過程:

  • 初始化AVFormatContext 骄酗。
  • 打開文件妥畏,獲取流信息邦邦,獲取視頻流/音頻流。
  • 找到解碼器醉蚁,并且初始化解碼器燃辖。
  • 初始化AVPacket ,AVFrame 馍管,和buffer郭赐。
  • 對輸出格式進(jìn)行規(guī)范,如視頻的寬高确沸,音頻的采用率捌锭,聲道數(shù)等。
  • 讀取一幀數(shù)據(jù)罗捎,然后把數(shù)據(jù)寫入到文件观谦。
  • 讀完數(shù)據(jù)后,釋放內(nèi)存桨菜。
#include <jni.h>
#include <string.h>
#include <stdlib.h>
#include "android/log.h"

extern "C"{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"
};

#define LOGD(FORMAT,...) __android_log_print(ANDROID_LOG_INFO,"jni",FORMAT,##__VA_ARGS__);

extern "C"
JNIEXPORT jint JNICALL
Java_audioplayer_MainActivity_getYuvData(JNIEnv *env, jobject instance, jstring srcPath_,
                                                   jstring desPath_) {
    const char *srcPath = env->GetStringUTFChars(srcPath_, 0);
    const char *desPath = env->GetStringUTFChars(desPath_, 0);

    AVFormatContext *pFormatCtx;
    int i,videoIndex;
    AVCodecContext *pCodecCtx;
    AVCodec *pCodec;

    /* init */
    av_register_all();
    avformat_network_init();
    pFormatCtx = avformat_alloc_context();

    /* open file,find streams,and then find a video stream */
    if(avformat_open_input(&pFormatCtx,srcPath,NULL,NULL)!=0){
        LOGD("Couldn't open input stream.");
        return -1;
    }
    if(avformat_find_stream_info(pFormatCtx,NULL)<0){
        LOGD("Couldn't find stream information.");
        return -1;
    }
    videoIndex = -1;
    for(i=0;i<pFormatCtx->nb_streams;i++){
        if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO){
            videoIndex = i;
            break;
        }
    }
    if(videoIndex == -1){
        LOGD("Don't find a video stream.");
        return -1;
    }

    /* find a decoder */
    pCodecCtx = pFormatCtx->streams[videoIndex]->codec;
    pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
    if(pCodec == NULL){
        LOGD("Codec not found.\n");
        return -1;
    }
    if(avcodec_open2(pCodecCtx,pCodec,NULL)<0){
        LOGD("Could not open codec.");
        return -1;
    }

    LOGD("File format: %s.\nVideo duration: %lld.\nVideo width: %d,Video height: %d.",
        pFormatCtx->iformat->name,pFormatCtx->duration,pCodecCtx->width,pCodecCtx->height);

    /* init Buffer */
    AVPacket *packet = (AVPacket *)malloc(sizeof(AVPacket));
    AVFrame *pFrame = av_frame_alloc();
    AVFrame *pFrameYuv = av_frame_alloc();
    uint8_t *out_buffer = (uint8_t *)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P,pCodecCtx->width,pCodecCtx->height));
    avpicture_fill((AVPicture *)pFrameYuv,out_buffer,AV_PIX_FMT_YUV420P,pCodecCtx->width,pCodecCtx->height);

    struct SwsContext *swsContext= sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
        pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
    int ret,got_picture;

    FILE *fp = fopen(desPath,"wb+");
    int frame_cnt = 0;

    /* ever time read a frame and decode it */
    while(av_read_frame(pFormatCtx,packet)>=0){
        if(packet->stream_index == videoIndex){
            ret = avcodec_decode_video2(pCodecCtx,pFrame,&got_picture,packet);
            if(ret < 0){
                LOGD("Decode Error.");
                return -1;
            }
            if(got_picture){
                sws_scale(swsContext, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
                          pFrameYuv->data, pFrameYuv->linesize);
                LOGD("Decoded frame index: %d\n",frame_cnt);
                fwrite(pFrameYuv->data[0],1,pCodecCtx->width * pCodecCtx->height,fp);
                fwrite(pFrameYuv->data[1],1,pCodecCtx->width * pCodecCtx->height / 4,fp);
                fwrite(pFrameYuv->data[2],1,pCodecCtx->width * pCodecCtx->height / 4,fp);
                fflush(fp);
                frame_cnt++;
            }
        }
        av_free_packet(packet);
    }

    LOGD("Decode end");
    fclose(fp);
    sws_freeContext(swsContext);
    av_frame_free(&pFrameYuv);
    av_frame_free(&pFrame);
    avcodec_close(pCodecCtx);
    avformat_close_input(&pFormatCtx);

    env->ReleaseStringUTFChars(srcPath_, srcPath);
    env->ReleaseStringUTFChars(desPath_, desPath);
    return 0;
}

extern "C"
JNIEXPORT jint JNICALL
Java_audioplayer_MainActivity_getPcmData(JNIEnv *env, jobject instance, jstring srcPath_,
                                                   jstring desPath_) {
    const char *srcPath = env->GetStringUTFChars(srcPath_, 0);
    const char *desPath = env->GetStringUTFChars(desPath_, 0);

    AVFormatContext *pFormatCtx;
    int i,audioIndex;
    AVCodecContext *pCodecCtx;
    AVCodec *pCodec;

    /* init */
    av_register_all();
    avformat_network_init();
    pFormatCtx = avformat_alloc_context();

    /* open file,find streams,and then find a video stream */
    if(avformat_open_input(&pFormatCtx,srcPath,NULL,NULL)!=0){
        LOGD("Couldn't open input stream.");
        return -1;
    }
    if(avformat_find_stream_info(pFormatCtx,NULL)<0){
        LOGD("Couldn't find stream information.");
        return -1;
    }
    audioIndex = -1;
    for(i=0;i<pFormatCtx->nb_streams;i++){
        if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO){
            audioIndex = i;
            break;
        }
    }
    if(audioIndex == -1){
        LOGD("Don't find a video stream.");
        return -1;
    }

    /* find a decoder */
    pCodecCtx = pFormatCtx->streams[audioIndex]->codec;
    pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
    if(pCodec == NULL){
        LOGD("Codec not found.\n");
        return -1;
    }
    if(avcodec_open2(pCodecCtx,pCodec,NULL)<0){
        LOGD("Could not open codec.");
        return -1;
    }

    LOGD("File format: %s.\nVideo duration: %lld.\nVideo width: %d,Video height: %d.",
         pFormatCtx->iformat->name,pFormatCtx->duration,pCodecCtx->width,pCodecCtx->height);

    /* init Buffer */
    AVPacket *packet = (AVPacket *)malloc(sizeof(AVPacket));
    AVFrame *pFrame = av_frame_alloc();

    /* change sample rate and format to a standard format */
    SwrContext *swrCtx = swr_alloc();
    enum AVSampleFormat in_sample_fmt = pCodecCtx->sample_fmt;
    enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
    int in_sample_rate = pCodecCtx->sample_rate;
    int out_sample_rate = 44100;
    uint64_t in_ch_layout = pCodecCtx->channel_layout;
    uint64_t  out_ch_layout = AV_CH_LAYOUT_STEREO;

    swr_alloc_set_opts(swrCtx,out_ch_layout,out_sample_fmt,out_sample_rate,
        in_ch_layout,in_sample_fmt,in_sample_rate,0,NULL);
    swr_init(swrCtx);

    int out_channel_nb = av_get_channel_layout_nb_channels(out_ch_layout);
    uint8_t *out_buffer = (uint8_t *) av_malloc(2 * 44100);
    FILE *fp = fopen(desPath,"wb+");

    int ret,got_frame,frame_cnt = 0;

    while(av_read_frame(pFormatCtx,packet)>=0){
        if(packet->stream_index == audioIndex){
            ret = avcodec_decode_audio4(pCodecCtx,pFrame,&got_frame,packet);
            if(ret < 0){
                LOGD("Decode end");
            }
            if(got_frame){
                LOGD("Decoded frame index: %d\n",frame_cnt);
                swr_convert(swrCtx,&out_buffer,2 * 44100,(const uint8_t **)pFrame->data,pFrame->nb_samples);
                int out_buffer_size = av_samples_get_buffer_size(NULL, out_channel_nb, pFrame->nb_samples, out_sample_fmt, 1);
                fwrite(out_buffer, 1, out_buffer_size, fp);
                fflush(fp);
                frame_cnt++;
            }

        }
        av_free_packet(packet);
    }
    LOGD("Decode finish");
    fclose(fp);
    swr_free(&swrCtx);
    av_frame_free(&pFrame);
    avcodec_close(pCodecCtx);
    avformat_close_input(&pFormatCtx);

    env->ReleaseStringUTFChars(srcPath_, srcPath);
    env->ReleaseStringUTFChars(desPath_, desPath);
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市泻红,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌谊路,老刑警劉巖讹躯,帶你破解...
    沈念sama閱讀 211,948評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異潮梯,居然都是意外死亡,警方通過查閱死者的電腦和手機秉馏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,371評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來脱羡,“玉大人萝究,你說我怎么就攤上這事∏岷冢” “怎么了?”我有些...
    開封第一講書人閱讀 157,490評論 0 348
  • 文/不壞的土叔 我叫張陵氓鄙,是天一觀的道長业舍。 經(jīng)常有香客問我,道長舷暮,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,521評論 1 284
  • 正文 為了忘掉前任复颈,我火速辦了婚禮,結(jié)果婚禮上耗啦,老公的妹妹穿的比我還像新娘。我一直安慰自己帜讲,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 65,627評論 6 386
  • 文/花漫 我一把揭開白布仰担。 她就那樣靜靜地躺著玷氏,像睡著了一般腋舌。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上侦厚,一...
    開封第一講書人閱讀 49,842評論 1 290
  • 那天,我揣著相機與錄音诗宣,去河邊找鬼。 笑死召庞,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的篮灼。 我是一名探鬼主播徘禁,決...
    沈念sama閱讀 38,997評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼送朱!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起驶沼,我...
    開封第一講書人閱讀 37,741評論 0 268
  • 序言:老撾萬榮一對情侶失蹤回怜,失蹤者是張志新(化名)和其女友劉穎大年,沒想到半個月后玉雾,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,203評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡遏餐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,534評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了失都。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,673評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡粹庞,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出庞溜,到底是詐尸還是另有隱情,我是刑警寧澤流码,帶...
    沈念sama閱讀 34,339評論 4 330
  • 正文 年R本政府宣布又官,位于F島的核電站漫试,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏驾荣。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,955評論 3 313
  • 文/蒙蒙 一播掷、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧垒酬,春花似錦、人聲如沸伤溉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,770評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽宫静。三九已至券时,卻和暖如春孤里,著一層夾襖步出監(jiān)牢的瞬間橘洞,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,000評論 1 266
  • 我被黑心中介騙來泰國打工虏等, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留弄唧,地道東北人霍衫。 一個月前我還...
    沈念sama閱讀 46,394評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像澄干,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子麸俘,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,562評論 2 349

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

  • FFmpeg 介紹 FFmpeg是一套可以用來記錄惧笛、轉(zhuǎn)換數(shù)字音頻、視頻徐紧,并能將其轉(zhuǎn)化為流的開源計算機程序。采用LG...
    Y了個J閱讀 11,247評論 0 28
  • 教程一:視頻截圖(Tutorial 01: Making Screencaps) 首先我們需要了解視頻文件的一些基...
    90后的思維閱讀 4,678評論 0 3
  • ### YUV顏色空間 視頻是由一幀一幀的數(shù)據(jù)連接而成拂檩,而一幀視頻數(shù)據(jù)其實就是一張圖片嘲碧。 yuv是一種圖片儲存格式...
    天使君閱讀 3,264評論 0 4
  • ffmpeg是一個非常有用的命令行程序,它可以用來轉(zhuǎn)碼媒體文件愈涩。它是領(lǐng)先的多媒體框架FFmpeg的一部分,其有很多...
    城市之光閱讀 6,760評論 3 6
  • 現(xiàn)狀:現(xiàn)在視頻直播非常的火煤篙,所以在視頻直播開發(fā)中毁腿,使用的對視頻進(jìn)行遍解碼的框架顯得尤為重要了辑奈,其實已烤,這種框架蠻多的...
    ZHANG_GO閱讀 3,157評論 0 2