第三十五節(jié) 利用SurfaceView播放視頻文件

要實(shí)現(xiàn)的功能:我們將視頻文件(格式或者是mp4、flv、rmvb,這些都是壓縮后的格式)解碼成RGBA之后,利用SurfaceView來進(jìn)行播放。
cpp文件

#include <jni.h>
#include <string>
#include <android/log.h>
extern "C" {
//編碼
#include "libavcodec/avcodec.h"
//封裝格式處理
#include "libavformat/avformat.h"
//像素處理
#include "libswscale/swscale.h"
#include <android/native_window_jni.h>
#include <unistd.h>
}

#define LOGI(FORMAT,...) __android_log_print(ANDROID_LOG_INFO,"jason",FORMAT,##__VA_ARGS__);
#define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"jason",FORMAT,##__VA_ARGS__);
extern "C"
JNIEXPORT void JNICALL
Java_com_dongnao_ffmpegdemo_VideoView_render(JNIEnv *env, jobject instance, jstring input_,
                                             jobject surface) {
    const char *input = env->GetStringUTFChars(input_,false);
    av_register_all();

    //Allocate an AVFormatContext.
    AVFormatContext *pFormatCtx = avformat_alloc_context();
    //第四個(gè)參數(shù)是 可以傳一個(gè) 字典   是一個(gè)入?yún)⒊鰠ο?  0 on success
    if (avformat_open_input(&pFormatCtx, input, NULL, NULL) != 0) {
        LOGE("%s","打開輸入視頻文件失敗");
    }
    //獲取視頻信息  >=0 if OK
    if(avformat_find_stream_info(pFormatCtx,NULL) < 0){
        LOGE("%s","獲取視頻信息失敗");
        return;
    }

    int vidio_stream_idx=-1;

    //nb_streams:視音頻流的個(gè)數(shù)
    //一般情況有2個(gè)流即nb_streams=2,s->streams[0]為 視頻流,s->streams[1]為音頻流
    for (int i = 0; i < pFormatCtx->nb_streams; ++i) {
        if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
            LOGE("  找到視頻id %d", pFormatCtx->streams[i]->codec->codec_type);
            vidio_stream_idx=i;
            break;
        }
    }

    //獲取視頻編解碼器
    AVCodecContext *pCodecCtx=pFormatCtx->streams[vidio_stream_idx]->codec;
    LOGE("獲取視頻編碼器上下文 %p  ",pCodecCtx);
    //加密的用不了
    AVCodec *pCodex = avcodec_find_decoder(pCodecCtx->codec_id);
    LOGE("獲取視頻編碼 %p",pCodex);
    //zero on success, a negative value on error
    //該函數(shù)用于初始化一個(gè)視音頻編解碼器的AVCodecContext
    //利用給定的AVCodec結(jié)構(gòu)初始化AVCodecContext結(jié)構(gòu)
    if (avcodec_open2(pCodecCtx, pCodex, NULL)<0) {
        return;
    }
    //AVPacket結(jié)構(gòu)體中存放的是壓縮數(shù)據(jù)
    AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket));

    //AVFrame結(jié)構(gòu)體一般用于存儲(chǔ)原始數(shù)據(jù)(即非壓縮數(shù)據(jù),例如對視頻來說是YUV,RGB,對音頻來說是PCM)
    AVFrame *frame;
    frame = av_frame_alloc();
    //RGB
    AVFrame *rgb_frame = av_frame_alloc();
    //只有指定了AVFrame的像素格式、畫面大小才能真正分配內(nèi)存
    //給緩沖區(qū)分配內(nèi)存
    uint8_t   *out_buffer= (uint8_t *) av_malloc(avpicture_get_size(AV_PIX_FMT_RGBA, pCodecCtx->width, pCodecCtx->height));
    LOGE("寬  %d,  高  %d  ",pCodecCtx->width,pCodecCtx->height);

    //設(shè)置rgbFrame的緩沖區(qū),像素格式
    //avpicture_fill函數(shù)將out_buffer指向的數(shù)據(jù)填充到rgb_frame內(nèi),但并沒有拷貝,只是將rgb_frame結(jié)構(gòu)內(nèi)的data指針指向了out_buffer的數(shù)據(jù)
    int re= avpicture_fill((AVPicture *) rgb_frame, out_buffer, AV_PIX_FMT_RGBA, pCodecCtx->width, pCodecCtx->height);
    LOGE("申請內(nèi)存%d   ",re);

    int length=0;
    int got_frame;
    int frameCount=0;

    //SwsContext結(jié)構(gòu)體主要用于視頻圖像的轉(zhuǎn)換
    //SwrContext結(jié)構(gòu)體主要用于音頻重采樣,比如采樣率轉(zhuǎn)換,聲道轉(zhuǎn)換
    SwsContext *swsContext = sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,
                                            pCodecCtx->width,pCodecCtx->height,AV_PIX_FMT_RGBA,SWS_BICUBIC,NULL,NULL,NULL
    );
    ANativeWindow *nativeWindow = ANativeWindow_fromSurface(env, surface);
    //視頻緩沖區(qū)
    ANativeWindow_Buffer outBuffer;
    //0 if OK, < 0 on error or end of file
    while (av_read_frame(pFormatCtx, packet)>=0) {
        if (packet->stream_index == vidio_stream_idx) {
            //看下第三個(gè)參數(shù):@param[in,out] got_picture_ptr Zero if no frame could be decompressed, otherwise, it is nonzero.
            //這是個(gè)"入?yún)⒊鰠? 參數(shù)
            length = avcodec_decode_video2(pCodecCtx, frame, &got_frame, packet);
            LOGE(" 獲得長度   %d ", length);

            if (got_frame) {
            //繪制之前   配置一些信息  比如寬高   格式
                ANativeWindow_setBuffersGeometry(nativeWindow, pCodecCtx->width, pCodecCtx->height,
                                                 WINDOW_FORMAT_RGBA_8888);
            //繪制
                ANativeWindow_lock(nativeWindow, &outBuffer, NULL);
                LOGI("解碼%d幀",frameCount++);

                sws_scale(swsContext, (const uint8_t *const *) frame->data, frame->linesize, 0
                        , pCodecCtx->height, rgb_frame->data,
                          rgb_frame->linesize);
                //rgb_frame是有畫面數(shù)據(jù)
                uint8_t *dst= (uint8_t *) outBuffer.bits;
                //拿到一行有多少個(gè)字節(jié) RGBA
                int destStride=outBuffer.stride*4;
                //像素?cái)?shù)據(jù)的首地址
                //AVFrame 中對于packed格式的數(shù)據(jù)(例如RGB24),會(huì)存到data[0]里面。
                //對于planar格式的數(shù)據(jù)(例如YUV420P),則會(huì)分開成data[0],data[1],data[2]...(YUV420P中data[0]存Y,data[1]存U,data[2]存V)
                uint8_t * src= (uint8_t *) rgb_frame->data[0];
                //實(shí)際內(nèi)存一行字節(jié)數(shù)量
                //For video, size in bytes of each picture line.
                //For audio, size in bytes of each plane.
                int srcStride = rgb_frame->linesize[0];

                for (int i = 0; i < pCodecCtx->height; ++i) {
                   // memcpy(void *dest, const void *src, size_t n) 內(nèi)存拷貝
                    memcpy(dst + i * destStride,  src + i * srcStride, srcStride);
                }

                ANativeWindow_unlockAndPost(nativeWindow);
                usleep(1000 * 16);
            }
        }
        av_free_packet(packet);
    }
    ANativeWindow_release(nativeWindow);
    av_frame_free(&frame);
    avcodec_close(pCodecCtx);
    avformat_free_context(pFormatCtx);
    env->ReleaseStringUTFChars(input_, input);
}

