写一个ununtu C++ 程序,调用ffmpeg, 来判断一个数字电影的视频文件mxf 是不是Jpeg2000?
以下是一个 Ubuntu C++ 程序 ,调用 FFmpeg API 来判断 MXF 文件是否使用 JPEG 2000 编码。
1. 安装依赖(FFmpeg 开发库)
在 Ubuntu 上安装 FFmpeg 开发包:
bash
sudo apt update
sudo apt install libavformat-dev libavcodec-dev libavutil-dev
2. C++ 程序代码
cpp
#include <iostream>
#include <string>
#include <cstring>
extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
}
bool is_mxf_jpeg2000(const std::string& filename) {
// 初始化 FFmpeg
avformat_network_init();
// 打开输入文件
AVFormatContext* format_ctx = nullptr;
if (avformat_open_input(&format_ctx, filename.c_str(), nullptr, nullptr) != 0) {
std::cerr << "Error: Could not open file " << filename << std::endl;
return false;
}
// 探测流信息
if (avformat_find_stream_info(format_ctx, nullptr) < 0) {
std::cerr << "Error: Could not find stream info" << std::endl;
avformat_close_input(&format_ctx);
return false;
}
// 查找视频流
bool is_jpeg2000 = false;
for (unsigned int i = 0; i < format_ctx->nb_streams; i++) {
AVStream* stream = format_ctx->streams[i];
if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
// 检查编码格式
if (stream->codecpar->codec_id == AV_CODEC_ID_JPEG2000) {
is_jpeg2000 = true;
break;
}
}
}
// 释放资源
avformat_close_input(&format_ctx);
return is_jpeg2000;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <input.mxf>" << std::endl;
return 1;
}
std::string filename = argv[1];
if (is_mxf_jpeg2000(filename)) {
std::cout << "✅ The MXF file contains JPEG 2000 video." << std::endl;
} else {
std::cout << "❌ The MXF file does NOT contain JPEG 2000 video." << std::endl;
}
return 0;
}
3. 编译程序
使用 g++
编译(链接 FFmpeg 库):
bash
g++ check_mxf_jpeg2000.cpp -o check_mxf_jpeg2000 -lavformat -lavcodec -lavutil
4. 运行测试
bash
./check_mxf_jpeg2000 input.mxf
输出示例:
-
如果是 JPEG 2000:
text
✅ The MXF file contains JPEG 2000 video.
-
如果不是:
text
❌ The MXF file does NOT contain JPEG 2000 video.
5. 关键代码解析
代码部分 | 作用 |
---|---|
avformat_open_input() |
打开 MXF 文件 |
avformat_find_stream_info() |
探测流信息 |
stream->codecpar->codec_id |
检查视频编码格式 |
AV_CODEC_ID_JPEG2000 |
FFmpeg 定义的 JPEG 2000 编码标识 |
6. 替代方案(Shell 调用 FFmpeg)
如果不想写 C++,可以直接用 ffprobe
命令行:
bash
ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of default=noprint_wrappers=1:nokey=1 input.mxf
- 输出
jpeg2000
表示是 JPEG 2000。
总结
-
推荐 C++ 方案:适合集成到自动化工具或大型项目。
-
快速检查 :直接用
ffprobe
更简单。
如果需要扩展功能(如检查 DCP 合规性),可以结合 ASDCPLib。