Skip to content

Commit 39808ac

Browse files
committed
视频解码播放
使用FFmpeg进行视频解码播放
1 parent 17b18af commit 39808ac

10 files changed

Lines changed: 339 additions & 2 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,18 @@ android端基于FFmpeg库在中的使用。<br>
88
- #### 音频转码
99
- #### 音视频合成
1010
- #### 音频抽取
11+
- #### 音频解码播放
1112
- #### 视频抽取
1213
- #### 视频剪切
1314
- #### 视频转码
1415
- #### 视频截图
1516
- #### 视频转GIF动图
1617
- #### 视频添加水印
1718
- #### 图片合成视频
19+
- #### 视频解码播放
20+
1821
***
1922

20-
后续会加上音视频编解码。
23+
后续会加上音视频解码同步播放、直播推流。
2124
<br><br>
2225

‎app/CMakeLists.txt‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ add_library( # Sets the name of the library.
2323
src/main/cpp/ffmpeg_filter.c
2424
src/main/cpp/ffmpeg_opt.c
2525
src/main/cpp/audio_player.c
26-
src/main/cpp/openSL_audio_player.c)
26+
src/main/cpp/openSL_audio_player.c
27+
src/main/cpp/video_player.c)
2728

2829
add_library( ffmpeg
2930
SHARED

‎app/src/main/AndroidManifest.xml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@
3434

3535
<activity android:name=".activity.VideoHandleActivity"/>
3636

37+
<activity android:name=".activity.VideoPlayerActivity"
38+
android:screenOrientation="landscape">
39+
</activity>
40+
3741
</application>
3842

3943
</manifest>

‎app/src/main/cpp/video_player.c‎

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
//
2+
// Created by frank on 2018/2/1.
3+
//
4+
#include "libavcodec/avcodec.h"
5+
#include "libavformat/avformat.h"
6+
#include "libswscale/swscale.h"
7+
#include <android/native_window.h>
8+
#include <android/native_window_jni.h>
9+
#include <stdio.h>
10+
#include <unistd.h>
11+
#include <libavutil/imgutils.h>
12+
#include <android/log.h>
13+
14+
#define TAG "MediaPlayer"
15+
#define LOGI(FORMAT,...) __android_log_print(ANDROID_LOG_INFO, TAG, FORMAT, ##__VA_ARGS__);
16+
#define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR, TAG, FORMAT, ##__VA_ARGS__);
17+
18+
//播放倍率
19+
float play_rate = 1;
20+
//视频总时长
21+
long duration = 0;
22+
23+
JNIEXPORT jint JNICALL Java_com_frank_ffmpeg_VideoPlayer_play
24+
(JNIEnv * env, jclass clazz, jstring filePath, jobject surface){
25+
26+
const char * file_name = (*env)->GetStringUTFChars(env, filePath, JNI_FALSE);
27+
//注册所有组件
28+
av_register_all();
29+
//分配上下文
30+
AVFormatContext * pFormatCtx = avformat_alloc_context();
31+
//打开视频文件
32+
if(avformat_open_input(&pFormatCtx, file_name, NULL, NULL)!=0) {
33+
LOGE("Couldn't open file:%s\n", file_name);
34+
return -1;
35+
}
36+
//检索多媒体流信息
37+
if(avformat_find_stream_info(pFormatCtx, NULL)<0) {
38+
LOGE("Couldn't find stream information.");
39+
return -1;
40+
}
41+
//寻找视频流的第一帧
42+
int videoStream = -1, i;
43+
for (i = 0; i < pFormatCtx->nb_streams; i++) {
44+
if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO
45+
&& videoStream < 0) {
46+
videoStream = i;
47+
}
48+
}
49+
if(videoStream==-1) {
50+
LOGE("couldn't find a video stream.");
51+
return -1;
52+
}
53+
54+
//获取视频总时长
55+
if (pFormatCtx->duration != AV_NOPTS_VALUE) {
56+
duration = (long) (pFormatCtx->duration / AV_TIME_BASE);
57+
LOGE("duration=%d", duration);
58+
}
59+
60+
//获取codec上下文指针
61+
AVCodecContext * pCodecCtx = pFormatCtx->streams[videoStream]->codec;
62+
//寻找视频流的解码器
63+
AVCodec * pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
64+
if(pCodec==NULL) {
65+
LOGE("couldn't find Codec.");
66+
return -1;
67+
}
68+
if(avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
69+
LOGE("Couldn't open codec.");
70+
return -1;
71+
}
72+
// 获取native window
73+
ANativeWindow* nativeWindow = ANativeWindow_fromSurface(env, surface);
74+
// 获取视频宽高
75+
int videoWidth = pCodecCtx->width;
76+
int videoHeight = pCodecCtx->height;
77+
// 设置native window的buffer大小,可自动拉伸
78+
ANativeWindow_setBuffersGeometry(nativeWindow, videoWidth, videoHeight, WINDOW_FORMAT_RGBA_8888);
79+
ANativeWindow_Buffer windowBuffer;
80+
if(avcodec_open2(pCodecCtx, pCodec, NULL)<0) {
81+
LOGE("Couldn't open codec.");
82+
return -1;
83+
}
84+
//申请内存
85+
AVFrame * pFrame = av_frame_alloc();
86+
AVFrame * pFrameRGBA = av_frame_alloc();
87+
if(pFrameRGBA == NULL || pFrame == NULL) {
88+
LOGE("Couldn't allocate video frame.");
89+
return -1;
90+
}
91+
// buffer中数据用于渲染,且格式为RGBA
92+
int numBytes=av_image_get_buffer_size(AV_PIX_FMT_RGBA, pCodecCtx->width, pCodecCtx->height, 1);
93+
94+
uint8_t * buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));
95+
av_image_fill_arrays(pFrameRGBA->data, pFrameRGBA->linesize, buffer, AV_PIX_FMT_RGBA,
96+
pCodecCtx->width, pCodecCtx->height, 1);
97+
98+
// 由于解码出来的帧格式不是RGBA的,在渲染之前需要进行格式转换
99+
struct SwsContext *sws_ctx = sws_getContext(pCodecCtx->width,
100+
pCodecCtx->height,
101+
pCodecCtx->pix_fmt,
102+
pCodecCtx->width,
103+
pCodecCtx->height,
104+
AV_PIX_FMT_RGBA,
105+
SWS_BILINEAR,
106+
NULL,
107+
NULL,
108+
NULL);
109+
110+
int frameFinished;
111+
AVPacket packet;
112+
113+
while(av_read_frame(pFormatCtx, &packet)>=0) {
114+
//判断是否为视频流
115+
if(packet.stream_index==videoStream) {
116+
//对该帧进行解码
117+
avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
118+
if (frameFinished) {
119+
// lock native window
120+
ANativeWindow_lock(nativeWindow, &windowBuffer, 0);
121+
// 格式转换
122+
sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data,
123+
pFrame->linesize, 0, pCodecCtx->height,
124+
pFrameRGBA->data, pFrameRGBA->linesize);
125+
// 获取stride
126+
uint8_t * dst = windowBuffer.bits;
127+
int dstStride = windowBuffer.stride * 4;
128+
uint8_t * src = pFrameRGBA->data[0];
129+
int srcStride = pFrameRGBA->linesize[0];
130+
// 由于window的stride和帧的stride不同,因此需要逐行复制
131+
int h;
132+
for (h = 0; h < videoHeight; h++) {
133+
memcpy(dst + h * dstStride, src + h * srcStride, (size_t) srcStride);
134+
}
135+
ANativeWindow_unlockAndPost(nativeWindow);
136+
}
137+
//延迟等待
138+
usleep((unsigned long) (1000 * 40 * play_rate));
139+
}
140+
av_packet_unref(&packet);
141+
}
142+
//释放内存以及关闭文件
143+
av_free(buffer);
144+
av_free(pFrameRGBA);
145+
av_free(pFrame);
146+
avcodec_close(pCodecCtx);
147+
avformat_close_input(&pFormatCtx);
148+
return 0;
149+
}
150+
151+
//设置播放速率
152+
JNIEXPORT jint JNICALL Java_com_frank_ffmpeg_VideoPlayer_setPlayRate
153+
(JNIEnv * env, jclass clazz, jfloat playRate){
154+
play_rate = playRate;
155+
}
156+
157+
//获取视频总时长
158+
JNIEXPORT jint JNICALL Java_com_frank_ffmpeg_VideoPlayer_getDuration
159+
(JNIEnv * env, jclass clazz){
160+
return duration;
161+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.frank.ffmpeg;
2+
3+
/**
4+
* 视频播放器
5+
* Created by frank on 2018/2/1
6+
*/
7+
public class VideoPlayer {
8+
9+
static {
10+
System.loadLibrary("media-handle");
11+
}
12+
13+
public native int play(String filePath, Object surface);
14+
public native int setPlayRate(float playRate);
15+
16+
}

‎app/src/main/java/com/frank/ffmpeg/activity/VideoHandleActivity.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.frank.ffmpeg.activity;
22

33
import android.annotation.SuppressLint;
4+
import android.content.Intent;
45
import android.os.Bundle;
56
import android.os.Environment;
67
import android.os.Handler;
@@ -65,6 +66,7 @@ private void intView() {
6566
findViewById(R.id.btn_generate_gif).setOnClickListener(this);
6667
findViewById(R.id.btn_screen_record).setOnClickListener(this);
6768
findViewById(R.id.btn_combine_video).setOnClickListener(this);
69+
findViewById(R.id.btn_play_video).setOnClickListener(this);
6870
}
6971

7072
private void setVisible() {
@@ -117,6 +119,9 @@ public void onClick(View v) {
117119
case R.id.btn_combine_video:
118120
handleType = 7;
119121
break;
122+
case R.id.btn_play_video:
123+
handleType = 8;
124+
break;
120125
default:
121126
handleType = 0;
122127
break;
@@ -196,6 +201,9 @@ private void doHandleVideo(int handleType){
196201
String combineVideo = PATH + File.separator + "combineVideo.mp4";
197202
commandLine = FFmpegUtil.pictureToVideo(picturePath, combineVideo);
198203
break;
204+
case 8:
205+
startActivity(new Intent(VideoHandleActivity.this, VideoPlayerActivity.class));
206+
return;
199207
default:
200208
break;
201209
}
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package com.frank.ffmpeg.activity;
2+
3+
import android.os.Bundle;
4+
import android.os.Environment;
5+
import android.support.v7.app.AppCompatActivity;
6+
import android.util.Log;
7+
import android.view.SurfaceHolder;
8+
import android.view.SurfaceView;
9+
import android.view.View;
10+
import android.widget.Button;
11+
12+
import com.frank.ffmpeg.R;
13+
import com.frank.ffmpeg.VideoPlayer;
14+
15+
import java.io.File;
16+
17+
/**
18+
* 使用ffmpeg播放视频
19+
* Created by frank on 2018/2/1.
20+
*/
21+
public class VideoPlayerActivity extends AppCompatActivity implements SurfaceHolder.Callback {
22+
private static final String TAG = MainActivity.class.getSimpleName();
23+
SurfaceHolder surfaceHolder;
24+
private final static String PATH = Environment.getExternalStorageDirectory().getPath() + File.separator;
25+
private String filePath = PATH + "hello.mp4";
26+
private VideoPlayer videoPlayer;
27+
//播放倍率
28+
private float playRate = 1;
29+
@Override
30+
protected void onCreate(Bundle savedInstanceState) {
31+
super.onCreate(savedInstanceState);
32+
setContentView(R.layout.activity_video_player);
33+
34+
initView();
35+
initPlayer();
36+
}
37+
38+
private void initView(){
39+
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surface_view);
40+
surfaceHolder = surfaceView.getHolder();
41+
surfaceHolder.addCallback(this);
42+
43+
Button btn_slow = (Button) findViewById(R.id.btn_slow);
44+
btn_slow.setOnClickListener(new View.OnClickListener() {
45+
@Override
46+
public void onClick(View view) {
47+
if(playRate <= 32){
48+
playRate *= 2;
49+
}
50+
Log.i(TAG, "playRate=" + playRate);
51+
videoPlayer.setPlayRate(playRate);
52+
}
53+
});
54+
55+
Button btn_fast = (Button) findViewById(R.id.btn_fast);
56+
btn_fast.setOnClickListener(new View.OnClickListener() {
57+
@Override
58+
public void onClick(View view) {
59+
if(playRate >= 1/32){
60+
playRate *= 0.5;
61+
}
62+
Log.i(TAG, "playRate=" + playRate);
63+
videoPlayer.setPlayRate(playRate);
64+
}
65+
});
66+
67+
}
68+
69+
private void initPlayer(){
70+
videoPlayer = new VideoPlayer();
71+
}
72+
73+
@Override
74+
public void surfaceCreated(SurfaceHolder holder) {
75+
new Thread(new Runnable() {
76+
@Override
77+
public void run() {
78+
videoPlayer.play(filePath, surfaceHolder.getSurface());
79+
}
80+
}).start();
81+
}
82+
83+
@Override
84+
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
85+
86+
}
87+
88+
@Override
89+
public void surfaceDestroyed(SurfaceHolder holder) {
90+
91+
}
92+
93+
@Override
94+
protected void onDestroy() {
95+
super.onDestroy();
96+
if(videoPlayer != null){
97+
videoPlayer = null;
98+
}
99+
}
100+
101+
}

‎app/src/main/res/layout/activity_video_handle.xml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,13 @@
8585
android:layout_centerInParent="true"
8686
android:visibility="gone"/>
8787

88+
<Button
89+
android:id="@+id/btn_play_video"
90+
android:layout_width="wrap_content"
91+
android:layout_height="wrap_content"
92+
android:layout_centerHorizontal="true"
93+
android:layout_below="@id/btn_combine_video"
94+
android:layout_marginTop="10dp"
95+
android:text="@string/video_play"/>
96+
8897
</RelativeLayout>

0 commit comments

Comments
 (0)