1. 程式人生 > >android ffmpeg+OpenGL播放yuv+openSL 快放 慢放 視訊播放器

android ffmpeg+OpenGL播放yuv+openSL 快放 慢放 視訊播放器

這裡是完整的音視訊播放器,功能如下(這裡有iOS版的):
這裡寫圖片描述
視訊是通過opengl 播放yuv資料,音訊是opensl播放。
app執行流程如下圖:
這裡寫圖片描述
紅色虛線內的是一個執行緒的執行,總共涉及到四個執行緒。
java層幾乎沒有播放器的內容,ffmpeg,opengl,opensl都是在c++層執行,所以可以原封不動的遷移到其他平臺,如ios,不過c/c++程式碼ios程式設計師看起來不太友好,有ios版的,ios版的有yuv->RGB->image的方法,有ffmpeg解碼播放流程圖,解碼播放流程一目瞭然。
看一下app表現,小米6播放每分鐘100M等級的視訊:
播放每分鐘100M等級的視訊
可以看到cpu使用在10%左右,很省電了有沒有100M每分鐘,一部電影是十幾G的清晰度。
再看常規清晰度720p:
這裡寫圖片描述


cpu消耗只有3%左右,這也就是直播清晰度了,這cpu消耗還能說什麼。
看記憶體優化:
這裡寫圖片描述
整個播放過程native層記憶體佔用都在15M左右波動,Graphics佔用記憶體也沒變化,播放過程中記憶體釋放很到位,沒有記憶體增長。大家可以自行測試。
這裡給大家看下ffmpeg解碼程式碼:
FFmpeg.h

//
// Created by huizai on 2017/11/22.
//

