321 lines
11 KiB
C++
321 lines
11 KiB
C++
#include "clip_action.h"
|
|
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <ctime>
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <iomanip>
|
|
#include <iostream>
|
|
#include <sstream>
|
|
#include <thread>
|
|
|
|
#if defined(RK3588_ENABLE_FFMPEG)
|
|
extern "C" {
|
|
#include <libavcodec/avcodec.h>
|
|
#include <libavformat/avformat.h>
|
|
#include <libavutil/imgutils.h>
|
|
#include <libavutil/opt.h>
|
|
#include <libswscale/swscale.h>
|
|
}
|
|
#define HAS_FFMPEG 1
|
|
#else
|
|
#define HAS_FFMPEG 0
|
|
#endif
|
|
|
|
namespace rk3588 {
|
|
|
|
bool ClipAction::Init(const SimpleJson& config) {
|
|
pre_sec_ = config.ValueOr<int>("pre_sec", 5);
|
|
post_sec_ = config.ValueOr<int>("post_sec", 10);
|
|
format_ = config.ValueOr<std::string>("format", "mp4");
|
|
fps_ = config.ValueOr<int>("fps", 25);
|
|
|
|
if (const SimpleJson* upload_cfg = config.Find("upload")) {
|
|
uploader_ = CreateUploader(*upload_cfg);
|
|
if (!uploader_) {
|
|
std::cerr << "[ClipAction] failed to create uploader\n";
|
|
return false;
|
|
}
|
|
} else {
|
|
SimpleJson default_cfg;
|
|
uploader_ = CreateUploader(default_cfg);
|
|
}
|
|
|
|
std::cout << "[ClipAction] initialized, pre=" << pre_sec_ << "s post=" << post_sec_
|
|
<< "s format=" << format_ << "\n";
|
|
return true;
|
|
}
|
|
|
|
void ClipAction::Execute(AlarmEvent& event, std::shared_ptr<Frame> frame) {
|
|
if (!frame_buffer_) {
|
|
std::cerr << "[ClipAction] frame buffer not set\n";
|
|
return;
|
|
}
|
|
if (!frame) return;
|
|
|
|
uint64_t trigger_ts_ms = 0;
|
|
if (!frame_buffer_->FindTimestampByFrameId(frame->frame_id, trigger_ts_ms)) {
|
|
using namespace std::chrono;
|
|
trigger_ts_ms = static_cast<uint64_t>(duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count());
|
|
}
|
|
|
|
const uint64_t pre_ms = static_cast<uint64_t>(std::max(0, pre_sec_)) * 1000ULL;
|
|
const uint64_t post_ms = static_cast<uint64_t>(std::max(0, post_sec_)) * 1000ULL;
|
|
const uint64_t start_ts = (trigger_ts_ms > pre_ms) ? (trigger_ts_ms - pre_ms) : 0;
|
|
const uint64_t end_ts = trigger_ts_ms + post_ms;
|
|
|
|
// Best-effort: wait for post-event window to elapse so frames are available in ring buffer.
|
|
if (post_sec_ > 0) {
|
|
std::this_thread::sleep_for(std::chrono::seconds(post_sec_));
|
|
}
|
|
|
|
auto frames = frame_buffer_->GetFramesInRange(start_ts, end_ts);
|
|
if (frames.empty()) {
|
|
frames.push_back(frame);
|
|
}
|
|
|
|
std::string url = ProcessClip(frames, event);
|
|
if (!url.empty()) {
|
|
event.clip_url = url;
|
|
std::cout << "[ClipAction] clip uploaded: " << url << "\n";
|
|
}
|
|
}
|
|
|
|
std::string ClipAction::ProcessClip(const std::vector<std::shared_ptr<Frame>>& frames, const AlarmEvent& event) {
|
|
#if HAS_FFMPEG
|
|
if (frames.empty()) {
|
|
std::cerr << "[ClipAction] no frames to process\n";
|
|
return "";
|
|
}
|
|
|
|
std::shared_ptr<Frame> sample_frame;
|
|
for (const auto& f : frames) {
|
|
if (f) { sample_frame = f; break; }
|
|
}
|
|
if (!sample_frame) return "";
|
|
|
|
int width = sample_frame->width;
|
|
int height = sample_frame->height;
|
|
|
|
if (width <= 0 || height <= 0) {
|
|
std::cerr << "[ClipAction] invalid frame size\n";
|
|
return "";
|
|
}
|
|
|
|
// Create temporary file
|
|
std::filesystem::path tmp_dir;
|
|
try {
|
|
tmp_dir = std::filesystem::temp_directory_path();
|
|
} catch (...) {
|
|
tmp_dir = ".";
|
|
}
|
|
std::filesystem::path tmp_path = tmp_dir / ("clip_" + std::to_string(event.timestamp_ms) + "." + format_);
|
|
|
|
// Set up FFmpeg output
|
|
AVFormatContext* fmt_ctx = nullptr;
|
|
if (avformat_alloc_output_context2(&fmt_ctx, nullptr, format_.c_str(), tmp_path.string().c_str()) < 0) {
|
|
std::cerr << "[ClipAction] failed to create output context\n";
|
|
return "";
|
|
}
|
|
|
|
const AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_H264);
|
|
if (!codec) {
|
|
avformat_free_context(fmt_ctx);
|
|
return "";
|
|
}
|
|
|
|
AVStream* stream = avformat_new_stream(fmt_ctx, codec);
|
|
if (!stream) {
|
|
avformat_free_context(fmt_ctx);
|
|
return "";
|
|
}
|
|
|
|
AVCodecContext* enc_ctx = avcodec_alloc_context3(codec);
|
|
enc_ctx->width = width;
|
|
enc_ctx->height = height;
|
|
enc_ctx->time_base = AVRational{1, fps_};
|
|
enc_ctx->framerate = AVRational{fps_, 1};
|
|
enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
|
|
enc_ctx->bit_rate = 2000000;
|
|
enc_ctx->gop_size = fps_;
|
|
|
|
if (fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) {
|
|
enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
|
|
}
|
|
|
|
if (avcodec_open2(enc_ctx, codec, nullptr) < 0) {
|
|
avcodec_free_context(&enc_ctx);
|
|
avformat_free_context(fmt_ctx);
|
|
return "";
|
|
}
|
|
|
|
avcodec_parameters_from_context(stream->codecpar, enc_ctx);
|
|
stream->time_base = enc_ctx->time_base;
|
|
|
|
if (!(fmt_ctx->oformat->flags & AVFMT_NOFILE)) {
|
|
if (avio_open(&fmt_ctx->pb, tmp_path.string().c_str(), AVIO_FLAG_WRITE) < 0) {
|
|
avcodec_free_context(&enc_ctx);
|
|
avformat_free_context(fmt_ctx);
|
|
return "";
|
|
}
|
|
}
|
|
|
|
if (avformat_write_header(fmt_ctx, nullptr) < 0) {
|
|
avcodec_free_context(&enc_ctx);
|
|
avformat_free_context(fmt_ctx);
|
|
return "";
|
|
}
|
|
|
|
// Encode frames
|
|
AVFrame* av_frame = av_frame_alloc();
|
|
av_frame->width = width;
|
|
av_frame->height = height;
|
|
av_frame->format = AV_PIX_FMT_YUV420P;
|
|
av_frame_get_buffer(av_frame, 32);
|
|
|
|
AVPacket* pkt = av_packet_alloc();
|
|
int64_t pts = 0;
|
|
|
|
auto encode_frame = [&](const std::shared_ptr<Frame>& frame) {
|
|
if (!frame) return;
|
|
|
|
AVPixelFormat src_fmt = AV_PIX_FMT_NONE;
|
|
if (frame->format == PixelFormat::RGB) {
|
|
src_fmt = AV_PIX_FMT_RGB24;
|
|
} else if (frame->format == PixelFormat::BGR) {
|
|
src_fmt = AV_PIX_FMT_BGR24;
|
|
} else if (frame->format == PixelFormat::NV12) {
|
|
src_fmt = AV_PIX_FMT_NV12;
|
|
} else if (frame->format == PixelFormat::YUV420) {
|
|
src_fmt = AV_PIX_FMT_YUV420P;
|
|
}
|
|
if (src_fmt == AV_PIX_FMT_NONE) return;
|
|
|
|
SwsContext* sws = sws_getContext(width, height, src_fmt,
|
|
width, height, AV_PIX_FMT_YUV420P,
|
|
SWS_BILINEAR, nullptr, nullptr, nullptr);
|
|
if (sws) {
|
|
uint8_t* src_data[4] = {nullptr, nullptr, nullptr, nullptr};
|
|
int src_linesize[4] = {0, 0, 0, 0};
|
|
|
|
auto plane_ptr = [&](int idx) -> uint8_t* {
|
|
if (idx < 0 || idx >= frame->plane_count) return nullptr;
|
|
if (frame->planes[idx].data) return frame->planes[idx].data;
|
|
if (!frame->data) return nullptr;
|
|
const int off = frame->planes[idx].offset;
|
|
if (off < 0 || static_cast<size_t>(off) >= frame->data_size) return nullptr;
|
|
return frame->data + off;
|
|
};
|
|
auto plane_stride = [&](int idx, int fallback) -> int {
|
|
if (idx >= 0 && idx < frame->plane_count && frame->planes[idx].stride > 0) {
|
|
return frame->planes[idx].stride;
|
|
}
|
|
if (frame->stride > 0) return frame->stride;
|
|
return fallback;
|
|
};
|
|
|
|
if (frame->format == PixelFormat::RGB || frame->format == PixelFormat::BGR) {
|
|
src_data[0] = plane_ptr(0) ? plane_ptr(0) : frame->data;
|
|
src_linesize[0] = plane_stride(0, width * 3);
|
|
} else if (frame->format == PixelFormat::NV12) {
|
|
src_data[0] = plane_ptr(0) ? plane_ptr(0) : frame->data;
|
|
src_data[1] = plane_ptr(1);
|
|
if (!src_data[1] && frame->data) src_data[1] = frame->data + static_cast<size_t>(width) * height;
|
|
src_linesize[0] = plane_stride(0, width);
|
|
src_linesize[1] = plane_stride(1, width);
|
|
} else if (frame->format == PixelFormat::YUV420) {
|
|
src_data[0] = plane_ptr(0) ? plane_ptr(0) : frame->data;
|
|
src_data[1] = plane_ptr(1);
|
|
src_data[2] = plane_ptr(2);
|
|
src_linesize[0] = plane_stride(0, width);
|
|
src_linesize[1] = plane_stride(1, width / 2);
|
|
src_linesize[2] = plane_stride(2, width / 2);
|
|
}
|
|
|
|
if (!src_data[0]) {
|
|
sws_freeContext(sws);
|
|
return;
|
|
}
|
|
sws_scale(sws, src_data, src_linesize, 0, height,
|
|
av_frame->data, av_frame->linesize);
|
|
sws_freeContext(sws);
|
|
}
|
|
|
|
av_frame->pts = pts++;
|
|
|
|
avcodec_send_frame(enc_ctx, av_frame);
|
|
while (avcodec_receive_packet(enc_ctx, pkt) == 0) {
|
|
av_packet_rescale_ts(pkt, enc_ctx->time_base, stream->time_base);
|
|
pkt->stream_index = stream->index;
|
|
av_interleaved_write_frame(fmt_ctx, pkt);
|
|
av_packet_unref(pkt);
|
|
}
|
|
};
|
|
|
|
for (const auto& f : frames) {
|
|
encode_frame(f);
|
|
}
|
|
|
|
// Flush encoder
|
|
avcodec_send_frame(enc_ctx, nullptr);
|
|
while (avcodec_receive_packet(enc_ctx, pkt) == 0) {
|
|
av_packet_rescale_ts(pkt, enc_ctx->time_base, stream->time_base);
|
|
pkt->stream_index = stream->index;
|
|
av_interleaved_write_frame(fmt_ctx, pkt);
|
|
av_packet_unref(pkt);
|
|
}
|
|
|
|
av_write_trailer(fmt_ctx);
|
|
|
|
av_packet_free(&pkt);
|
|
av_frame_free(&av_frame);
|
|
avcodec_free_context(&enc_ctx);
|
|
if (!(fmt_ctx->oformat->flags & AVFMT_NOFILE)) { avio_closep(&fmt_ctx->pb); }
|
|
avformat_free_context(fmt_ctx);
|
|
|
|
// Read file and upload
|
|
std::ifstream file(tmp_path, std::ios::binary | std::ios::ate);
|
|
if (!file) {
|
|
std::cerr << "[ClipAction] failed to read temp file\n";
|
|
return "";
|
|
}
|
|
|
|
size_t file_size = file.tellg();
|
|
file.seekg(0);
|
|
std::vector<uint8_t> file_data(file_size);
|
|
file.read(reinterpret_cast<char*>(file_data.data()), file_size);
|
|
file.close();
|
|
|
|
std::string key = GenerateKey(event);
|
|
auto result = uploader_->Upload(key, file_data.data(), file_data.size(), "video/mp4");
|
|
|
|
// Clean up temp file
|
|
std::error_code ec;
|
|
std::filesystem::remove(tmp_path, ec);
|
|
|
|
if (result.success) {
|
|
return result.url;
|
|
}
|
|
std::cerr << "[ClipAction] upload failed: " << result.error << "\n";
|
|
#else
|
|
std::cerr << "[ClipAction] FFmpeg not enabled\n";
|
|
#endif
|
|
return "";
|
|
}
|
|
|
|
std::string ClipAction::GenerateKey(const AlarmEvent& event) {
|
|
auto now = std::chrono::system_clock::now();
|
|
auto time_t_now = std::chrono::system_clock::to_time_t(now);
|
|
std::tm* tm = std::localtime(&time_t_now);
|
|
|
|
std::ostringstream oss;
|
|
oss << std::put_time(tm, "%Y%m%d") << "/"
|
|
<< event.node_id << "_"
|
|
<< std::put_time(tm, "%H%M%S") << "_"
|
|
<< event.frame_id << "." << format_;
|
|
return oss.str();
|
|
}
|
|
|
|
} // namespace rk3588
|