一、安装Emscripten
Emscripten是一个工具链,作用是通过LLVM来编译生成asm.js、WebAssembly字节码,目的是让你能够在网页中接近最快的速度运行C和C++,并且不需要任何插件。进入Emscripten的GitHub首页下载emsdk:
解压后进入目录输入一下命令配置emsdk:
emsdk.bat update
emsdk.bat install latest
emsdk.bat activate latest #激活已安装的Emscripten
emsdk_env.bat #配置emsdk环境,每个控制台都需要执行
emcc -v #验证
./emsdk update
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh #配置emsdk环境,每个控制台都需要执行
emcc -v #验证
二、编译FFmpeg
1、Windows下使用MinGW编译,双击msys/msys.bat,输入以下命令。在Linux下编译命令一样。
#!/bin/bash
./configure --arch=x86_64 --enable-shared --disable-yasm --prefix=/home/FFmpeg-n2.8.18/build/
make
make install
2、使用Emscripen,此方式编译的库只能用于wasm
#!/bin/bash
unzip FFmpeg-n2.8.18.zip
cd FFmpeg-n2.8.18/
make clean
source '/home/wuhao/programfiles/emsdk-3.0.0/emsdk_env.sh'
emconfigure ./configure --arch=x86_64 --enable-shared --disable-yasm --prefix=/home/wuhao/project/FFmpeg-n2.8.18/build-wasm/ \
--enable-gpl --enable-version3 \
--enable-cross-compile --target-os=none \
--disable-inline-asm --disable-asm --disable-stripping \
--ar=emar --cc=emcc --cxx=em++ --dep-cc=emcc --ranlib=emranlib --nm="/home/wuhao/programfiles/emsdk-3.0.0/upstream/bin/llvm-nm"
make
make install
三、将c++代码编译成wasm
将已经实现功能的C++代码编译成wasm。
#!/bin/bash
export EXPORTED_FUNCTIONS="[ \
_avformat_open_input, \
_avformat_find_stream_info, \
_avcodec_close, \
_avformat_close_input, \
_av_register_all, \
_avformat_network_init, \
_av_log_set_level, \
_av_log_set_callback, \
_av_read_frame, \
_av_frame_alloc, \
_avcodec_decode_video2, \
_av_frame_free, \
_av_free_packet, \
_avformat_new_stream, \
_avcodec_copy_context, \
_av_dump_format, \
_avio_open, \
_avformat_alloc_context, \
_av_guess_format, \
_av_free, \
_av_malloc, \
_avcodec_find_decoder, \
_avcodec_open2, \
_avformat_free_context, \
_avio_close, \
_avpicture_fill, \
_avpicture_get_size, \
_sws_freeContext, \
_sws_getContext, \
_sws_scale, \
_main, _InitInputStream, _CloseContext, _SaveFrameImage, _GetJsonData, _GetImageData
]"
export EXPORTED_RUNTIME_METHODS="[ \
ccall, cwrap, printErr
]"
export TOTAL_MEMORY=134217728
export FLIB="ffmpeg/lib-wasm"
echo "Running Emscripten..."
source '/home/wuhao/programfiles/emsdk-3.0.0/emsdk_env.sh'
em++ FfmpegHelper.cpp \
${FLIB}/libavcodec.a ${FLIB}/libavdevice.a ${FLIB}/libavfilter.a ${FLIB}/libavformat.a ${FLIB}/libavutil.a ${FLIB}/libswresample.a ${FLIB}/libswscale.a \
-I ./ffmpeg/include \
-o ./FfmpegHelper.html \
-s WASM=1 \
-s ALLOW_MEMORY_GROWTH=1 \
-s TOTAL_MEMORY=${TOTAL_MEMORY} \
-s EXPORTED_FUNCTIONS="${EXPORTED_FUNCTIONS}" \
-s EXPORTED_RUNTIME_METHODS="${EXPORTED_RUNTIME_METHODS}"
chmod 777 ./*