FFMPEG+OPENSLES+生產(chǎn)者模式播放音視頻(二)

視頻播放

準(zhǔn)備工作

1. 首先轿亮,定義一個(gè)播放控件PlayerView
public class PlayerView extends TextureView implements TextureView.SurfaceTextureListener {

    public PlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setSurfaceTextureListener(this);
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
        LogUtils.e("onSurfaceTextureAvailable:width=" + width + ",height=" + height);
        setSurface(new Surface(surfaceTexture), width, height);
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

    }

    /**
     * ndk調(diào)用這個(gè)方法設(shè)置視頻的寬高
     *
     * @param videoWidth
     * @param videoHeight
     */
    public void onNativeGetVideoSize(int videoWidth, int videoHeight) {
        LogUtils.e("onNativeGetVideoSize:videoWidth=" + videoWidth + ",videoHeight=" + videoHeight);
        int width = getWidth();
        int height = getHeight();
        float scaleX = videoWidth * 1.0f / width;
        float scaleY = videoHeight * 1.0f / height;
        float maxScale = Math.max(scaleX, scaleY);//要保證寬度或者高度全屏
        scaleX /= maxScale;
        scaleY /= maxScale;
        Matrix matrix = new Matrix();
        matrix.setScale(scaleX, scaleY, width / 2, height / 2);
        setTransform(matrix);
    }

    private native void setSurface(Surface surface, int width, int height);

    public native void play(String path);
}
2. 編寫頁(yè)面布局activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.levylin.ffmpegdemo.PlayerView
        android:id="@+id/playerView"
        android:layout_width="match_parent"
        android:layout_height="150dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/play_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="playVideo"
            android:text="播放" />
    </LinearLayout>
</LinearLayout>
3.編寫主界面MainActivity
class MainActivity : AppCompatActivity() {

    val URL = "rtmp://live.hkstv.hk.lxdns.com/live/hks"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        play_btn.setOnClickListener { playVideo() }
    }

    fun playVideo() {
        playerView.play(URL)
    }

    companion object {

        init {
            System.loadLibrary("native-lib")
        }
    }
}
4.定義權(quán)限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
5.CMakeLists.txt修改

add_library( native-lib
             SHARED
             src/main/cpp/native-lib.cpp )

改為

file(GLOB my_source src/main/cpp/*.cpp)
add_library( native-lib
             SHARED
             ${my_source} )

主要是為了方便后續(xù)新增別的cpp文件,不需要手動(dòng)再去修改CMakeLists.txt

C++核心代碼

1.定義一個(gè)my-log.h
#ifndef FFMPEGDEMO_MY_LOG_H
#define FFMPEGDEMO_MY_LOG_H

#include <android/log.h>

#define TAG "LEVY"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__)

#endif //FFMPEGDEMO_MY_LOG_H
2.定義一個(gè)FFmpegVideo的h文件和C++文件

FFmpegVideo.h

#ifndef FFMPEGDEMO_FFMPEGVIDEO_H
#define FFMPEGDEMO_FFMPEGVIDEO_H

#include "my-log.h"
#include <queue>
#include <unistd.h>
#include <pthread.h>

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

using namespace std;

class FFmpegVideo {
public:
    FFmpegVideo();

    ~FFmpegVideo();

    /**
     * 從隊(duì)列中獲取一個(gè)包
     * @param packet
     * @return
     */
    int get(AVPacket *packet);

    /**
     * 往隊(duì)列中插入一個(gè)包
     * @param packet
     * @return
     */
    int put(AVPacket *packet);

    /**
     * 播放
     */
    void play();

    /**
     * 結(jié)束
     */
    void stop();

    /**
     * 設(shè)置解碼器上下文
     * @param avCodecContext
     */
    void setAVCodecPacket(AVCodecContext *avCodecContext);

    /**
     * 播放回調(diào)
     * @param call
     */
    void setPlayCall(void(*call)(AVFrame *frame));

public:
    int isPlay;//是否播放
    int index;//視頻流索引
    queue<AVPacket *> video_queue;//包隊(duì)列
    pthread_t tid;//播放線程id
    AVCodecContext *avCodecContext;//解碼器上下文
    pthread_mutex_t mutex;//互斥鎖
    pthread_cond_t cond;
};