VideoView

package com.dongnao.ffmpegdemo;

import android.content.Context;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by david on 2017/9/20.
 */

public class VideoView  extends SurfaceView {
    static{
        System.loadLibrary("avcodec-56");
        System.loadLibrary("avdevice-56");
        System.loadLibrary("avfilter-5");
        System.loadLibrary("avformat-56");
        System.loadLibrary("avutil-54");
        System.loadLibrary("postproc-53");
        System.loadLibrary("swresample-1");
        System.loadLibrary("swscale-3");
        System.loadLibrary("native-lib");
    }
    public VideoView(Context context) {
        super(context);
    }

    public VideoView(Context context, AttributeSet attrs) {
      super(context, attrs);
        init();

    }

    private void init() {
        SurfaceHolder holder = getHolder();
        holder.setFormat(PixelFormat.RGBA_8888);
    }

    public VideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void player(final String input) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //繪制功能 不需要交給SurfaveView
                //VideoView.this.getHolder().getSurface()
                render(input, VideoView.this.getHolder().getSurface());
            }
        }).start();
    }

    public native void render(String input, Surface surface);
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 學(xué)習(xí)目標(biāo):Android視頻播放功能在Android應(yīng)用場景(掌握)視頻播放第一種方式使用系統(tǒng)自帶的播放器(掌握)...
    Anwfly閱讀 1,684評論 0 1
  • 一.在Android中,我們有三種方式來實(shí)現(xiàn)視頻的播放:1、使用其自帶的播放器。指定Action為ACTION_V...
    鄭_S_W閱讀 455評論 0 0
  • 1.編碼方式和封裝格式 常見的AVI、RMVB、MKV、ASF、WMV、MP4、3GP、FLV等文件其實(shí)只能算是...
    如山似水lbb閱讀 850評論 0 1
  • 我們有三種方式來實(shí)現(xiàn)視頻的播放: 1、使用其自帶的播放器。指定Action為ACTION_VIEW,Data為Ur...
    ItemWang閱讀 728評論 0 1
  • 前言 早年看電影是在在線的視頻網(wǎng)站上看,但是往往有些電影是需要會(huì)員或者是購買才能看的,作為一個(gè)窮學(xué)生讓我為了看一個(gè)...
    萌噠噠的小貔貅閱讀 18,235評論 1 18