使用Android studio移植FFmpeg3.3进行转码

转载地址:http://blog.csdn.net/quan648997767/article/details/71437275


注意以下操作必须使用Android studio2.2以上

第一步:导入so文件

1、在main目录下新建jniLibs目录

2、再在jniLibs下新建armeabi目录

3、将编译好的so文件拷贝到armeabi目录下

4、将编译生成的include目录拷贝到jniLibs目录下(参考:编译FFmpeg


第二步:配置CMakeLists

[plain]  view plain  copy
 print ?
  1. cmake_minimum_required(VERSION 3.4.1)  
  2.   
  3. add_library( native-lib  
  4.              SHARED  
  5.              src/main/cpp/native-lib.cpp  
  6.              src/main/cpp/test_ffmpeg.cpp)  
  7.   
  8. find_library( log-lib  
  9.               log )  
  10.   
  11.   
  12. find_library( android-lib  
  13.               android )  
  14.   
  15. set(distribution_DIR ${CMAKE_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI})  
  16.   
  17. add_library( avutil-55  
  18.              SHARED  
  19.              IMPORTED )  
  20. set_target_properties( avutil-55  
  21.                        PROPERTIES IMPORTED_LOCATION  
  22.                        ${distribution_DIR}/libavutil-55.so)  
  23.   
  24. add_library( swresample-2  
  25.              SHARED  
  26.              IMPORTED )  
  27. set_target_properties( swresample-2  
  28.                        PROPERTIES IMPORTED_LOCATION  
  29.                        ${distribution_DIR}/libswresample-2.so)  
  30.   
  31. add_library( avfilter-6  
  32.              SHARED  
  33.              IMPORTED )  
  34. set_target_properties( avfilter-6  
  35.                        PROPERTIES IMPORTED_LOCATION  
  36.                        ${distribution_DIR}/libavfilter-6.so)  
  37.   
  38. add_library( avformat-57  
  39.              SHARED  
  40.              IMPORTED )  
  41. set_target_properties( avformat-57  
  42.                        PROPERTIES IMPORTED_LOCATION  
  43.                        ${distribution_DIR}/libavformat-57.so)  
  44.   
  45. add_library( swscale-4  
  46.              SHARED  
  47.              IMPORTED )  
  48. set_target_properties( swscale-4  
  49.                        PROPERTIES IMPORTED_LOCATION  
  50.                        ${distribution_DIR}/libswscale-4.so)  
  51.   
  52.   
  53. add_library( avcodec-57  
  54.              SHARED  
  55.              IMPORTED )  
  56. set_target_properties( avcodec-57  
  57.                        PROPERTIES IMPORTED_LOCATION  
  58.                        ${distribution_DIR}/libavcodec-57.so)  
  59.   
  60. set(CMAKE_VERBOSE_MAKEFILE on)  
  61. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")  
  62. include_directories(src/main/cpp)  
  63. include_directories(src/main/jniLibs/include)  
  64.   
  65. target_link_libraries(native-lib  
  66.                       avcodec-57  
  67.                       avfilter-6  
  68.                       avformat-57  
  69.                       avutil-55  
  70.                       swresample-2  
  71.                       swscale-4  
  72.                       ${log-lib}  
  73.                       ${android-lib})  

第三步:配置build.gradle

[plain]  view plain  copy
 print ?
  1. defaultConfig {...  
  2.         externalNativeBuild {  
  3.             cmake {  
  4.                 cppFlags "-std=c++11 -frtti -fexceptions"  
  5.             }  
  6.         }  
  7.         ndk {  
  8.             //这里我们只有armeabi就只配置这个就行了  
  9.             abiFilters  'armeabi'  
  10.         }  
  11.     }  
  12.     sourceSets.main {  
  13.         jniLibs.srcDirs = ['src/main/jniLibs']  
  14.     }  
  15.       
  16.     externalNativeBuild {  
  17.         cmake {  
  18.             path "CMakeLists.txt"  
  19.         }  
  20.     }  



第四步:编写native方法

[java]  view plain  copy
 print ?
  1. package com.zzq.mack.ffmpeg.natives;  
  2.   
  3. /** 
  4.  * Created by mack on 2017/4/28. 
  5.  */  
  6.   
  7. public class PlayerNative {  
  8.   
  9.     /** 
  10.      * 音视频解码播放 
  11.      * @param path 
  12.      * @param view 
  13.      */  
  14.     public native static void paly(String path,Object view);  
  15.   
  16.   
  17. }  

生成头文件 参考http://blog.csdn.net/quan648997767/article/details/64923143

第五步:编写c/c++代码

[cpp]  view plain  copy
 print ?
  1. #include <jni.h>  
  2. #include <com_zzq_mack_ffmpeg_PlayerNative.h>  
  3. #include <android/native_window.h>  
  4. #include <android/native_window_jni.h>  
  5. #include <unistd.h>  
  6. #include <android/log.h>  
  7. #define LOGI(FORMAT,...) __android_log_print(ANDROID_LOG_INFO,"TAG",FORMAT,##__VA_ARGS__);  
  8. #define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"TAG",FORMAT,##__VA_ARGS__);  
  9. extern "C" {  
  10. #include "libavformat/avformat.h"  
  11. #include "libswscale/swscale.h"  
  12. #include <libavfilter/avfiltergraph.h>  
  13. #include "libavfilter/avfilter.h"  
  14. #include "libavutil/imgutils.h"  
  15. #include "libavutil/avutil.h"  
  16. #include "libavfilter/buffersink.h"  
  17. #include "libavfilter/buffersrc.h"  
  18. #include "libavcodec/avcodec.h"  
  19. }  
  20. /** 
  21.  * 
  22.  * 音视频解码  
  23.  */  
  24.   
  25. JNIEXPORT void JNICALL  
  26. Java_com_zzq_mack_ffmpeg_natives_PlayerNative_paly(JNIEnv *env, jclass type, jstring path_, jobject view) {  
  27.     const char *path = env->GetStringUTFChars(path_, 0);  
  28.     //注册所有的编解码器  
  29.     av_register_all();  
  30.     //avcodec_register_all();  
  31.     int ret;  
  32.     //封装格式上线文  
  33.     AVFormatContext *fmt_ctx = avformat_alloc_context();  
  34.     //打开输入流并读取头文件。此时编解码器还没有打开  
  35.     if(avformat_open_input(&fmt_ctx,path,NULL,NULL) < 0){  
  36.         return;  
  37.     }  
  38.     //获取信息  
  39.     if(avformat_find_stream_info(fmt_ctx,NULL) < 0){  
  40.         return;  
  41.     }  
  42.     //获取视频流的索引位置  
  43.     int video_stream_index = -1;  
  44.     for (int i = 0; i < fmt_ctx->nb_streams; i++) {  
  45.         if(fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO){  
  46.             video_stream_index = i;  
  47.             LOGE("找到视频流索引位置video_stream_index=%d",video_stream_index);  
  48.             break;  
  49.         }  
  50.     }  
  51.     if (video_stream_index == -1){  
  52.         LOGE("未找到视频流索引");  
  53.     }  
  54.     ANativeWindow* nativeWindow = ANativeWindow_fromSurface(env,view);  
  55.     if (nativeWindow == NULL) {  
  56.         LOGE("ANativeWindow_fromSurface error");  
  57.         return;  
  58.     }  
  59.     //绘制时候的缓冲区  
  60.     ANativeWindow_Buffer outBuffer;  
  61.     //获取视频流解码器  
  62.   
  63.     AVCodecContext *codec_ctx = avcodec_alloc_context3(NULL);  
  64.     avcodec_parameters_to_context(codec_ctx, fmt_ctx->streams[video_stream_index]->codecpar);  
  65.     AVCodec *avCodec = avcodec_find_decoder(codec_ctx->codec_id);  
  66.     //打开解码器  
  67.     if((ret = avcodec_open2(codec_ctx,avCodec,NULL)) < 0){  
  68.         ret = -3;  
  69.         return;  
  70.     }  
  71.     //循环从文件读取一帧压缩数据  
  72.     //开始读取视频  
  73.     int y_size = codec_ctx->width * codec_ctx->height;  
  74.     AVPacket *pkt = (AVPacket *)malloc(sizeof(AVPacket));//分配一个packet  
  75.     av_new_packet(pkt,y_size);//分配packet的数据  
  76.     AVFrame *yuvFrame = av_frame_alloc();  
  77.     AVFrame *rgbFrame = av_frame_alloc();  
  78.     // 颜色转换器  
  79.     SwsContext *m_swsCtx = sws_getContext(codec_ctx->width, codec_ctx->height, codec_ctx->pix_fmt, codec_ctx->width,  
  80.                                           codec_ctx->height, AV_PIX_FMT_RGBA, SWS_BICUBIC, NULL, NULL, NULL);  
  81.     //int numBytes = av_image_get_buffer_size(AV_PIX_FMT_RGBA, codec_ctx->width, codec_ctx->height, 1);  
  82.     //uint8_t *out_buffer = (uint8_t *) av_malloc(numBytes * sizeof(uint8_t));  
  83.     LOGE("开始解码");  
  84.     int  index = 0;  
  85.     while (1){  
  86.         if(av_read_frame(fmt_ctx,pkt) < 0){  
  87.             //这里就认为视频读完了  
  88.             break;  
  89.         }  
  90.         if(pkt->stream_index == video_stream_index) {  
  91.             //视频解码  
  92.             ret = avcodec_send_packet(codec_ctx, pkt);  
  93.             if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {  
  94.                 LOGE("avcodec_send_packet ret=%d", ret);  
  95.                 av_packet_unref(pkt);  
  96.                 continue;  
  97.             }  
  98.             //从解码器返回解码输出数据  
  99.             ret = avcodec_receive_frame(codec_ctx, yuvFrame);  
  100.             if (ret < 0 && ret != AVERROR_EOF) {  
  101.                 LOGE("avcodec_receive_frame ret=%d", ret);  
  102.                 av_packet_unref(pkt);  
  103.                 continue;  
  104.             }  
  105.             //avcodec_decode_video2(codec_ctx,yuvFrame,&got_pictue,&pkt);  
  106.             sws_scale(m_swsCtx, (const uint8_t *const *) yuvFrame->data, yuvFrame->linesize, 0,  
  107.                       codec_ctx->height, rgbFrame->data, rgbFrame->linesize);  
  108.             //设置缓冲区的属性  
  109.             ANativeWindow_setBuffersGeometry(nativeWindow, codec_ctx->width, codec_ctx->height,  
  110.                                              WINDOW_FORMAT_RGBA_8888);  
  111.             ret = ANativeWindow_lock(nativeWindow, &outBuffer, NULL);  
  112.             if (ret != 0) {  
  113.                 LOGE("ANativeWindow_lock error");  
  114.                 return;  
  115.             }  
  116.             av_image_fill_arrays(rgbFrame->data, rgbFrame->linesize,  
  117.                                  (const uint8_t *) outBuffer.bits, AV_PIX_FMT_RGBA,  
  118.                                  codec_ctx->width, codec_ctx->height, 1);  
  119.             //fill_ANativeWindow(&outBuffer,outBuffer.bits,rgbFrame);  
  120.             //将缓冲区数据显示到surfaceView  
  121.             ret = ANativeWindow_unlockAndPost(nativeWindow);  
  122.             if (ret != 0) {  
  123.                 LOGE("ANativeWindow_unlockAndPost error");  
  124.                 return;  
  125.             }  
  126.             LOGE("成功显示到缓冲区%d次",++index);  
  127.         }  
  128.         av_packet_unref(pkt);  
  129.         usleep(1000*16);  
  130.   
  131. //            /*  
  132. //            //UYVY  
  133. //            fwrite(pFrameYUV->data[0],(pCodecCtx->width)*(pCodecCtx->height),2,output);  
  134. //            //YUV420P  
  135. //            fwrite(pFrameYUV->data[0],(pCodecCtx->width)*(pCodecCtx->height),1,output);  
  136. //            fwrite(pFrameYUV->data[1],(pCodecCtx->width)*(pCodecCtx->height)/4,1,output);  
  137. //            fwrite(pFrameYUV->data[2],(pCodecCtx->width)*(pCodecCtx->height)/4,1,output);  
  138.     }  
  139.     //av_free(out_buffer);  
  140.     av_frame_free(&rgbFrame);  
  141.     avcodec_close(codec_ctx);  
  142.     sws_freeContext(m_swsCtx);  
  143.     avformat_close_input(&fmt_ctx);  
  144.     ANativeWindow_release(nativeWindow);  
  145.     env->ReleaseStringUTFChars(path_, path);  
  146.     LOGI("解析完成");  
  147. }  
第六步:JAVA层调用

[java]  view plain  copy
 print ?
  1. public void mPaly(View view){  
  2.         final String path = "/storage/emulated/0/pp/service/video/test1.flv";//1493695201802.mp4";//  
  3.         final VideoView mVideo = (VideoView) findViewById(R.id.video);  
  4.         if (new File(path).exists()){  
  5.             runOnUiThread(new Runnable() {  
  6.                 @Override  
  7.                 public void run() {  
  8.                     PlayerNative.paly(path,mVideo.getHolder().getSurface());  
  9.                     //PlayerNative.voideCoding(path);  
  10.                 }  
  11.             });  
  12.         }else{  
  13.             System.out.println("文件不存在");  
  14.         }  
  15.     }  
VideoView是一个自己重写的SurfaceView代码如下:

[java]  view plain  copy
 print ?
  1. package com.zzq.mack.ffmpeg;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.PixelFormat;  
  5. import android.util.AttributeSet;  
  6. import android.view.SurfaceHolder;  
  7. import android.view.SurfaceView;  
  8.   
  9. /** 
  10.  * Created by mack on 2017/4/28. 
  11.  */  
  12.   
  13. public class VideoView extends SurfaceView {  
  14.     public VideoView(Context context) {  
  15.         super(context);  
  16.         init();  
  17.     }  
  18.   
  19.     public VideoView(Context context, AttributeSet attrs) {  
  20.         super(context, attrs);  
  21.         init();  
  22.     }  
  23.   
  24.     public VideoView(Context context, AttributeSet attrs, int defStyleAttr) {  
  25.         super(context, attrs, defStyleAttr);  
  26.         init();  
  27.     }  
  28.   
  29.     private void init() {  
  30.         SurfaceHolder holder = getHolder();  
  31.         holder.setFormat(PixelFormat.RGBA_8888);  
  32.     }  
  33.   
  34.   
  35. }  
布局文件也给出来吧:

[html]  view plain  copy
 print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical"  
  6.     android:background="@android:color/white">  
  7.   
  8.     <Button  
  9.         android:id="@+id/btn"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:text="开始"  
  13.         android:onClick="mPaly"/>  
  14.   
  15.   
  16.     <com.zzq.mack.ffmpeg.VideoView  
  17.         android:id="@+id/video"  
  18.         android:layout_width="match_parent"  
  19.         android:layout_height="match_parent" />  
  20.   
  21. </LinearLayout>  
最后加上权限就可以跑了:

[plain]  view plain  copy
 print ?
  1. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>  
  2.   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  3.   <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值