# GerFrameCountForMP4
**Repository Path**: vividlipi/GerFrameCountForMP4
## Basic Information
- **Project Name**: GerFrameCountForMP4
- **Description**: 前端使用WebAssembly分析MP4格式文件,获取视频帧数/帧率
- **Primary Language**: C
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 2
- **Forks**: 0
- **Created**: 2020-05-04
- **Last Updated**: 2021-10-03
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
请点击查看效果--> [网页Demo 获取MP4视频帧数](http://vividlipi.gitee.io/gerframecountformp4)
### 1. WASM本地环境
初次接触WASM请先按照 [开发者引导](https://www.wasm.com.cn/getting-started/developers-guide/)[1] 搭建本地编译环境,书写helloworld程序。
### 2. 获取MP4视频帧数
#### 2.1 编译C文件
> `emcc -O2 -o getMP4FrameCount.js getMP4FrameCount.c -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall']"`
编译生成文件:
- getMP4FrameRate.js
- getMP4FrameRate.wasm
> `-O2`开启优化等级为2级,压缩编译产出文件的大小
#### 2.2 JS中调用C函数
##### 2.2.1 引用JS文件
```html
```
##### 2.2.2 获取MP4视频帧数
```html
```
### 3. 运行查看
1. 在文件目录启动服务器:`emrun --no_browser --port 8080 .`
2. 浏览器打开`http://localhost:8080/`
3. 上传一个MP4文件,页面将显示视频帧数
### 4. 运行测试
#### 4.1 生成测试视频
(测试视频已准备,这里介绍如何生成测试视频,有兴趣可以尝试更多测试视频)
resource文件下有一张纯黑色图片:black.png,使用ffmpeg命令生成视频,命令如下
> `ffmpeg -loop 1 -i black.png -c:v libx264 -t 5 -pix_fmt yuv420p -vf scale=320:240 125.mp4`
- `-t 5`表示生成一个10s的视频
- `125.mp4`为输出结果文件,可任意指定。此命令生成视频帧率为25fps
#### 4.2 编译文件
##### 4.2.1 编译测试文件
> `gcc -c test.c`
- `-c`参数表示不链接
##### 4.2.2 编译功能文件
> `gcc -c getMP4FrameCount.c -D TEST`
- `-c`参数表示定义宏,默认定义宏为 1[11]
##### 4.2.3 链接
> `gcc -o testRun test.o getMP4FrameCount.o`
#### 4.3 执行测试
> `./testRun`
```shell
root# gcc -c test.c
root# gcc -c getMP4FrameCount.c -D TEST
root# gcc -o testRun test.o getMP4FrameCount.o
root# ./testRun
TEST PASS: ../resource/375.mp4
TEST PASS: ../resource/125.mp4
root#
```
> 以上命令忽略了切换目录的操作,执行时候需要留意目录下是否有对应的文件
### 参考链接
1. [WASM中文-开发者引导](https://www.wasm.com.cn/getting-started/developers-guide/)
2. [官网-Emscripten安装](https://emscripten.org/docs/getting_started/downloads.html)
3. [简书-调用C中的自定义方法](https://www.jianshu.com/p/488b93e9b3e8)
4. [StackOverflow-如何在前端传递文件给WASM](https://stackoverflow.com/questions/47313403/passing-client-files-to-webassembly-from-the-front-end)
5. [在线查看MP4文件BOX组织](https://gpac.github.io/mp4box.js/test/filereader.html)
6. [CSDN-从MP4文件获取帧率](https://blog.csdn.net/a2657222/article/details/11045593)
7. [博客园-mp4文件格式解析](https://www.cnblogs.com/ranson7zop/p/7889272.html)
8. [MDN-C to WASM](https://developer.mozilla.org/en-US/docs/WebAssembly/C_to_wasm)
9. [MDN-Compile Exist C to WASM](https://developer.mozilla.org/en-US/docs/WebAssembly/existing_C_to_wasm)
10. [Emscripting a C library to Wasm](https://developers.google.com/web/updates/2018/03/emscripting-a-c-library)
11. [GCC编译 Preprocessor-Options](https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html)