歡迎大家來我的部落格逛逛👏: hauhau.cn
效果 🔅
Clion 中示範的效果
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuQTMuQzMuQDO4UCR4USNFViQ4UCOCVCNFVCMyUyNy0SOw0SMyAjMGhTJxIUJ1UUJBFUJ4gTJ2UUJvw1ZvxmYvwlbj5SdhhWdhhmLldWYtl2Lc9CX6MHc0RHaiojIsJye.png)
終端中運作也沒有問題
思路 💡
通過 fork 一個子程序來調用 ffmpeg 進行推流,視訊幀通過 opencv 來擷取,通過管道傳輸到子程序,實作推流
代碼 🔨
需要注意的是,機器上要先安裝 ffmpeg,其次視訊的幀率一定要比對,否則會出現莫名其妙的問題
main.cc:
#include <iostream>
#include <csignal>
#include <opencv4/opencv2/opencv.hpp>
bool is_running = true;
void OnSignal(int) {
is_running = false;
}
int main() {
// 觸發下面的信号就退出
signal(SIGINT, OnSignal);
signal(SIGQUIT, OnSignal);
signal(SIGTERM, OnSignal);
// 打開攝像頭
cv::VideoCapture capture(0);
if (!capture.isOpened()) {
std::cerr << "Failed to open camera." << std::endl;
return EXIT_FAILURE;
}
capture.set(cv::CAP_PROP_FRAME_WIDTH, 1280);
capture.set(cv::CAP_PROP_FRAME_HEIGHT, 720);
std::string rtmp_server_url = "rtmp://localhost:1935/live/test";
std::stringstream command;
command << "ffmpeg ";
// infile options
command << "-y " // overwrite output files
<< "-an " // disable audio
<< "-f rawvideo " // force format to rawvideo
<< "-vcodec rawvideo " // force video rawvideo ('copy' to copy stream)
<< "-pix_fmt bgr24 " // set pixel format to bgr24
<< "-s 1280x720 " // set frame size (WxH or abbreviation)
<< "-r 30 "; // set frame rate (Hz value, fraction or abbreviation)
command << "-i - "; //
// outfile options
command << "-c:v libx264 " // Hyper fast Audio and Video encoder
<< "-pix_fmt yuv420p " // set pixel format to yuv420p
<< "-preset ultrafast " // set the libx264 encoding preset to ultrafast
<< "-f flv " // force format to flv
<< rtmp_server_url;
cv::Mat frame;
// 在子程序中調用 ffmpeg 進行推流
FILE *fp = nullptr;
fp = popen(command.str().c_str(), "w");
// 将 cv 讀到的每一幀傳入子程序
if (fp != nullptr) {
while (is_running) {
capture >> frame;
if (frame.empty()) {
continue;
}
fwrite(frame.data, sizeof(char), frame.total() * frame.elemSize(), fp);
}
pclose(fp);
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
}
CMakeLists.txt:
cmake_minimum_required(VERSION 3.20)
project(rtmp_test)
set(CMAKE_CXX_STANDARD 20)
message("")
message("Operation system is ${CMAKE_SYSTEM}")
if (CMAKE_SYSTEM_NAME MATCHES "Linux")
message("Current platform: Linux")
link_directories(/usr/local/lib)
include_directories(/usr/local/include)
message(STATUS "Load link directories from /usr/local/lib")
message(STATUS "Load include directories from /usr/local/include")
elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin")
message("Current platform: Darwin")
link_directories(/opt/homebrew/lib)
include_directories(/opt/homebrew/include)
message(STATUS "Load link directories from /opt/homebrew/lib")
message(STATUS "Load include directories from /opt/homebrew/include")
SET(OPENSSL_ROOT_DIR /opt/homebrew/Cellar/[email protected]/1.1.1l)
SET(OPENSSL_INCLUDE_DIR /opt/homebrew/Cellar/[email protected]/1.1.1l/include)
else ()
message(FATAL_ERROR "Platform ${CMAKE_SYSTEM_NAME} is not support for this project")
endif ()
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
if (CMAKE_BUILD_TYPE STREQUAL Debug)
ADD_DEFINITIONS(-DDEBUG)
message(STATUS "CMake Build Type: Debug")
message("")
elseif (CMAKE_BUILD_TYPE STREQUAL Release)
message(STATUS "CMake Build Type: Release")
message("")
endif ()
file(GLOB ProjectSRC
"*.cc")
add_executable(${PROJECT_NAME} ${ProjectSRC})
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})