c++ 调用ffmpeg命令获取视频属性

时间:2022-07-26
本文章向大家介绍c++ 调用ffmpeg命令获取视频属性,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
    string command = "ffmpeg -i D:\vc\images\tanned_part_3600.mp4";
    FILE* pPipe = _popen(command.c_str(), "rt");
    if (!pPipe) {
        return "popen failed!";
    }
    char* buffer = new char[1024];
    char* info = new char[10000]{ 0 };
    uint32_t bytesRead, readCount=0;
    
	while (true) {
		bytesRead = fread(buffer, 1, 1024, pPipe);
		if (bytesRead == 0) {
			break;
		}
		memcpy(info + readCount, buffer, bytesRead);
		readCount += bytesRead;
    }
    
    //readCount 0,就是读取不到

单独执行上面command

$ ffmpeg -i D:\vc\images\tanned_part_3600.mp4
ffmpeg version 4.3.1-full_build-www.gyan.dev Copyright (c) 2000-2020 the FFmpeg developers
            。。。。。
      handler_name    : VideoHandler
At least one output file must be specified

报错了,难道是错误的原因?

那么换一个没有错误的命令:

ffmpeg -i D:\vc\images\tanned_part_3600.mp4 -ss 00:00:00 -vframes 1 -y  aaa.jpg

还是不行。。。

难道是打印日志级别的原因?

ffmpeg -loglevel info -i tanned_part_3600.mp4

还是不行

上述popen只是读取stdout的输出,,stderr是读取不到的,,猜测上面信息是打印到是stderr的了,搜了一下有种办法是建3个pipe可以间接取到stderr信息,不方便。

linux里有个stderr重定向的功能 2>&1 不妨一试,虽然是windows平台。

ffmpeg -i D:\vc\images\tanned_part_3600.mp4 2>&1

竟然可以了。

然后通过正则获取比如,码率:

    std::regex bitrate_reg(".*bitrate: (\d+) kb.*");
    std::smatch matchResult;
    string inputstr, inputstr2;
    inputstr = string(info);
    inputstr2 = inputstr.substr(0, readCount);
    
    if (std::regex_search(inputstr2, matchResult, bitrate_reg))
    {
        for (size_t i = 1; i < matchResult.size(); ++i)
        {
            cout << matchResult[i] << endl;   //码率
        }
    }