#endif //FFMPEGDEMO_FFMPEGVIDEO_H

FFmpegVideo.cpp

#include "FFmpegVideo.h"

/**
 * ANativeWindow繪制的方法回調(diào)
 * @param frame 
 */
static void (*video_call)(AVFrame *frame);

/**
 * 視頻播放線程
 * @param data 
 * @return 
 */
void *playVideo(void *data) {
    LOGE("播放視頻線程");
    FFmpegVideo *video = (FFmpegVideo *) data;
    AVCodecContext *pContext = video->avCodecContext;
    //像素格式
    AVPixelFormat pixelFormat = AV_PIX_FMT_RGBA;
    SwsContext *swsContext = sws_getContext(pContext->width,
                                            pContext->height,
                                            pContext->pix_fmt,
                                            pContext->width,
                                            pContext->height,
                                            pixelFormat,
                                            SWS_BICUBIC,
                                            NULL,
                                            NULL,
                                            NULL);
    LOGE("獲取swsContext完成");
    //要畫在window上的frame
    AVFrame *rgb_frame = av_frame_alloc();
    uint8_t *out_buffer = (uint8_t *) av_malloc(
            (size_t) avpicture_get_size(pixelFormat, pContext->width, pContext->height));
    avpicture_fill((AVPicture *) rgb_frame, out_buffer, pixelFormat, pContext->width,
                   pContext->height);
    LOGE("設(shè)置rgb_frame完成");
    int got_frame;
    AVFrame *frame = av_frame_alloc();
    AVPacket *packet = (AVPacket *) av_malloc(sizeof(AVPacket));
    av_init_packet(packet);
    while (video->isPlay) {
        video->get(packet);
        avcodec_decode_video2(pContext, frame, &got_frame, packet);
        if (!got_frame) {
            continue;
        }
        sws_scale(swsContext, (const uint8_t *const *) frame->data, frame->linesize, 0,
                  frame->height, rgb_frame->data, rgb_frame->linesize);
        video_call(rgb_frame);
        usleep(16 * 1000);//這邊先暫定時(shí)間是16毫秒
    }
}

FFmpegVideo::FFmpegVideo() {
    pthread_mutex_init(&mutex, NULL);//初始化互斥鎖
    pthread_cond_init(&cond, NULL);//初始化條件
}

FFmpegVideo::~FFmpegVideo() {

}

int FFmpegVideo::get(AVPacket *packet) {
    LOGE("獲取視頻包");
    pthread_mutex_lock(&mutex);
    if (isPlay) {
        if (video_queue.empty()) {
            LOGE("列表為空");
            pthread_cond_wait(&cond, &mutex);
        } else {
            AVPacket *packet1 = video_queue.front();
            video_queue.pop();
            if (av_packet_ref(packet, packet1) < 0) {
                LOGE("獲取包.....克隆失敗");
                return 0;
            }
            av_free_packet(packet1);
        }
    }
    pthread_mutex_unlock(&mutex);
    return 1;
}

int FFmpegVideo::put(AVPacket *packet) {
    LOGE("插入視頻包");
    AVPacket *packet1 = (AVPacket *) malloc(sizeof(AVPacket));
    if (av_copy_packet(packet1, packet) < 0) {
        LOGE("克隆失敗");
        return 0;
    }
    pthread_mutex_lock(&mutex);
    video_queue.push(packet1);
    av_free_packet(packet);
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);
    return 1;
}

void FFmpegVideo::play() {
    isPlay = 1;
    pthread_create(&tid, NULL, playVideo, this);
}

void FFmpegVideo::stop() {
    isPlay = 0;
}

void FFmpegVideo::setAVCodecPacket(AVCodecContext *avCodecContext) {
    this->avCodecContext = avCodecContext;
}

void FFmpegVideo::setPlayCall(void (*call)(AVFrame *)) {
    video_call = call;
}

3.編寫jni實(shí)現(xiàn)方法

#include <jni.h>
#include <string>
#include "FFmpegVideo.h"
#include <android/native_window.h>
#include <android/native_window_jni.h>

