在前一篇文章FFmpeg編程開發(fā)筆記 —— Android 移植 FFmpeg + SDL2.0 庫中脯颜,我們介紹了將FFmpeg + SDL2.0移植到Android中,并成功運(yùn)行期升。接下來我們在這基礎(chǔ)上蒋川,利用FFmpeg 和 SDL 實(shí)現(xiàn)一個(gè)簡易的播放器扔傅。
1询兴、替換native_render.c文件
我們在src/main/jni/src/目錄下,將native_render.c復(fù)制一份并重命名為simple_player.c诽表,然后將同目錄中的Android.mk文件中的LOCAL_SRC_FILES的native_render.c 替換成 simple_player.c 唉锌。然后使用Build->Refresh Linked C++ Projects。這時(shí)我們就將simple_player.c文件鏈接到了SDLMain庫中竿奏,替換掉原來的native_render.c文件了袄简。
2、開始編寫播放器的代碼
添加頭文件泛啸、定義Android Native層的Log等:
#include <jni.h>
#include <android/native_window_jni.h>
#include "SDL.h"
#include "SDL_thread.h"
#include "SDL_events.h"
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/pixfmt.h"
#include "libswscale/swscale.h"
#ifdef __ANDROID__
#include <jni.h>
#include <android/log.h>
#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR,"ERROR: ", __VA_ARGS__)
#define ALOGI(...) __android_log_print(ANDROID_LOG_INFO,"INFO: ", __VA_ARGS__)
#else
#define ALOGE(format, ...) printf("ERROR: " format "\n",##__VA_ARGS__)
#define ALOGI(format, ...) printf("INFO: " format "\n",##__VA_ARGS__)
#endif
然后在main方法里面執(zhí)行FFmpeg查找視頻文件绿语、打開視頻流等操作,這里的流程就是FFmpeg的通用流程候址,基本上格式都是固定的吕粹,如下所示:
// 注冊所有支持的文件格式以及編解碼器
av_register_all();
// 分配一個(gè)AVFormatContext
pFormatCtx = avformat_alloc_context();
// 判斷文件是否能打開
if (avformat_open_input(&pFormatCtx, file_path, NULL, NULL) != 0) {
ALOGE("can't open the file. \n");
return -1;
}
// 判斷能夠找到文件流信息
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
ALOGE("Could't find stream infomation.\n");
return -1;
}
// 打印文件信息
av_dump_format(pFormatCtx, -1, file_path, 0);
videoStream = -1;
for (i = 0; i < pFormatCtx->nb_streams; i++) {
// 新版ffmpeg將AVCodecContext *codec 替換成*codecpar
// if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStream = i;
break;
}
}
// 判斷是否找到video stream
ALOGI("videoStream: %d", videoStream);
if (videoStream == -1) {
ALOGE("Didn't find a video stream.\n");
return -1;
}
// 獲取videoStream對(duì)應(yīng)的codec context
pCodecParameters = pFormatCtx->streams[videoStream]->codecpar;
// 查找解碼器對(duì)應(yīng)的Id
pCodec = avcodec_find_decoder(pCodecParameters->codec_id);
// 沒有找到
if (pCodec == NULL) {
ALOGE("Codec not found.\n");
return -1;
}
// 根據(jù)解碼器Id創(chuàng)建解碼上下文
pCodecCtx = avcodec_alloc_context3(pCodec);
if (avcodec_parameters_to_context(pCodecCtx, pCodecParameters) < 0) {
ALOGE("copy the codec parameters to context fail!");
return -1;
}
// 打開解碼器
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
ALOGE("Could not open codec.\n");
return -1;
}
// 創(chuàng)建frame對(duì)象
pFrame = av_frame_alloc();
if (pFrame == NULL) {
ALOGE("Unable to allocate an AVFrame!\n");
return -1;
}
// 渲染的YUV
pFrameYUV = av_frame_alloc();
到這里,F(xiàn)Fmpeg播放視頻的初始化流程基本完成岗仑,接下來就是初始化SDL了匹耕,初始化也是比較流程化的東西,如下所示:
//---------------------------init sdl---------------------------//
// SDL初始化是否成功
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
ALOGE("Could not initialize SDL - %s. \n", SDL_GetError());
return -1;
}
// 創(chuàng)建窗口
screen = SDL_CreateWindow("My Player Window", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, pCodecCtx->width, pCodecCtx->height,
SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL);
if (!screen) {
ALOGE("SDL: could not set video mode - exiting\n");
return -1;
}
// 創(chuàng)建渲染器
SDL_Renderer *renderer = SDL_CreateRenderer(screen, -1, 0);
// 創(chuàng)建Texture
videoTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_YV12,
SDL_TEXTUREACCESS_STREAMING, pCodecCtx->width, pCodecCtx->height);
初始化完成后荠雕,我們來創(chuàng)建緩沖稳其,為AVPacket分配內(nèi)存:
// 創(chuàng)建緩沖
numBytes = avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx->width,
pCodecCtx->height);
out_buffer = (uint8_t *) av_malloc(numBytes * sizeof(uint8_t));
avpicture_fill((AVPicture *) pFrameYUV, out_buffer, AV_PIX_FMT_YUV420P,
pCodecCtx->width, pCodecCtx->height);
rect.x = 0;
rect.y = 0;
rect.w = pCodecCtx->width;
rect.h = pCodecCtx->height;
int y_size = pCodecCtx->width * pCodecCtx->height;
// 創(chuàng)建packet
packet = (AVPacket *) malloc(sizeof(AVPacket));
av_new_packet(packet, y_size);
到這里,基本上都準(zhǔn)備好了舞虱。接下來就是從視頻文件中逐幀讀取出來欢际,并繪制到Surface上母市,同時(shí)給SDL添加返回按鈕點(diǎn)擊事件監(jiān)聽:
// 讀取幀
while (av_read_frame(pFormatCtx, packet) >= 0) {
if (packet->stream_index == videoStream) {
// 舊版本使用方法
// getFrameCode = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
// 新版本的獲取幀方法
getPacketCode = avcodec_send_packet(pCodecCtx, packet);
if (getPacketCode == 0) {
getFrameCode = avcodec_receive_frame(pCodecCtx, pFrame);
if (getFrameCode < 0) {
ALOGE("decode error.\n");
return -1;
}
if (getFrameCode == 0) {
// 縮放幀
sws_scale(img_convert_ctx, (uint8_t const * const *) pFrame->data,
pFrame->linesize, 0, pCodecCtx->height,
pFrameYUV->data, pFrameYUV->linesize);
// iPitch 計(jì)算yuv一行數(shù)據(jù)占的字節(jié)數(shù)
SDL_UpdateYUVTexture(videoTexture, &rect,
pFrameYUV->data[0], pFrameYUV->linesize[0],
pFrameYUV->data[1], pFrameYUV->linesize[1],
pFrameYUV->data[2], pFrameYUV->linesize[2]);
// 清空數(shù)據(jù)
SDL_RenderClear(renderer);
// 復(fù)制數(shù)據(jù)
SDL_RenderCopy(renderer, videoTexture, &rect, &rect);
// 渲染到屏幕
SDL_RenderPresent(renderer);
// 延時(shí)40毫秒
SDL_Delay(40);
} else if (getFrameCode == AVERROR(EAGAIN)) {
ALOGE("%s", "Frame is not available right, please try another input");
} else if (getFrameCode == AVERROR_EOF) {
ALOGE("%s", "the decoder has been fully flushed");
} else if (getFrameCode == AVERROR(EINVAL)) {
ALOGE("%s", "codec not opened, or it is an encoder");
} else {
ALOGI("%s", "legitimate decoding errors");
}
}
}
// 釋放AVPacket
av_packet_unref(packet);
// 處理事件
if (SDL_PollEvent(&event)) {
SDL_bool needToQuit = SDL_FALSE;
switch (event.type) {
// 退出
case SDL_QUIT:
// 點(diǎn)擊返回鍵
case SDL_KEYDOWN:
needToQuit = SDL_TRUE;
break;
default:
break;
}
// 是否需要停止矾兜,退出循環(huán)
if (needToQuit) {
SDL_Quit();
break;
}
}
}
最后,銷毀創(chuàng)建的用于渲染顯示的Texture患久,銷毀FFmpeg的變量椅寺,防止內(nèi)存泄漏:
// 銷毀Texture
SDL_DestroyTexture(videoTexture);
// 釋放緩沖和對(duì)象
sws_freeContext(img_convert_ctx);
av_free(out_buffer);
av_free(pFrame);
av_free(pFrameYUV);
avcodec_parameters_free(&pCodecParameters);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
到這里浑槽,簡易播放器就實(shí)現(xiàn)了畸悬。但這樣是否就可以使用了呢暂题?還不行。首先冲秽,我們在main方法里面讀取了argv[1] 作為路徑荆萤。那么這個(gè)路徑是怎么來的呢镊靴?是從SDLActivity里面來的。我們將SDLActivity中的getArguments()方法修改成如下:
protected String[] getArguments() {
String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = sdcard + "/video.mp4";
return new String[]{ path };
}
然后在手機(jī)上復(fù)制一個(gè)名為video.mp4的文件到存儲(chǔ)根目錄链韭,也就是 /storage/emulated/0/目錄偏竟,Android
Studio重新調(diào)用Build->Refresh Linked C++ Projects,然后再運(yùn)行程序敞峭。如無意外踊谋,我們就能播放視頻了。