#ifndef FFMPEG_DEMO_FFMPEGDECODER_H
#define FFMPEG_DEMO_FFMPEGDECODER_H
#include "JniDefine.h"
#include "YUV_GL_DATA.h"
extern "C" { //編碼 #include "libavcodec/avcodec.h" //封裝格式處理 #include "libavformat/avformat.h" //畫素處理 #include "libswscale/swscale.h" #include "libswresample/swresample.h" } //定義音訊重取樣後的引數 #define SAMPLE_SIZE 16 #define SAMPLE_RATE 44100 #define CHANNEL 2 typedef struct FFmpeg{ int totleMs; //音訊播放時間
int aFps; //視訊播放時間 int vFps; //視訊流索引 int videoStreamIndex; int audioStreamIndex; int sampleRate; int sampleSize; int channel; //音訊貞資料的長度 int pcmDataLength; AVFormatContext * pFormatCtx; AVCodecContext * pVideoCodecCtx; AVCodecContext * pAudioCodecCtx; AVFrame * pYuv; AVFrame * pPcm; AVCodec * pVideoCodec; //視訊解碼器 AVCodec * pAudioCodec; //音訊解碼器 struct SwsContext * pSwsCtx; SwrContext * pSwrCtx; const char * url; AVPacket pkt; char * audioData; H264YUV_Frame yuvFrame; }Decoder; int OpenAndInitDecoder(Decoder * decoder); int Read(Decoder * decoder); int Decode(Decoder * decoder,AVPacket packet); int YuvToGLData(Decoder *decoder); int ToPcm(Decoder * decoder,AACFrame * frame); void printError(const char* flag,int ret); double r2d(AVRational r); #endif //FFMPEG_DEMO_FFMPEGDECODER_H
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

FFmpeg.cpp

//
// Created by huizai on 2017/11/22.
//

#include "FFmpeg.h"


int OpenAndInitDecoder(Decoder * decoder){

    //1.註冊所有元件
    av_register_all();
    avformat_network_init();
    //2.開啟輸入視訊檔案
    //封裝格式上下文,統領全域性的結構體,儲存了視訊檔案封裝格式的相關資訊
    decoder->pFormatCtx = avformat_alloc_context();
    int ret = avformat_open_input(&decoder->pFormatCtx, decoder->url, NULL, NULL);
    if (ret != 0) {
        return  ret;
    } else{
        FFLOGI("視訊長度:%d",decoder->pFormatCtx->duration);
    }
    decoder->totleMs = (int)(decoder->pFormatCtx->duration/AV_TIME_BASE)*1000;
    avformat_find_stream_info(decoder->pFormatCtx, NULL);
    //分別找到音訊視訊解碼器並開啟解碼器
    for (int i = 0; i < decoder->pFormatCtx->nb_streams; i++) {
        AVStream *stream = decoder->pFormatCtx->streams[i];
        AVCodec * codec = avcodec_find_decoder(stream->codecpar->codec_id);
        AVCodecContext * codecCtx = avcodec_alloc_context3(codec);
        avcodec_parameters_to_context(codecCtx, stream->codecpar);

        if (codecCtx->codec_type == AVMEDIA_TYPE_VIDEO) {
            printf("video\n");
            decoder->videoStreamIndex = i;
            decoder->pVideoCodec  = codec;
            decoder->pVideoCodecCtx = codecCtx;
            int err = avcodec_open2(decoder->pVideoCodecCtx, decoder->pVideoCodec, NULL);
            if (err != 0) {
                char buf[1024] = {0};
                av_strerror(err, buf, sizeof(buf));
                printf("open videoCodec error:%s", buf);
                return false;
            }
        }
        if (codecCtx->codec_type == AVMEDIA_TYPE_AUDIO) {
            printf("audio\n");
            decoder->audioStreamIndex = i;
            decoder->pAudioCodec  = codec;
            decoder->pAudioCodecCtx = codecCtx;
            int err = avcodec_open2(decoder->pAudioCodecCtx, decoder->pAudioCodec, NULL);
            if (err != 0) {
                char buf[1024] = {0};
                av_strerror(err, buf, sizeof(buf));
                printf("open audionCodec error:%s", buf);
                return false;
            }
            if (codecCtx->sample_rate != SAMPLE_RATE) {
                decoder->sampleRate = codecCtx->sample_rate;
            }
        }
    }
    decoder ->pYuv = av_frame_alloc();
    decoder ->pPcm = av_frame_alloc();
    decoder ->channel = CHANNEL;
    decoder ->sampleSize = SAMPLE_SIZE;
    decoder ->sampleRate = decoder->pAudioCodecCtx->sample_rate;
   // printf("open acodec success! sampleRate:%d  channel:%d  sampleSize:%d fmt:%d\n",
         //  decoder->sampleRate,decoder->channel,decoder->sampleSize,decoder->pAudioCodecCtx->sample_fmt);
    FFLOGI("open acodec success! sampleRate:%d  channel:%d  fmt:%d\n",
           decoder->pAudioCodecCtx->sample_rate,decoder->pAudioCodecCtx->channels,decoder->pAudioCodecCtx->sample_fmt);
    return  ret;
}
int  Read(Decoder * decoder){

    //這裡先不加執行緒鎖,在啟動多執行緒的地方統一加鎖
    // AVPacket * pkt = malloc(sizeof(AVPacket));
    if (!decoder->pFormatCtx) {
        return -1;
    }
    int err = av_read_frame(decoder->pFormatCtx,&decoder->pkt);
    if (err != 0) {
        printError("av_read_pkt_error:",err);
        if (err == -541478725){
            //讀取檔案結束
            return -9;
        }
        return  -2;
    }
    return  0;
}
int Decode(Decoder* decoder,AVPacket packet){
    if (!decoder->pFormatCtx) {
        return -1;
    }
    //分配AVFream 空間
    if (decoder->pYuv == NULL) {
        decoder->pYuv = av_frame_alloc();
    }
    if (decoder->pPcm == NULL) {
        decoder->pPcm = av_frame_alloc();
    }
    AVCodecContext * pCodecCtx;
    AVFrame * tempFrame;
    if (packet.stream_index == decoder->videoStreamIndex) {
        pCodecCtx = decoder->pVideoCodecCtx;
        tempFrame = decoder->pYuv;
    }else if (packet.stream_index == decoder->audioStreamIndex){
        pCodecCtx = decoder->pAudioCodecCtx;
        tempFrame = decoder->pPcm;
    }else{
        return -1;
    }
    if (!pCodecCtx) {
        return -1;
    }
    int re = avcodec_send_packet(pCodecCtx,&packet);
    if (re != 0) {
        char errorBuf[1024] = {0};
        av_make_error_string(errorBuf,1024,re);
        FFLOGE("send pkt error:%s",errorBuf);
        return -1;
    }
    re = avcodec_receive_frame(pCodecCtx, tempFrame);
    if (re != 0) {
        char errorBuf[1024] = {0};
        av_make_error_string(errorBuf,1024,re);
        FFLOGE("receive av_data error:%s",errorBuf);
        return -1;
    }
    if (packet.stream_index == decoder->videoStreamIndex) {
        decoder->vFps = (int)((packet.pts * r2d(decoder->pFormatCtx->streams[decoder->videoStreamIndex]->time_base))*1000);
    }else if (packet.stream_index == decoder->audioStreamIndex){
        decoder->aFps = (int)((packet.pts * r2d(decoder->pFormatCtx->streams[decoder->audioStreamIndex]->time_base))*1000);
    }
    FFLOGI("[D]");
    return 0;
}
int Min(int a,int b){
    return a>b?b:a;
}
void copyDecodedFrame(unsigned char *src, unsigned char *dist,int linesize, int width, int height)
{
    width = Min(linesize, width);
    if (sizeof(dist) == 0) {
        return;
    }
    for (int i = 0; i < height; ++i) {
        memcpy(dist, src, width);
        dist += width;
        src += linesize;
    }
}

int   YuvToGLData(Decoder *decoder){
    if (!decoder->pFormatCtx || !decoder->pYuv ||decoder-> pYuv->linesize[0] <= 0) {
        return -1;
    }
    //把資料重新封裝成opengl需要的格式
    unsigned int lumaLength= (unsigned int)(decoder->pYuv->height)*(Min(decoder->pYuv->linesize[0], decoder->pYuv->width));
    unsigned int chromBLength=(unsigned int)((decoder->pYuv->height)/2)*(Min(decoder->pYuv->linesize[1], (decoder->pYuv->width)/2));
    unsigned int chromRLength=(unsigned int)((decoder->pYuv->height)/2)*(Min(decoder->pYuv->linesize[2], (decoder->pYuv->width)/2));

    decoder->yuvFrame.luma.dataBuffer = (unsigned char*)malloc(lumaLength);
    decoder->yuvFrame.chromaB.dataBuffer = (unsigned char*)malloc(chromBLength);
    decoder->yuvFrame.chromaR.dataBuffer = (unsigned char*)malloc(chromRLength);

    decoder->yuvFrame.width=(unsigned int)decoder->pYuv->width;
    decoder->yuvFrame.height=(unsigned int)decoder->pYuv->height;

    if (decoder->pYuv->height <= 0) {
        free(decoder->yuvFrame.luma.dataBuffer);
        free(decoder->yuvFrame.chromaB.dataBuffer);
        free(decoder->yuvFrame.chromaR.dataBuffer);
        return -1;
    }

    copyDecodedFrame(decoder->pYuv->data[0],decoder->yuvFrame.luma.dataBuffer,decoder->pYuv->linesize[0],
                     decoder->pYuv->width,decoder->pYuv->height);
    copyDecodedFrame(decoder->pYuv->data[1], decoder->yuvFrame.chromaB.dataBuffer,decoder->pYuv->linesize[1],
                     decoder->pYuv->width / 2,decoder->pYuv->height / 2);
    copyDecodedFrame(decoder->pYuv->data[2], decoder->yuvFrame.chromaR.dataBuffer,decoder->pYuv->linesize[2],
                     decoder->pYuv->width / 2,decoder->pYuv->height / 2);
    return 0;
}
int ToPcm(Decoder * decoder,AACFrame * frame){
    if (!decoder->pFormatCtx || !decoder->pPcm) {
        return -1;
    }
   // printf("sample_rate:%d,channels:%d,sample_fmt:%d,channel_layout:%llu,nb_samples:%d\n",pAudioCodecCtx->sample_rate,pAudioCodecCtx->channels,pAudioCodecCtx->sample_fmt,pAudioCodecCtx->channel_layout,pPcm->nb_samples);
    //音訊重取樣
    if (decoder->pSwrCtx == NULL) {
        decoder->pSwrCtx = swr_alloc();
        swr_alloc_set_opts(decoder->pSwrCtx,
                           AV_CH_LAYOUT_STEREO,//2聲道立體聲
                           AV_SAMPLE_FMT_S16,  //取樣大小 16位
                           decoder->sampleRate,
                           decoder->pAudioCodecCtx->channel_layout,
                           decoder->pAudioCodecCtx->sample_fmt,// 樣本型別
                           decoder->pAudioCodecCtx->sample_rate,
                           0, 0);
        int ret = swr_init(decoder->pSwrCtx);
        char errorBuf[1024] = {0};
        av_make_error_string(errorBuf,1024,ret);
        FFLOGE("swr_init error:%s",errorBuf);
    }
    uint8_t * tempData[1];
    tempData[0] = (uint8_t*)frame->dataBuffer;
    int len = swr_convert(decoder->pSwrCtx, tempData, 10000, (const uint8_t**)decoder->pPcm->data,decoder->pPcm->nb_samples);
    if (len < 0) {
        char errbuf[1024] = {0};
        FFLOGE("swr_convert error:%d",len);
        return 0;
    }
    int outSize = av_samples_get_buffer_size(NULL,
                                             CHANNEL,
                                             len,
                                             AV_SAMPLE_FMT_S16,0);
    frame->length = (unsigned int)outSize;
    FFLOGI("nb_smples:%d,des_smples:%d,outSize:%d",decoder->pPcm->nb_samples,len,outSize);
    return 0;
}

void printError(const char * flag,int ret){
    char errorbuf[1024] = {0};
    av_make_error_string(errorbuf, 1024, ret);
    FFLOGE("%s,ret:%d,%s", flag, ret, errorbuf);
}
double r2d(AVRational r){
    return r.num == 0 || r.den == 0 ? 0.:(double)r.num/(double)r.den;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229

可以跟iOS版的對比一下,根本沒區別,都是一樣的,要不怎麼說跨平臺技術呢。程式碼說明可以去看ios版的有簡單說明。也可以下載原始碼debug進行了解。

說明一點,想要做優化的,就是我這裡執行緒鎖加的很粗糙,這樣會造成不同執行緒對資源的等待,會有點點不流暢,應該精細到每一句就好了,自己去調吧。