pthread_t main_tid;
int isPlaying;
ANativeWindow *window;
const char *path;
FFmpegVideo *video;

jobject jobj;
JavaVM *jvm;

void call_video_play(AVFrame *frame) {
    if (!window) {
        LOGE("window is null");
        return;
    }
    ANativeWindow_Buffer buffer;
    if (ANativeWindow_lock(window, &buffer, NULL) < 0) {
        LOGE("window 鎖住失敗");
        return;
    }
    uint8_t *dst = (uint8_t *) buffer.bits;
    int dstStride = buffer.stride * 4;
    uint8_t *src = frame->data[0];
    int srcStride = frame->linesize[0];
    for (int i = 0; i < video->avCodecContext->height; ++i) {
        memcpy(dst + i * dstStride, src + i * srcStride, (size_t) srcStride);
    }
    ANativeWindow_unlockAndPost(window);
}

void *proccess(void *data) {
    av_register_all();//使用ffmpeg必須要注冊(cè)
    avformat_network_init();//如果播放網(wǎng)絡(luò)視頻戈鲁,需要注冊(cè)

    AVFormatContext *formatContext = avformat_alloc_context();
    if (avformat_open_input(&formatContext, path, NULL, NULL) < 0) {
        LOGE("打開視頻失敗");
    }
    LOGE("打開視頻成功");
    if (avformat_find_stream_info(formatContext, NULL) < 0) {
        LOGE("尋找流信息失敗");
    }
    LOGE("尋找流信息成功");
    for (int i = 0; i < formatContext->nb_streams; ++i) {
        AVStream *stream = formatContext->streams[i];
        AVCodecContext *codecContext = stream->codec;
        //獲取解碼器
        AVCodec *codec = avcodec_find_decoder(codecContext->codec_id);
        if (avcodec_open2(codecContext, codec, NULL) < 0) {
            LOGE("打開解碼器失敗");
            continue;
        }
        if (codecContext->codec_type == AVMEDIA_TYPE_VIDEO) {
            video->index = i;
            video->setAVCodecPacket(codecContext);
            int width = codecContext->width;
            int height = codecContext->height;
            LOGE("視頻:寬=%d,高寬=%d", width, height);
            JNIEnv *env;
            jvm->AttachCurrentThread(&env, 0);
            LOGE("獲取env");
            jclass clazz = env->GetObjectClass(jobj);
            LOGE("Native found Java jobj Class :%d", clazz ? 1 : 0);
            jmethodID mid = env->GetMethodID(clazz, "onNativeGetVideoSize", "(II)V");
            if (env && jobj && mid) {
                LOGE("給JAVA中設(shè)置寬高");
                env->CallVoidMethod(jobj, mid, width, height);
            }
            ANativeWindow_setBuffersGeometry(window, width, height,
                                             WINDOW_FORMAT_RGBA_8888);
        }
    }
    LOGE("開始播放");
    video->play();
    AVPacket *packet = (AVPacket *) av_malloc(sizeof(AVPacket));
    while (isPlaying) {
        if (av_read_frame(formatContext, packet) < 0) {
            LOGE("讀取幀失敗");
            av_packet_unref(packet);
            continue;
        }
        if (video && video->isPlay && video->index == packet->stream_index) {
            video->put(packet);
        }
        av_packet_unref(packet);
    }
    isPlaying = 0;
    if (video && video->isPlay) {
        video->stop();
    }
    av_free_packet(packet);
    avformat_free_context(formatContext);
    pthread_exit(0);
}

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    jvm = vm;
    JNIEnv *env = NULL;
    jint result = -1;
    if (jvm) {
        LOGE("jvm init success");
    }
    if (vm->GetEnv((void **) &env, JNI_VERSION_1_4) != JNI_OK) {
        return result;
    }
    return JNI_VERSION_1_4;
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_levylin_ffmpegdemo_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

extern "C"
JNIEXPORT void JNICALL
Java_com_levylin_ffmpegdemo_PlayerView_setSurface(JNIEnv *env, jobject instance, jobject surface,
                                                  jint width, jint height) {
    if (!window) {
        window = ANativeWindow_fromSurface(env, surface);
    }
    if (!jobj) {
        jobj = env->NewGlobalRef(instance);
    }
}
extern "C"
JNIEXPORT void JNICALL
Java_com_levylin_ffmpegdemo_PlayerView_play(JNIEnv *env, jobject instance, jstring path_) {
    path = env->GetStringUTFChars(path_, 0);
    video = new FFmpegVideo;
    video->setPlayCall(call_video_play);
    isPlaying = 1;
    pthread_create(&main_tid, NULL, proccess, NULL);
    env->ReleaseStringUTFChars(path_, path);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌突诬,老刑警劉巖苫拍,帶你破解...
    沈念sama閱讀 222,627評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異旺隙,居然都是意外死亡怯疤,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,180評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門催束,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人伏社,你說我怎么就攤上這事抠刺。” “怎么了摘昌?”我有些...
    開封第一講書人閱讀 169,346評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵速妖,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我聪黎,道長(zhǎng)罕容,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,097評(píng)論 1 300
  • 正文 為了忘掉前任稿饰,我火速辦了婚禮锦秒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘喉镰。我一直安慰自己旅择,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,100評(píng)論 6 398
  • 文/花漫 我一把揭開白布侣姆。 她就那樣靜靜地躺著生真,像睡著了一般。 火紅的嫁衣襯著肌膚如雪捺宗。 梳的紋絲不亂的頭發(fā)上柱蟀,一...
    開封第一講書人閱讀 52,696評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音蚜厉,去河邊找鬼长已。 笑死,一個(gè)胖子當(dāng)著我的面吹牛昼牛,可吹牛的內(nèi)容都是我干的痰哨。 我是一名探鬼主播,決...
    沈念sama閱讀 41,165評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼匾嘱,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼斤斧!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起霎烙,我...
    開封第一講書人閱讀 40,108評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤撬讽,失蹤者是張志新(化名)和其女友劉穎蕊连,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體游昼,經(jīng)...
    沈念sama閱讀 46,646評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡甘苍,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,709評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了烘豌。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片载庭。...
    茶點(diǎn)故事閱讀 40,861評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖廊佩,靈堂內(nèi)的尸體忽然破棺而出囚聚,到底是詐尸還是另有隱情,我是刑警寧澤标锄,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布顽铸,位于F島的核電站,受9級(jí)特大地震影響料皇,放射性物質(zhì)發(fā)生泄漏谓松。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,196評(píng)論 3 336
  • 文/蒙蒙 一践剂、第九天 我趴在偏房一處隱蔽的房頂上張望鬼譬。 院中可真熱鬧,春花似錦逊脯、人聲如沸拧簸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,698評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)盆赤。三九已至,卻和暖如春歉眷,著一層夾襖步出監(jiān)牢的瞬間牺六,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,804評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工汗捡, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留淑际,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,287評(píng)論 3 379
  • 正文 我出身青樓扇住,卻偏偏與公主長(zhǎng)得像春缕,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子艘蹋,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,860評(píng)論 2 361

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

  • demo鏈接在文末锄贼。 在Android Studio中有3種方法生成so文件。 最初的時(shí)候女阀,我曾經(jīng)使用過Visua...
    梧葉已秋聲閱讀 33,763評(píng)論 5 26
  • 前段時(shí)間由于做比賽的事宅荤,一直都沒時(shí)間寫博客屑迂,現(xiàn)在終于可以補(bǔ)上一篇了,一直想學(xué)習(xí)一點(diǎn)NDK開發(fā)的知識(shí)冯键,但是遲遲沒有動(dòng)...
    冰鑒IT閱讀 1,763評(píng)論 7 18
  • Android NDK 開發(fā)入門(CMake) 本文主要記錄以及簡(jiǎn)單介紹Ndk 的入門惹盼,以及google目前推薦的...
    Straw_Hat閱讀 1,217評(píng)論 0 0
  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程,因...
    小菜c閱讀 6,450評(píng)論 0 17
  • 說起鍋包肉是我大東北的名菜惫确,起源是光緒年間始創(chuàng)自哈爾濱道臺(tái)府府尹杜學(xué)贏廚師鄭興文之手手报。 作為一個(gè)地道的冰城人,對(duì)鍋...
    邊思文閱讀 402評(píng)論 1 1