id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,542,934
|
cv_target_rect.cpp
|
edman007_chiton/cv_target_rect.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "cv_target_rect.hpp"
#ifdef HAVE_OPENCV
#include "util.hpp"
TargetRect::TargetRect(const cv::RotatedRect &rect) : rect(rect) {
count = 0;
valid = true;
frame = NULL;//we never actually allocate for the first frame
}
TargetRect::TargetRect(const TargetRect &old_target, const cv::RotatedRect &new_rect, const AVFrame *cur_frame){
frame = av_frame_alloc();
if (old_target.frame && old_target.rect.size.area() > new_rect.size.area()){
int ret = av_frame_ref(frame, old_target.frame);
if (ret){
LERROR("av_frame_ref failed TargetRect::1");
}
best_rect = old_target.rect;
} else {
int ret = av_frame_ref(frame, cur_frame);
if (ret){
LERROR("av_frame_ref failed Targetrect::2");
}
best_rect = new_rect;
}
rect = new_rect;
valid = true;
count = old_target.count + 1;
}
TargetRect::TargetRect(const TargetRect &rhs){
rect = rhs.rect;
best_rect = rhs.best_rect;
count = rhs.count;
valid = rhs.valid;
if (rhs.frame){
//alloc and copy the frame
frame = av_frame_alloc();
int ret = av_frame_ref(frame, rhs.frame);
if (ret){
LERROR("av_frame_ref failed TargetRect::3");
}
} else {
frame = NULL;
}
LDEBUG("Slow copy of TargetRect");
}
TargetRect::TargetRect(TargetRect &&rhs) noexcept
: rect(std::move(rhs.rect)), best_rect(std::move(rhs.best_rect)) {
count = rhs.count;
valid = rhs.valid;
frame = rhs.frame;
rhs.frame = NULL;
}
TargetRect::~TargetRect(){
av_frame_free(&frame);
}
const cv::RotatedRect& TargetRect::get_rect(void) const {
return rect;
}
bool TargetRect::is_valid(void) const{
return valid;
}
void TargetRect::mark_invalid(void){
valid = false;
}
int TargetRect::get_count(void) const{
return count;
}
void TargetRect::scale(float s) {
if (s == 1){
return;
}
scale_rect(s, rect);
scale_rect(s, best_rect);
}
void TargetRect::scale_rect(float s, cv::RotatedRect &rect) {
rect.center.x /= s;
rect.center.y /= s;
rect.size.width /= s;
rect.size.height /= s;
}
const AVFrame *TargetRect::get_best_frame(void) const {
return frame;
}
const cv::RotatedRect& TargetRect::get_best_rect(void) const {
return best_rect;
}
//HAVE_OPENCV
#endif
| 3,279
|
C++
|
.cpp
| 108
| 26.185185
| 112
| 0.624525
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,935
|
motion_controller.cpp
|
edman007_chiton/motion_controller.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "motion_controller.hpp"
#include "util.hpp"
#include "motion_opencv.hpp"
#include "motion_cvbackground.hpp"
#include "motion_cvmask.hpp"
#include "motion_cvdetect.hpp"
#include "motion_cvdebugshow.hpp"
#include "motion_cvresize.hpp"
MotionController::MotionController(Database &db, Config &cfg, StreamUnwrap &stream, ImageUtil &img) :
ModuleController<MotionAlgo, MotionController>(cfg, db, "motion"),
stream(stream),
events(cfg, db, img),
img(img) {
video_idx = -1;
audio_idx = -1;
skip_ratio = cfg.get_value_double("motioncontroller-skip-ratio");
if (skip_ratio < 0){
skip_ratio = 0;
} else if (skip_ratio > 1){
skip_ratio = 1;
}
//register all known algorithms
#ifdef HAVE_OPENCV
register_module(new ModuleFactory<MotionOpenCV, MotionAlgo, MotionController>());
register_module(new ModuleFactory<MotionCVBackground, MotionAlgo, MotionController>());
register_module(new ModuleFactory<MotionCVMask, MotionAlgo, MotionController>());
register_module(new ModuleFactory<MotionCVDetect, MotionAlgo, MotionController>());
register_module(new ModuleFactory<MotionCVResize, MotionAlgo, MotionController>());
#ifdef DEBUG
register_module(new ModuleFactory<MotionCVDebugShow, MotionAlgo, MotionController>());
#endif
#endif
add_mods();
}
MotionController::~MotionController(){
}
bool MotionController::process_frame(int index, const AVFrame *frame, bool &skipped){
skipped = false;
bool video = index == video_idx;
if (!video && index != audio_idx){
return false;//unknown stream
}
if (should_skip()){
LINFO("Skipping frame due to excessive processing time");
skipped = true;
return true;
}
bool ret = true;
for (auto &ma : mods){
ret &= ma->process_frame(frame, video);
}
return ret;
}
bool MotionController::set_streams(void){
bool ret = set_video_stream(stream.get_video_stream(), stream.get_codec_context(stream.get_video_stream()));
ret &= set_audio_stream(stream.get_audio_stream(), stream.get_codec_context(stream.get_audio_stream()));
return ret;
}
bool MotionController::set_video_stream(const AVStream *stream, const AVCodecContext *codec){
if (!stream){
return false;//there is no video stream
}
video_idx = stream->index;
if (codec){
img.set_profile(codec->codec_id, codec->profile);
}
bool ret = true;
for (auto &ma : mods){
ret &= ma->set_video_stream(stream, codec);
}
return ret;
}
bool MotionController::set_audio_stream(const AVStream *stream, const AVCodecContext *codec){
if (!stream){
return false;//there is no audio stream
}
audio_idx = stream->index;
bool ret = true;
for (auto &ma : mods){
ret &= ma->set_audio_stream(stream, codec);
}
return ret;
}
bool MotionController::decode_video(void){
return !mods.empty();//need something better
}
bool MotionController::decode_audio(void){
return false;//unsupported
}
void MotionController::get_frame_timestamp(const AVFrame *frame, bool video, struct timeval &time){
if (video){
stream.timestamp(frame, video_idx, time);
} else {
stream.timestamp(frame, audio_idx, time);
}
}
EventController& MotionController::get_event_controller(void){
return events;
}
bool MotionController::should_skip(void){
//LINFO("Current Ratio is " + std::to_string(stream.get_mean_delay()/stream.get_mean_duration()));
if (stream.get_mean_duration() <= 0 || skip_ratio == 0){
return false;//disabled if the duration or skip ratio is unreasonable.
} else if (skip_ratio == 1){
return true;
}
return stream.get_mean_delay()/stream.get_mean_duration() < skip_ratio;
}
| 4,702
|
C++
|
.cpp
| 129
| 32.387597
| 112
| 0.675516
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,936
|
motion_cvresize.cpp
|
edman007_chiton/motion_cvresize.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "motion_cvresize.hpp"
#ifdef HAVE_OPENCV
#include "util.hpp"
#include <opencv2/imgproc.hpp>
static const std::string algo_name = "cvresize";
MotionCVResize::MotionCVResize(Config &cfg, Database &db, MotionController &controller) : MotionAlgo(cfg, db, controller, algo_name) {
scale_ratio = cfg.get_value_double("motion-cvresize-scale");
if (scale_ratio <= 0 || scale_ratio > 1){
scale_ratio = 1;
}
ocv = NULL;
}
MotionCVResize::~MotionCVResize(){
ocv = NULL;
}
bool MotionCVResize::process_frame(const AVFrame *frame, bool video){
if (!video || !ocv){
return true;
}
if (scale_ratio == 1){
return true;
}
cv::resize(ocv->get_UMat(), buf_mat, cv::Size(), scale_ratio, scale_ratio, cv::INTER_NEAREST);
return true;
}
bool MotionCVResize::init(void) {
ocv = static_cast<MotionOpenCV*>(controller.get_module_before("opencv", this));
return true;
}
bool MotionCVResize::set_video_stream(const AVStream *stream, const AVCodecContext *codec) {
return true;
}
const std::string& MotionCVResize::get_mod_name(void) {
return algo_name;
}
const cv::UMat& MotionCVResize::get_UMat(void) const {
if (scale_ratio == 1){
return ocv->get_UMat();
}
return buf_mat;
}
float MotionCVResize::get_scale_ratio(void) const {
return scale_ratio;
}
#endif
| 2,270
|
C++
|
.cpp
| 66
| 31.227273
| 134
| 0.65267
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,937
|
database_manager.cpp
|
edman007_chiton/database_manager.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2021 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "database_manager.hpp"
#include "util.hpp"
//we increment Major when we break backwards compatibility
static const int CURRENT_DB_VERSION_MAJOR = 1;
//we increment minor when we add a backwards compatible version
static const int CURRENT_DB_VERSION_MINOR = 4;
static const std::string CURRENT_DB_VERSION = std::to_string(CURRENT_DB_VERSION_MAJOR) + "." + std::to_string(CURRENT_DB_VERSION_MINOR);
DatabaseManager::DatabaseManager(Database &db) : db(db) {
}
bool DatabaseManager::initilize_db(){
const std::string config_tbl = "CREATE TABLE config ( "
"name varchar(40) COLLATE utf8mb4_unicode_ci NOT NULL, "
"value varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, "
"camera int(11) NOT NULL, "
"UNIQUE KEY camera (camera,name) "
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
const std::string videos_tbl = "CREATE TABLE videos ( "
"id int(11) unsigned NOT NULL AUTO_INCREMENT, "
"path varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, "
"starttime bigint(20) NOT NULL, "
"endtime bigint(20) DEFAULT NULL, "
"camera int(11) NOT NULL, "
"`locked` tinyint(1) NOT NULL DEFAULT 0, "
"`extension` ENUM('.ts','.mp4') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '.ts', "
"`name` BIGINT NOT NULL, "
"`init_byte` INT NULL DEFAULT NULL, "
"`start_byte` INT NULL DEFAULT NULL, "
"`end_byte` INT NULL DEFAULT NULL, "
"`codec` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, "
"`av_type` ENUM('audio', 'video', 'audiovideo') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'audiovideo', "
"`width` INT NULL DEFAULT NULL, "
"`height` INT NULL DEFAULT NULL, "
"`framerate` FLOAT NULL DEFAULT NULL, "
"PRIMARY KEY (id,camera,starttime), "
"KEY endtime (endtime), "
"KEY starttime (starttime), "
"KEY camera (camera) "
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
const std::string exports_tbl = "CREATE TABLE `exports` ( "
"`id` int(10) unsigned NOT NULL AUTO_INCREMENT, "
"`camera` int(11) NOT NULL, "
"`path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', "
"`starttime` bigint(20) NOT NULL, "
"`endtime` bigint(20) NOT NULL, "
"`progress` int(11) NOT NULL DEFAULT 0, "
"PRIMARY KEY (`id`), "
"KEY `camera` (`camera`,`starttime`,`progress`) "
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
const std::string images_tbl = "CREATE TABLE `images` ( "
"`id` int(11) NOT NULL AUTO_INCREMENT, "
" camera int(11) NOT NULL, "
"`path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, "
"`prefix` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, "
"`extension` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, "
"`starttime` bigint(20) NOT NULL, "
"PRIMARY KEY (`id`), "
"KEY starttime (starttime) "
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
const std::string events_tbl ="CREATE TABLE `events` ("
"`id` int(11) NOT NULL AUTO_INCREMENT, "
"`camera` int(11) NOT NULL, "
"`img` int(11) DEFAULT NULL, "
"`source` varchar(64) NOT NULL, "
"`starttime` bigint(20) NOT NULL, "
"`x0` int(11) NOT NULL, "
"`y0` int(11) NOT NULL, "
"`x1` int(11) NOT NULL, "
"`y1` int(11) NOT NULL, "
"`score` float NOT NULL, "
"PRIMARY KEY (`id`), "
"KEY camera (`camera`, `source`, `starttime`) "
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ";
//create the config table
DatabaseResult *res = db.query(config_tbl);
bool ret = true;
if (res){
delete res;
} else {
LFATAL("Could not create config table");
ret = false;
}
//create the videos table
if (ret){
res = db.query(videos_tbl);
if (res){
delete res;
} else {
LFATAL("Could not create videos table");
ret = false;
}
}
//create the exports table
if (ret){
res = db.query(exports_tbl);
if (res){
delete res;
} else {
LFATAL("Could not create exports table");
ret = false;
}
}
//create the images table
if (ret){
res = db.query(images_tbl);
if (res){
delete res;
} else {
LFATAL("Could not create images table");
ret = false;
}
}
//create the events table
if (ret){
res = db.query(events_tbl);
if (res){
delete res;
} else {
LFATAL("Could not create events table");
ret = false;
}
}
if (ret){
return set_latest_version();
}
return ret;
}
bool DatabaseManager::check_database(void){
std::string sql = "SELECT value FROM config WHERE name = 'database-version' AND camera = -1";
DatabaseResult *res = db.query(sql);
bool ret = false;
if (res && res->next_row()){
std::string cur_version = res->get_field(0);
int cur_major;
int cur_minor;
try {
cur_major = std::stoi(cur_version.substr(0, cur_version.find('.')));
cur_minor = std::stoi(cur_version.substr(cur_version.find('.') + 1));
} catch (std::invalid_argument &e){
LDEBUG("Database Version is invalid");
cur_major = INT_MAX;
cur_minor = INT_MAX;
} catch (std::out_of_range &e) {
LDEBUG("Database Version is out of range");
cur_major = INT_MAX;
cur_minor = INT_MAX;
}
if (cur_major > CURRENT_DB_VERSION_MAJOR){
LFATAL("Error, current database version " + cur_version + " is incompible with this version of chiton");
} else if (cur_major < CURRENT_DB_VERSION_MAJOR){
if (!upgrade_database(cur_major, cur_minor)){
LFATAL("The database needs an upgrade, but the upgrade from " + cur_version + " to " + CURRENT_DB_VERSION);//shouldn't happen
} else {
ret = true;
}
//normally we would just upgrade...but no such upgrade is possible
} else {//equal
if (cur_minor > CURRENT_DB_VERSION_MINOR){
LWARN("Current database version is newer than expected (" + cur_version + " -> " + CURRENT_DB_VERSION
+ "), continuing without changing the database version");
ret = true;//this is not an issue
} else if (cur_minor < CURRENT_DB_VERSION_MINOR){
if (!upgrade_database(cur_major, cur_minor)){
LFATAL("The database needs an upgrade, but no other version is known, is " + cur_version + " but expected " + CURRENT_DB_VERSION);//shouldn't happen
} else {
ret = true;
}
} else {//equal
LINFO("Detected latest database version " + CURRENT_DB_VERSION);
ret = true;
}
}
} else {
//no database version? then we try initilizing it
ret = initilize_db();
}
delete res;
return ret;
}
bool DatabaseManager::set_latest_version(void){
std::string sql = "INSERT INTO config (camera, name, value) VALUES (-1, 'database-version', '"
+ CURRENT_DB_VERSION + "') ON DUPLICATE KEY UPDATE "
+ " value = '" + CURRENT_DB_VERSION + "'";
long affected_rows = 0;
DatabaseResult *res = db.query(sql, &affected_rows, NULL);
bool ret = false;
if (res && affected_rows){
LINFO("Database Upgraded to " + CURRENT_DB_VERSION);
ret = true;
} else {
LFATAL("Failed to update database version");
}
delete res;
return ret;
}
bool DatabaseManager::upgrade_database(int major, int minor){
if (1 == major){
switch (minor){
case 0:
return upgrade_from_1_0();
case 1:
return upgrade_from_1_1();
case 2:
return upgrade_from_1_2();
case 3:
return upgrade_from_1_3();
default:
return false;
}
}
return false;
}
bool DatabaseManager::upgrade_from_1_0(void){
const std::string alter_query = "ALTER TABLE `videos` ADD `locked` BOOLEAN NOT NULL DEFAULT FALSE AFTER `camera`";
const std::string exports_tbl = "CREATE TABLE `exports` ( "
"`id` int(10) unsigned NOT NULL AUTO_INCREMENT, "
"`camera` int(11) NOT NULL, "
"`path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', "
"`starttime` bigint(20) NOT NULL, "
"`endtime` bigint(20) NOT NULL, "
"`progress` int(11) NOT NULL DEFAULT 0, "
"PRIMARY KEY (`id`), "
"KEY `camera` (`camera`,`starttime`,`progress`) "
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
DatabaseResult *res = db.query(alter_query);
bool ret = true;
if (res){
delete res;
} else {
LWARN("Database Upgrade Failed - " + alter_query);
ret = false;
}
//create the exports table
if (ret){
res = db.query(exports_tbl);
if (res){
delete res;
} else {
LFATAL("Could not create exports table");
ret = false;
}
}
if (ret){
return upgrade_from_1_1();
} else {
return ret;
}
}
bool DatabaseManager::upgrade_from_1_1(void){
const std::string images_tbl = "CREATE TABLE `images` ( "
"`id` int(11) NOT NULL AUTO_INCREMENT, "
"camera int(11) NOT NULL, "
"`path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, "
"`prefix` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, "
"`extension` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, "
"`starttime` bigint(20) NOT NULL, "
"PRIMARY KEY (`id`), "
"KEY starttime (starttime) "
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
const std::string video_alter = "ALTER TABLE `videos` ADD `extension` ENUM('.ts','.mp4') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '.ts' AFTER `locked`, "
" ADD `name` BIGINT NOT NULL AFTER `extension`, "
" ADD `init_byte` INT NULL DEFAULT NULL AFTER `name`, "
" ADD `start_byte` INT NULL DEFAULT NULL AFTER `init_byte`, "
" ADD `end_byte` INT NULL DEFAULT NULL AFTER `start_byte`";
const std::string video_update = "UPDATE videos SET name = id";
bool ret = true;
DatabaseResult *res = db.query(images_tbl);
if (res){
delete res;
} else {
LFATAL("Could not create images table");
ret = false;
}
//update the video table
if (ret){
res = db.query(video_alter);
if (res){
delete res;
} else {
LFATAL("Could not alter video table");
ret = false;
}
}
if (ret){
res = db.query(video_update);
if (res){
delete res;
} else {
LFATAL("Could not update video table");
ret = false;
}
}
if (ret){
return upgrade_from_1_2();
} else {
return ret;
}
}
bool DatabaseManager::upgrade_from_1_2(void){
const std::string video_alter = "ALTER TABLE `videos` ADD "
"`codec` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL AFTER `end_byte`, "
"ADD `av_type` ENUM('audio', 'video', 'audiovideo') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'audiovideo' AFTER `codec`, "
"ADD `width` INT NULL DEFAULT NULL AFTER `av_type`, "
"ADD `height` INT NULL DEFAULT NULL AFTER `width`, "
"ADD `framerate` FLOAT NULL DEFAULT NULL AFTER `height`";
bool ret = true;
DatabaseResult *res = db.query(video_alter);
if (res){
delete res;
} else {
LFATAL("Could not alter video table");
ret = false;
}
if (ret){
return upgrade_from_1_3();
} else {
return ret;
}
}
bool DatabaseManager::upgrade_from_1_3(void){
const std::string events_tbl ="CREATE TABLE `events` ("
"`id` int(11) NOT NULL AUTO_INCREMENT, "
"`camera` int(11) NOT NULL, "
"`img` int(11) DEFAULT NULL, "
"`source` varchar(64) NOT NULL, "
"`starttime` bigint(20) NOT NULL, "
"`x0` int(11) NOT NULL, "
"`y0` int(11) NOT NULL, "
"`x1` int(11) NOT NULL, "
"`y1` int(11) NOT NULL, "
"`score` float NOT NULL, "
"PRIMARY KEY (`id`), "
"KEY camera (`camera`, `source`, `starttime`) "
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ";
bool ret = true;
DatabaseResult *res = db.query(events_tbl);
if (res){
delete res;
} else {
LFATAL("Could not create events table");
ret = false;
}
if (ret){
return set_latest_version();
} else {
return ret;
}
}
| 14,354
|
C++
|
.cpp
| 368
| 31.100543
| 182
| 0.584546
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,938
|
config.cpp
|
edman007_chiton/config.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include "util.hpp"
#include <fstream>
#include "config_parser.hpp"
#include "setting.hpp"
Config::Config(){
set_value("camera-id", std::string("-1"));//set the camera ID so other tools can use it
}
Config::Config(const Config &src) : cfg_db(src.cfg_db) {
set_value("camera-id", std::string("-1"));//set the camera ID so other tools can use it
}
bool Config::load_config(const std::string& path){
std::ifstream ifs;
ifs.open(path);
if (ifs.fail()){
LWARN( "Failed to open config file `" + path + "`");
return false;//didn't work
}
ConfigParser parser(*this, ifs);
parser.parse();
return true;
}
const std::string& Config::get_value(const std::string& key){
if (!key.compare("")){
LWARN( "Code is requesting a null key");
return EMPTY_STR;
}
auto ret = cfg_db.find(key);
if (ret == cfg_db.end()){
return get_default_value(key);
} else {
return ret->second;
}
}
void Config::set_value(const std::string& key, const std::string& value){
if (key.compare("")){
cfg_db[key] = value;
} else {
LINFO( "Ignoring empty key");
}
}
int Config::get_value_int(const std::string& key){
const std::string& val = get_value(key);
if (!val.compare("")){
//empty
return 0;
}
try {
return std::stoi(val);
} catch (const std::invalid_argument& ia){
LWARN( "Config value " + key + " ( " + val + " ) must be an integer");
} catch (const std::out_of_range& ia) {
LWARN( "Config value " + key + " ( " + val + " ) is out of range ");
}
return 0;
}
long Config::get_value_long(const std::string& key){
const std::string& val = get_value(key);
if (!val.compare("")){
//empty
return 0;
}
try {
return std::stol(val);
} catch (const std::invalid_argument& ia){
LWARN( "Config value " + key + " ( " + val + " ) must be an integer");
} catch (const std::out_of_range& ia) {
LWARN( "Config value " + key + " ( " + val + " ) is out of range ");
}
return 0;
}
long long Config::get_value_ll(const std::string& key){
const std::string& val = get_value(key);
if (!val.compare("")){
//empty
return 0;
}
try {
return std::stoll(val);
} catch (const std::invalid_argument& ia){
LWARN( "Config value " + key + " ( " + val + " ) must be an integer");
} catch (const std::out_of_range& ia) {
LWARN( "Config value " + key + " ( " + val + " ) is out of range ");
}
return 0;
}
double Config::get_value_double(const std::string& key){
const std::string& val = get_value(key);
if (!val.compare("")){
//empty
return 0;
}
try {
return std::stod(val);
} catch (const std::invalid_argument& ia){
LWARN( "Config value " + key + " ( " + val + " ) must be an integer");
} catch (const std::out_of_range& ia) {
LWARN( "Config value " + key + " ( " + val + " ) is out of range ");
}
return 0;
}
const std::string& Config::get_default_value(const std::string& key){
for (auto& itr : setting_options){
if (itr.key == key){\
//LDEBUG("Got default value of '" + itr.def + "' for '" + key + "'");//this is really verbose...
return itr.def;
}
}
LWARN("Code used undocumented config value '" + key + "'");
return EMPTY_STR;
}
bool Config::load_camera_config(int camera, Database &db){
//loads the global and then overwrites it with the local
DatabaseResult *res = db.query("SELECT name, value FROM config WHERE camera = -1 OR camera = " + std::to_string(camera) + " ORDER by camera ASC" );
if (!res){
return false;
}
while (res && res->next_row()){
set_value(res->get_field(0), res->get_field(1));
}
delete res;
set_value("camera-id", std::to_string(camera));//to allow us to pull this later
return true;
}
| 4,956
|
C++
|
.cpp
| 145
| 29.096552
| 151
| 0.579124
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,939
|
event.cpp
|
edman007_chiton/event.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "event.hpp"
#include "util.hpp"
Event::Event(Config &cfg) : cfg(cfg) {
src = NULL;
clear();
};
Event::~Event(){
av_frame_free(&src);
}
bool Event::set_timestamp(struct timeval &etime){
time.tv_sec = etime.tv_sec;
time.tv_usec = etime.tv_usec;
return true;
}
const struct timeval &Event::get_timestamp(void){
return time;
}
bool Event::set_position(float x0, float y0, float x1, float y1){
pos.reserve(4);
pos[0] = x0;
pos[1] = y0;
pos[2] = x1;
pos[3] = y1;
return true;
}
#ifdef HAVE_OPENCV
bool Event::set_position(const TargetRect &rect){
const cv::RotatedRect &r = rect.get_best_rect();
const cv::Rect b_rect = r.boundingRect();//upright rect
auto tl = b_rect.tl();//top left
auto br = b_rect.br();//bottom right
pos.reserve(4);
pos[0] = tl.x;
pos[1] = tl.y;
pos[2] = br.x;
pos[3] = br.y;
return true;
}
#endif
const std::vector<float>& Event::get_position(void){
return pos;
}
bool Event::set_frame(const AVFrame *frame){
if (!src){
src = av_frame_alloc();
} else {
av_frame_unref(src);
}
int ret = av_frame_ref(src, frame);
if (ret){
LERROR("av_frame_ref failed Event::set_frame");
}
return true;
}
const AVFrame* Event::get_frame(void){
return src;
}
void Event::clear(){
if (src){
//FIXME: Should this actually deallocate it, or should we have logic to just act as if it was deallocated to avoid excessive allocation
av_frame_unref(src);
av_frame_free(&src);
}
src = NULL;
time.tv_sec = 0;
time.tv_usec = 0;
source = "?";
score = 0;
valid = true;
}
void Event::invalidate(void){
valid = false;
}
bool Event::is_valid(void){
return valid;
}
bool Event::set_source(const std::string &name){
source = name;
return true;
}
const std::string& Event::get_source(void){
return source;
}
bool Event::set_score(float new_score){
score = new_score;
if (score < 0){
score = 0;
return false;
}
if (score > 100){
score = 100;
return false;
}
return true;
}
float Event::get_score(void){
return score;
}
| 3,122
|
C++
|
.cpp
| 119
| 22.512605
| 143
| 0.611985
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,940
|
stream_writer.cpp
|
edman007_chiton/stream_writer.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2021 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "stream_writer.hpp"
#include "util.hpp"
#include "chiton_ffmpeg.hpp"
#include <assert.h>
#include <iomanip>
#include <sstream>
StreamWriter::StreamWriter(Config& cfg) : cfg(cfg) {
file_opened = false;
init_seg = NULL;
init_len = -1;
output_file = NULL;
if (cfg.get_value("output-extension") == ".mp4"){
segment_mode = SEGMENT_FMP4;
} else {
segment_mode = SEGMENT_MPGTS;
}
interleave_queue_depth = cfg.get_value_int("interleave-queue-depth");
if (interleave_queue_depth > 10000 || interleave_queue_depth < 0){
interleave_queue_depth = 4;
}
video_stream_found = false;
audio_stream_found = false;
video_width = -1;
video_height = -1;
video_framerate = 0;
enc_pkt = av_packet_alloc();
}
bool StreamWriter::open(void){
if (file_opened){
return true;//already opened
}
stream_offset.clear();
last_dts.clear();
return open_path();
}
bool StreamWriter::open_path(void){
int error;
const AVOutputFormat *ofmt = output_format_context->oformat;
if (!(ofmt->flags & AVFMT_NOFILE)) {
if (output_file != NULL){
LERROR("Attempted to open file that's already open");
return false;
}
error = avio_open(&output_file, path.c_str(), AVIO_FLAG_WRITE);
if (error < 0) {
LERROR("Could not open output file '" + path + "'");
LERROR("Error occurred: " + std::string(av_err2str(error)));
return false;
}
if (output_format_context->pb != NULL){
LERROR("Attempted to open buffer that's already open");
return false;
}
error = avio_open_dyn_buf(&output_format_context->pb);
if (error < 0) {
LERROR("Could not open buffer");
LERROR("Error occurred: " + std::string(av_err2str(error)));
return false;
}
}
//apply the mux options
AVDictionary *opts = Util::get_dict_options(cfg.get_value("ffmpeg-mux-options"));
if (segment_mode == SEGMENT_FMP4){
//we need to make mp4s fragmented
//empty_moov+separate_moof++dash++separate_moof+omit_tfhd_offset+default_base_moof"
//skip_sidx requires libavf > 58.24.100
#if ((LIBAVFORMAT_VERSION_MAJOR >= 59) || (LIBAVFORMAT_VERSION_MAJOR == 58 && LIBAVFORMAT_VERSION_MINOR >= 25))
av_dict_set(&opts, "movflags", "+frag_custom+delay_moov+dash+skip_sidx+skip_trailer+empty_moov", 0);
#else
av_dict_set(&opts, "movflags", "+frag_custom+delay_moov+dash+global_sidx+skip_trailer+empty_moov", 0);
#endif
}
if (segment_mode == SEGMENT_FMP4 && init_len >= 0){
write_init();
} else {
error = avformat_write_header(output_format_context, &opts);
av_dict_free(&opts);
if (error < 0) {
LERROR("Error occurred when opening output file");
LERROR("Error occurred: " + std::string(av_err2str(error)));
return false;
}
init_len = frag_stream();
}
av_dump_format(output_format_context, 0, path.c_str(), 1);
file_opened = true;
return true;
}
StreamWriter::~StreamWriter(){
free_context();
av_packet_free(&enc_pkt);
}
long long StreamWriter::close(void){
if (!file_opened){
LWARN("Attempted to close a output stream that wasn't open");
return 0;
}
//flush it...
if (0 > av_interleaved_write_frame(output_format_context, NULL)){
LERROR("Error flushing muxing output for camera " + cfg.get_value("camera-id"));
}
if (0 > av_write_frame(output_format_context, NULL)){
LERROR("Error flushing muxing output for camera " + cfg.get_value("camera-id"));
}
if (segment_mode != SEGMENT_FMP4){
av_write_trailer(output_format_context);
}
avio_flush(output_format_context->pb);
write_buf(false);
long long pos = avio_tell(output_file);
avio_closep(&output_file);
file_opened = false;
return pos;
}
bool StreamWriter::write(const AVPacket *packet, const AVStream *in_stream){
if (!file_opened){
return false;
}
if (packet->stream_index >= static_cast<int>(stream_mapping.size()) ||
stream_mapping[packet->stream_index] < 0) {
return true;//we processed the stream we don't care about
}
AVStream *out_stream;
PacketInterleavingBuf *pkt_buf = new PacketInterleavingBuf(packet);
pkt_buf->video_keyframe = in_stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && packet->flags & AV_PKT_FLAG_KEY;
if (!pkt_buf->in || !pkt_buf->out){
LERROR("Could not allocate new output packet for writing");
delete pkt_buf;
return false;
}
//log_packet(unwrap.get_format_context(), packet, "in: " + path);
pkt_buf->out->stream_index = stream_mapping[pkt_buf->out->stream_index];
out_stream = output_format_context->streams[pkt_buf->out->stream_index];
/* copy packet */
pkt_buf->out->pts = av_rescale_q_rnd(pkt_buf->out->pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
pkt_buf->out->dts = av_rescale_q_rnd(pkt_buf->out->dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
pkt_buf->out->duration = av_rescale_q(pkt_buf->out->duration, in_stream->time_base, out_stream->time_base);
pkt_buf->out->pos = -1;
/* This should actually be used only for exporting video
//correct for the offset, it is intentional that we base the offset on DTS (always first), and subtract it from DTS and PTS to
//preserve any difference between them
if (stream_offset[stream_mapping[pkt_buf->out->stream_index]] < 0){
stream_offset[stream_mapping[pkt_buf->out->stream_index]] = pkt_buf->out->dts;
}
pkt_buf->out->dts -= stream_offset[stream_mapping[pkt_buf->out->stream_index]];
pkt_buf->out->pts -= stream_offset[stream_mapping[pkt_buf->out->stream_index]];
*/
//guarentee that they have an increasing DTS
if (pkt_buf->out->dts < last_dts[pkt_buf->out->stream_index]){
LWARN("Shifting frame timestamp due to out of order issue in camera " + cfg.get_value("camera-id") +", old dts was: " + std::to_string(pkt_buf->out->dts));
last_dts[pkt_buf->out->stream_index]++;
long pts_delay = pkt_buf->out->pts - pkt_buf->out->dts;
pkt_buf->out->dts = last_dts[pkt_buf->out->stream_index];
pkt_buf->out->pts = pkt_buf->out->dts + pts_delay;
} else if (pkt_buf->out->dts == last_dts[pkt_buf->out->stream_index]) {
LWARN("Received duplicate frame from camera " + cfg.get_value("camera-id") +" at dts: " + std::to_string(pkt_buf->out->dts) + ". Dropping Frame");
delete pkt_buf;
return true;
}
last_dts[pkt_buf->out->stream_index] = pkt_buf->out->dts;
//log_packet(output_format_context, out_pkt, "out: "+path);
interleave(pkt_buf);
return write_interleaved();
}
bool StreamWriter::write(PacketInterleavingBuf *pkt_buf){
if (keyframe_cbk && pkt_buf->video_keyframe){
keyframe_cbk(pkt_buf->in, *this);
}
//log_packet(output_format_context, pkt_buf->out, "Final Write");
write_counter += pkt_buf->out->size;//log this
int ret = av_interleaved_write_frame(output_format_context, pkt_buf->out);
if (ret < 0) {
LERROR("Error muxing packet for camera " + cfg.get_value("camera-id"));
return false;
}
delete pkt_buf;
return true;
}
void StreamWriter::log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt, const std::string &tag){
AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
LINFO(tag + ": pts:" + std::string(av_ts2str(pkt->pts)) +
" pts_time:"+std::string(av_ts2timestr(pkt->pts, time_base))+
" dts:" + std::string(av_ts2str(pkt->dts)) +
" dts_time:"+ std::string(av_ts2timestr(pkt->dts, time_base)) +
" duration:" +std::string(av_ts2str(pkt->duration)) +
" duration_time:" + std::string(av_ts2timestr(pkt->duration, time_base))+
" stream_index:" + std::to_string(pkt->stream_index)
);
av_pkt_dump_log2(NULL, 30, pkt, 0, fmt_ctx->streams[pkt->stream_index]);
}
long long StreamWriter::change_path(const std::string &new_path /* = "" */){
if ((path == new_path || new_path.empty()) && segment_mode == SEGMENT_FMP4){
return frag_stream();
} else if (!new_path.empty()){
long long pos = -1;
if (file_opened){//we close and reopen only if already open, otherwise the caller must open() after adding streams
pos = close();
path = new_path;
open_path();
} else {
path = new_path;
}
return pos;
}
return -1;
}
void StreamWriter::free_context(void){
if (file_opened){
close();
}
if (init_seg){
init_len = -1;
av_free(init_seg);
init_seg = NULL;
}
//free our interleaving buffers
for (auto ibuf : interleaving_buf){
delete ibuf;
}
interleaving_buf.clear();
avformat_free_context(output_format_context);
output_format_context = NULL;
stream_mapping.clear();
for (auto &encoder : encode_ctx){
avcodec_free_context(&encoder.second);
}
codec_str.clear();
video_stream_found = false;
audio_stream_found = false;
video_width = -1;
video_height = -1;
video_framerate = 0;
}
bool StreamWriter::alloc_context(void){
if (output_format_context){
return true;
}
avformat_alloc_output_context2(&output_format_context, NULL, NULL, path.c_str());
if (!output_format_context) {
LERROR("Could not create output context");
int error = AVERROR_UNKNOWN;
LERROR("Error occurred: " + std::string(av_err2str(error)));
return false;
}
return true;
}
bool StreamWriter::add_stream(const AVStream *in_stream){
AVStream *out_stream = init_stream(in_stream);
if (out_stream == NULL){
return false;
}
int error = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
if (error < 0) {
LERROR("Failed to copy codec parameters\n");
LERROR("Error occurred: " + std::string(av_err2str(error)));
return false;
}
if (stream_mapping[in_stream->index] != -1){
gen_codec_str(stream_mapping[in_stream->index], out_stream->codecpar);
}
//record the framerate for later from the input if the output didn't have it
if (in_stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO){
guess_framerate(in_stream);
guess_framerate(out_stream);//does this do anything if we just copied it?
LINFO("Framerate guessed is: " + std::to_string(video_framerate));
}
//validate the codec_tag
validate_codec_tag(out_stream);
return true;
}
bool StreamWriter::copy_streams(StreamUnwrap &unwrap){
bool ret = false;
for (unsigned int i = 0; i < unwrap.get_stream_count(); i++) {
ret |= add_stream(unwrap.get_format_context()->streams[i]);
}
return ret;
}
bool StreamWriter::add_encoded_stream(const AVStream *in_stream, const AVCodecContext *dec_ctx){
return add_encoded_stream(in_stream, dec_ctx, NULL);
}
bool StreamWriter::add_encoded_stream(const AVStream *in_stream, const AVCodecContext *dec_ctx, const AVFrame *frame){
if (dec_ctx == NULL){
return false;
}
AVStream *out_stream = init_stream(in_stream);
if (out_stream == NULL){
return false;
}
const AVCodec *encoder = NULL;
AVDictionary *opts = NULL;//watch out about return and free
//Audio
if (dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO){
if (cfg.get_value("encode-format-audio") == "ac3"){
encoder = avcodec_find_encoder(AV_CODEC_ID_AC3);
}
if (!encoder) {//default or above option(s) failed
encoder = avcodec_find_encoder(AV_CODEC_ID_AAC);
}
if (encoder){
encode_ctx[out_stream->index] = avcodec_alloc_context3(encoder);
if (!encode_ctx[out_stream->index]){
LERROR("Could not alloc audio encoding context");
return false;
}
encode_ctx[out_stream->index]->sample_rate = dec_ctx->sample_rate;
//this changes in FFMpeg 5.1
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100)
encode_ctx[out_stream->index]->ch_layout = dec_ctx->ch_layout;
#else
encode_ctx[out_stream->index]->channel_layout = dec_ctx->channel_layout;
encode_ctx[out_stream->index]->channels = av_get_channel_layout_nb_channels(encode_ctx[out_stream->index]->channel_layout);
#endif
encode_ctx[out_stream->index]->sample_fmt = encoder->sample_fmts[0];
encode_ctx[out_stream->index]->time_base = (AVRational){1, encode_ctx[out_stream->index]->sample_rate};
//apply encode audio options
AVDictionary *aopts = Util::get_dict_options(cfg.get_value("ffmpeg-encode-audio-opt"));
av_dict_copy(&opts, aopts, 0);
av_dict_free(&aopts);
} else {
LWARN("Could not find audio encoder");
return false;
}
} else if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO){//video
LWARN("Adding Video Stream!");
encoder = get_vencoder(dec_ctx->width, dec_ctx->height);
if (encoder){
encode_ctx[out_stream->index] = avcodec_alloc_context3(encoder);
if (!encode_ctx[out_stream->index]){
LERROR("Could not alloc video encoding context");
return false;
}
encode_ctx[out_stream->index]->height = dec_ctx->height;
encode_ctx[out_stream->index]->width = dec_ctx->width;
encode_ctx[out_stream->index]->sample_aspect_ratio = dec_ctx->sample_aspect_ratio;
//pull the framerate through based on some guesses
if (dec_ctx->framerate.num != 0 && dec_ctx->framerate.num != 0){
encode_ctx[out_stream->index]->framerate = dec_ctx->framerate;
} else {
if (in_stream->avg_frame_rate.num != 0 && in_stream->avg_frame_rate.den){
encode_ctx[out_stream->index]->framerate = in_stream->avg_frame_rate;
} else if (in_stream->r_frame_rate.num != 0 && in_stream->r_frame_rate.den != 0){
encode_ctx[out_stream->index]->framerate = in_stream->r_frame_rate;
}
}
//pick a pixel format
if (frame){
encode_ctx[out_stream->index]->pix_fmt = static_cast<AVPixelFormat>(frame->format);
} else {
encode_ctx[out_stream->index]->pix_fmt = dec_ctx->pix_fmt;
}
encode_ctx[out_stream->index]->time_base = in_stream->time_base;//av_inv_q(dec_ctx->framerate);
//set the fourcc
if (encode_ctx[out_stream->index]->codec_id == AV_CODEC_ID_HEVC){
encode_ctx[out_stream->index]->codec_tag = MKTAG('h', 'v', 'c', '1');//should be for hevc only?
}
if (cfg.get_value("video-bitrate") != "auto"){
long bitrate = cfg.get_value_long("video-bitrate");
if (bitrate > 1){
encode_ctx[out_stream->index]->bit_rate = bitrate;
}
}
if (!encode_ctx[out_stream->index]->bit_rate){
double framerate = av_q2d(dec_ctx->framerate);
if (framerate < 1){
framerate = 30;
}
double pixel_sec = encode_ctx[out_stream->index]->height * encode_ctx[out_stream->index]->height * framerate;
//estimate the bitrate
if (encode_ctx[out_stream->index]->codec_id == AV_CODEC_ID_HEVC){
encode_ctx[out_stream->index]->bit_rate = pixel_sec / 75;
} else {
//h264
encode_ctx[out_stream->index]->bit_rate = pixel_sec / 40;
}
}
//set min/max bitrate to +/- 10%
encode_ctx[out_stream->index]->rc_max_rate = encode_ctx[out_stream->index]->bit_rate + (encode_ctx[out_stream->index]->bit_rate/10);
encode_ctx[out_stream->index]->rc_min_rate = encode_ctx[out_stream->index]->bit_rate - (encode_ctx[out_stream->index]->bit_rate/10);
int bframe_max = cfg.get_value_int("video-encode-b-frame-max");
if (bframe_max < 0){
bframe_max = 16;
}
encode_ctx[out_stream->index]->max_b_frames = bframe_max;
LINFO("Selected video encode bitrate: " + std::to_string(encode_ctx[out_stream->index]->bit_rate/1000) + "kbps");
//apply encode video options
AVDictionary *vopts = Util::get_dict_options(cfg.get_value("ffmpeg-encode-video-opt"));
av_dict_copy(&opts, vopts, 0);
av_dict_free(&vopts);
//check if v4l2 was selected
bool using_v4l2 = std::string(encode_ctx[out_stream->index]->codec->name).find("_v4l2m2m") != std::string::npos;
//connect encoder, try VA-API
if (!using_v4l2 && !encode_ctx[out_stream->index]->hw_device_ctx &&
(cfg.get_value("video-encode-method") == "auto" || cfg.get_value("video-encode-method") == "vaapi")){
encode_ctx[out_stream->index]->hw_device_ctx = gcff_util.get_vaapi_ctx(encode_ctx[out_stream->index]->codec_id, encode_ctx[out_stream->index]->profile,
encode_ctx[out_stream->index]->width, encode_ctx[out_stream->index]->height);
if (encode_ctx[out_stream->index]->hw_device_ctx){
encode_ctx[out_stream->index]->pix_fmt = AV_PIX_FMT_VAAPI;
LWARN("Frame pix_fmt is " + std::to_string(frame->format));
if (frame && frame->format == AV_PIX_FMT_VAAPI && frame->hw_frames_ctx){
encode_ctx[out_stream->index]->hw_frames_ctx = av_buffer_ref(frame->hw_frames_ctx);
} else if (dec_ctx->pix_fmt == AV_PIX_FMT_VAAPI && dec_ctx->hw_frames_ctx){//this requires a decoded frame
encode_ctx[out_stream->index]->hw_frames_ctx = av_buffer_ref(dec_ctx->hw_frames_ctx);
} else {
//source is some unknown source, so we get a new va-api context
LWARN("Wrong pixel format provided for initilization");
}
}
} else if (using_v4l2 && dec_ctx->pix_fmt == AV_PIX_FMT_DRM_PRIME){
encode_ctx[out_stream->index]->pix_fmt = AV_PIX_FMT_DRM_PRIME;//if using V4L2 and the source was in DRM, keep using DRM
}
//if it fails we get the SW encoder
} else {
LWARN("Could not find video encoder");
return false;
}
} else {
LINFO("Unknown stream type");
return false;//not audio or video, can't encode it
}
if (output_format_context->oformat->flags & AVFMT_GLOBALHEADER){
encode_ctx[out_stream->index]->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
gcff_util.lock();
int ret = avcodec_open2(encode_ctx[out_stream->index], encoder, &opts);
gcff_util.unlock();
av_dict_free(&opts);
if (ret < 0) {
LERROR("Cannot open encoder for stream " + std::to_string(out_stream->index));
return false;
}
ret = avcodec_parameters_from_context(out_stream->codecpar, encode_ctx[out_stream->index]);
if (ret < 0) {
LERROR("Failed to copy encoder parameters to output stream " + std::to_string(out_stream->index));
return false;
}
out_stream->time_base = encode_ctx[out_stream->index]->time_base;
//get the profile info:
gen_codec_str(out_stream->index, out_stream->codecpar);
if (out_stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO){
guess_framerate(encode_ctx[out_stream->index]);
guess_framerate(dec_ctx);
guess_framerate(out_stream);
guess_framerate(in_stream);
LINFO("Framerate guessed is: " + std::to_string(video_framerate));
}
return true;
}
bool StreamWriter::write(const AVFrame *frame, const AVStream *in_stream){
int ret = 0;
ret = avcodec_send_frame(encode_ctx[stream_mapping[in_stream->index]], frame);
if (ret < 0){
LWARN("Error during encoding. Error code: " + std::string(av_err2str(ret)));
return false;
}
while (1) {
ret = avcodec_receive_packet(encode_ctx[stream_mapping[in_stream->index]], enc_pkt);
if (ret){
if (ret == AVERROR(EAGAIN)){
break;
}
LWARN("Error Receiving Packet");
break;
}
enc_pkt->stream_index = in_stream->index;//revert stream index because write will adjust this
bool write_ret = write(enc_pkt, in_stream);
av_packet_unref(enc_pkt);
if (!write_ret){
return false;
}
}
return true;
}
AVStream *StreamWriter::init_stream(const AVStream *in_stream){
if (!output_format_context){
if (!alloc_context()){
return NULL;
}
}
if (in_stream == NULL){
return NULL;
}
AVStream *out_stream = NULL;
AVCodecParameters *in_codecpar = in_stream->codecpar;
if (in_codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
in_codecpar->codec_type != AVMEDIA_TYPE_VIDEO) {
stream_mapping[in_stream->index] = -1;
return NULL;
}
stream_mapping[in_stream->index] = output_format_context->nb_streams;
//set the offset to -1, indicating unknown
stream_offset.push_back(-1);
last_dts.push_back(LONG_MIN);
out_stream = avformat_new_stream(output_format_context, NULL);
if (!out_stream) {
LERROR("Failed allocating output stream");
LERROR("Error occurred: " + std::string(av_err2str(AVERROR_UNKNOWN)));
stream_mapping[in_stream->index] = -1;
return NULL;
}
return out_stream;
}
bool StreamWriter::is_fragmented(void) const {
return segment_mode == SEGMENT_FMP4;
}
long long StreamWriter::frag_stream(void){
if (!is_fragmented()){
return -1;
}
//flush the buffers
av_interleaved_write_frame(output_format_context, NULL);
av_write_frame(output_format_context, NULL);
avio_flush(output_format_context->pb);
long long written = write_buf(true);
if (written < 0){
return -1;
}
long long pos = avio_tell(output_file);
return pos;
}
long long StreamWriter::get_init_len(void) const {
return init_len;
}
void StreamWriter::set_keyframe_callback(std::function<void(const AVPacket *pkt, StreamWriter &out)> cbk){
keyframe_cbk = cbk;
}
long long StreamWriter::write_buf(bool reopen){
if (output_file == NULL || output_format_context == NULL || output_format_context->pb == NULL){
LWARN("Attempted to write a buffer to a file when both don't exist");
return -1;
}
uint8_t *buf;
long long len;
len = avio_close_dyn_buf(output_format_context->pb, &buf);
avio_write(output_file, buf, len);
avio_flush(output_file);
if (init_seg == NULL){
init_seg = buf;
init_len = len;
} else {
av_free(buf);
}
if (reopen){
int error = avio_open_dyn_buf(&output_format_context->pb);
if (error < 0) {
LERROR("Could not open buffer");
LERROR("Error occurred: " + std::string(av_err2str(error)));
return -2;
}
} else {
output_format_context->pb = NULL;
}
return len;
}
long long StreamWriter::write_init(void){
if (init_seg == NULL || init_len < 0){
return -1;
}
if (init_len == 0){
return 0;
}
avio_write(output_file, init_seg, init_len);
return init_len;
}
void StreamWriter::interleave(PacketInterleavingBuf *buf){
if (buf->out->stream_index == 0){
buf->dts0 = buf->out->dts;
} else {
//convert to the stream 0 timebase
buf->dts0 = av_rescale_q_rnd(buf->out->dts,
output_format_context->streams[buf->out->stream_index]->time_base,
output_format_context->streams[0]->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
}
interleaved_dts[buf->out->stream_index] = buf->dts0;
//find the first buf where dts0 is > than ours, and insert jus before that
for (auto ibuf = interleaving_buf.begin(); ibuf != interleaving_buf.end(); ibuf++){
if ((*ibuf)->dts0 > buf->dts0){
interleaving_buf.insert(ibuf, buf);
return;
}
}
interleaving_buf.insert(interleaving_buf.end(), buf);
}
bool StreamWriter::fixup_duration_interleave(std::list<PacketInterleavingBuf*>::iterator itr){
auto in = *itr;
auto end_dts = in->out->dts + in->out->duration;
for (itr++; itr != interleaving_buf.end(); itr++){
if ((*itr)->out->stream_index == in->out->stream_index){
//found the previous packet
if (end_dts > (*itr)->out->dts){//our current DTS puts us past the next packet start
//log_packet(output_format_context, in->out, "Pre-fix");
auto target_duration = (*itr)->out->dts - in->out->dts;
if (target_duration > 0){
in->out->duration = target_duration;
}
//log_packet(output_format_context, in->out, "Post-fix");
return true;
} else {
return false;
}
}
}
return false;
}
bool StreamWriter::write_interleaved(void){
unsigned int stream_count = output_format_context->nb_streams;
//do not continue if we don't all streams
if (interleaved_dts.size() != stream_count){
if (interleaving_buf.size() > 100){
LWARN("Over 100 packets buffered and all streams not seen yet");
return false;
} else {
LDEBUG("Waiting for packet, interleaving_buf has " + std::to_string(interleaving_buf.size()));
return true;
}
}
//find the earilest DTS across all streams
long long last_dts = LLONG_MAX;
for (const auto dts : interleaved_dts){
if (dts.second < last_dts){
last_dts = dts.second;
}
}
bool ret = true;
for (auto ibuf = interleaving_buf.begin(); ibuf != interleaving_buf.end();){
if ((*ibuf)->dts0 <= last_dts && interleaving_buf.size() > interleave_queue_depth){
//fixup the PTS and DTS
try {
long track_dts = track_len_dts.at((*ibuf)->out->stream_index);//throws and we don't check
if ((*ibuf)->out->dts > track_dts){
long diff = (*ibuf)->out->dts - track_dts;
if (diff < (*ibuf)->out->duration){
//difference is less than a packet, shift DTS and PTS
(*ibuf)->out->dts -= diff;
(*ibuf)->out->pts -= diff;
} else {
LDEBUG("Excessive DTS gap (" + std::to_string(diff) + "), possible dropped packet");
}
}
} catch (std::out_of_range &e){
//track dts is not set (first run)
}
track_len_dts[(*ibuf)->out->stream_index] = (*ibuf)->out->dts + (*ibuf)->out->duration;
fixup_duration_interleave(ibuf);
ret &= write(*ibuf);
ibuf = interleaving_buf.erase(ibuf);
} else {
break;
}
}
return ret;
}
bool StreamWriter::gen_codec_str(const int stream, const AVCodecParameters *codec){
if (codec->codec_type == AVMEDIA_TYPE_AUDIO){
audio_stream_found = true;
} else if (codec->codec_type == AVMEDIA_TYPE_VIDEO){
video_stream_found = true;
//and copy the metadata
video_width = codec->width;
video_height = codec->height;
}
//extract the codec ID if available (much of this borrowed from ffmpeg/libavformat/hls.enc write_codec_attr())
if (codec->codec_id == AV_CODEC_ID_H264){
uint8_t *data = codec->extradata;
if (data && (data[0] | data[1] | data[2]) == 0 && data[3] == 1 && (data[4] & 0x1F) == 7) {
std::stringstream codec_id_builder;
codec_id_builder << "avc1.";
codec_id_builder << std::setfill('0') << std::setw(2) << std::hex << (unsigned int)data[5];
codec_id_builder << std::setfill('0') << std::setw(2) << std::hex << (unsigned int)data[6];
codec_id_builder << std::setfill('0') << std::setw(2) << std::hex << (unsigned int)data[7];
codec_str[stream] = codec_id_builder.str();
} else {
LWARN("Unknown h264 codec ID from encoder, going to make an uneducated guess");
codec_str[stream] = "avc1.640029";//just a random guess..should probably guess something closer...
}
} else if (codec->codec_id == AV_CODEC_ID_HEVC){
uint8_t *data = codec->extradata;
int profile = FF_PROFILE_UNKNOWN;
int level = FF_LEVEL_UNKNOWN;
if (codec->profile != FF_PROFILE_UNKNOWN){
profile = codec->profile;
}
if (codec->level != FF_LEVEL_UNKNOWN){
level = codec->level;
}
/* check the boundary of data which from current position is small than extradata_size */
while (data && (data - codec->extradata + 19) < codec->extradata_size) {
/* get HEVC SPS NAL and seek to profile_tier_level */
if (!(data[0] | data[1] | data[2]) && data[3] == 1 && ((data[4] & 0x7E) == 0x42)) {
uint8_t *rbsp_buf;
int remain_size = 0;
uint32_t rbsp_size = 0;
/* skip start code + nalu header */
data += 6;
/* process by reference General NAL unit syntax */
remain_size = codec->extradata_size - (data - codec->extradata);
rbsp_buf = nal_unit_extract_rbsp(data, remain_size, &rbsp_size);
if (!rbsp_buf){
break;
}
if (rbsp_size < 13) {
delete rbsp_buf;
break;
}
/* skip sps_video_parameter_set_id u(4),
* sps_max_sub_layers_minus1 u(3),
* and sps_temporal_id_nesting_flag u(1) */
profile = rbsp_buf[1] & 0x1f;
/* skip 8 + 8 + 32 + 4 + 43 + 1 bit */
level = rbsp_buf[12];
delete rbsp_buf;
break;
}
data++;
}
if (codec->codec_tag == MKTAG('h','v','c','1') &&
profile != FF_PROFILE_UNKNOWN &&
level != FF_LEVEL_UNKNOWN) {
codec_str[stream] = std::string(av_fourcc2str(codec->codec_tag)) + "." + std::to_string(profile) + ".4L" + std::to_string(level) + ".B01";
} else {
LWARN("Unknown h265 codec, making an uneducated guess");
codec_str[stream] = "hvc1.2.4.L150.B0";//just a random guess
}
} else if (codec->codec_id == AV_CODEC_ID_MP2) {
codec_str[stream] = "mp4a.40.33";
} else if (codec->codec_id == AV_CODEC_ID_MP3) {
codec_str[stream] = "mp4a.40.34";
} else if (codec->codec_id == AV_CODEC_ID_AAC) {
/* TODO : For HE-AAC, HE-AACv2, the last digit needs to be set to 5 and 29 respectively */
codec_str[stream] = "mp4a.40.2";
} else if (codec->codec_id == AV_CODEC_ID_AC3) {
codec_str[stream] = "ac-3";
} else if (codec->codec_id == AV_CODEC_ID_EAC3) {
codec_str[stream] = "ec-3";
} else {
LWARN("Unknown codec for stream " + std::to_string(stream));
return false;
}
if (codec_str.find(stream) != codec_str.end()){
LINFO("Codec for stream " + std::to_string(stream) + " - " + codec_str[stream]);
return true;
} else {
return false;
}
}
std::string StreamWriter::get_codec_str(void) const {
std::stringstream ss;
bool first = true;
for (const auto &str : codec_str){
if (!first){
ss << ",";
}
first = false;
ss << str.second;
}
return ss.str();
}
bool StreamWriter::have_video(void) const {
return video_stream_found;
}
bool StreamWriter::have_audio(void) const {
return audio_stream_found;
}
int StreamWriter::get_height(void) const {
return video_height;
}
int StreamWriter::get_width(void) const {
return video_width;
}
float StreamWriter::get_framerate(void) const {
return video_framerate;
}
//borrowed from ffmpeg/libavformat/avc.c
uint8_t *StreamWriter::nal_unit_extract_rbsp(const uint8_t *src, const uint32_t src_len, uint32_t *dst_len){
uint8_t *dst;
uint32_t i, len;
dst = new uint8_t[src_len + AV_INPUT_BUFFER_PADDING_SIZE];
if (!dst){
return NULL;
}
i = len = 0;
while (i + 2 < src_len){
if (!src[i] && !src[i + 1] && src[i + 2] == 3) {
dst[len++] = src[i++];
dst[len++] = src[i++];
i++; // remove emulation_prevention_three_byte
} else {
dst[len++] = src[i++];
}
}
while (i < src_len){
dst[len++] = src[i++];
}
memset(dst + len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
*dst_len = len;
return dst;
}
bool StreamWriter::guess_framerate(const AVStream *stream){
if (std::isfinite(video_framerate) && video_framerate > 0){
return true;//already valid
}
video_framerate = av_q2d(stream->avg_frame_rate);
if (!std::isfinite(video_framerate) || video_framerate < 0){
video_framerate = av_q2d(stream->r_frame_rate);
}
if (!std::isfinite(video_framerate) || video_framerate < 0){
video_framerate = 0;
return false;
} else {
return true;
}
}
bool StreamWriter::guess_framerate(const AVCodecContext* codec_ctx){
if (std::isfinite(video_framerate) && video_framerate > 0){
return true;//already valid
}
video_framerate = av_q2d(codec_ctx->framerate);
if (!std::isfinite(video_framerate) || video_framerate < 0){
video_framerate = 0;
return false;
} else {
return true;
}
}
bool StreamWriter::get_video_format(const AVFrame *frame, AVPixelFormat &pix_fmt, AVCodecID &codec_id, int &codec_profile) const {
const AVCodec *vencoder = get_vencoder(frame->width, frame->height, codec_id, codec_profile);
if (!vencoder || !vencoder->pix_fmts){
LWARN("Video Encoder has no pixel formats?");
pix_fmt = static_cast<AVPixelFormat>(frame->format);//I guess the encoder takes anything...see what this does
return false;
}
//FIXME: This is overly restrictive, our API should return all pix_fmts
pix_fmt = vencoder->pix_fmts[0];
return true;
}
const AVCodec* StreamWriter::get_vencoder(int width, int height, AVCodecID &codec_id, int &codec_profile) const {
const AVCodec *encoder = NULL;
if (cfg.get_value("encode-format-video") == "hevc"){
codec_id = AV_CODEC_ID_HEVC;
codec_profile = FF_PROFILE_HEVC_MAIN;
if ((cfg.get_value("video-encode-method") == "auto" || cfg.get_value("video-encode-method") == "vaapi") &&
gcff_util.have_vaapi(codec_id, codec_profile, width, height)){
encoder = avcodec_find_encoder_by_name("hevc_vaapi");
}
if (!encoder && ((cfg.get_value("video-encode-method") == "auto" || cfg.get_value("video-encode-method") == "vaapi") &&
gcff_util.have_v4l2(codec_id, codec_profile, width, height))){
encoder = avcodec_find_encoder_by_name("hevc_v4l2m2m");
}
if (!encoder){
encoder = avcodec_find_encoder(AV_CODEC_ID_HEVC);
}
}
if (!encoder) {//default or above option(s) failed
codec_id = AV_CODEC_ID_H264;
codec_profile = FF_PROFILE_H264_MAIN;
if ((cfg.get_value("video-encode-method") == "auto" || cfg.get_value("video-encode-method") == "vaapi") &&
gcff_util.have_vaapi(AV_CODEC_ID_H264, FF_PROFILE_H264_MAIN, width, height)){
encoder = avcodec_find_encoder_by_name("h264_vaapi");
}
if (!encoder && ((cfg.get_value("video-encode-method") == "auto" || cfg.get_value("video-encode-method") == "v4l2") &&
gcff_util.have_v4l2(AV_CODEC_ID_H264, FF_PROFILE_H264_MAIN, width, height))){
encoder = avcodec_find_encoder_by_name("h264_v4l2m2m");
}
if (!encoder){
encoder = avcodec_find_encoder(AV_CODEC_ID_H264);
}
}
return encoder;
}
const AVCodec* StreamWriter::get_vencoder(int width, int height) const {
AVCodecID codec_id;
int codec_profile;
return get_vencoder(width, height, codec_id, codec_profile);
}
unsigned int StreamWriter::get_bytes_written(void){
auto bytes = write_counter;
write_counter = 0;
return bytes;
}
PacketInterleavingBuf::PacketInterleavingBuf(const AVPacket *pkt){
in = av_packet_clone(pkt);
out = av_packet_clone(pkt);
video_keyframe = false;
}
PacketInterleavingBuf::~PacketInterleavingBuf(){
av_packet_free(&in);
av_packet_free(&out);
}
bool StreamWriter::validate_codec_tag(AVStream *stream){
stream->codecpar->codec_tag = av_codec_get_tag(output_format_context->oformat->codec_tag, stream->codecpar->codec_id);
return !stream->codecpar->codec_tag;
}
| 38,768
|
C++
|
.cpp
| 912
| 34.080044
| 167
| 0.59111
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,941
|
event_db.cpp
|
edman007_chiton/event_db.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "event_db.hpp"
static std::string algo_name = "db";
EventDB::EventDB(Config &cfg, Database &db, EventController &controller) : EventNotification(cfg, db, controller, algo_name) {
}
EventDB::~EventDB(){
}
bool EventDB::send_event(Event &e){
//save the thumbnail
long im_id = -1;
const AVFrame *frame = e.get_frame();
const struct timeval &e_time = e.get_timestamp();
const std::vector<float>& pos = e.get_position();
if (frame){
rect dims = {
.x = static_cast<int>(pos[0]), .y = static_cast<int>(pos[1]),
.w = static_cast<int>(pos[2] - pos[0]), .h= static_cast<int>(pos[3] - pos[1])
};
if (dims.x < 0){
dims.x = 0;
}
LWARN("x: " + std::to_string(dims.x) + " y: " + std::to_string(dims.y) +
" w: " + std::to_string(dims.w) + " h: " + std::to_string(dims.h));
std::string source = std::string(e.get_source());
if (!controller.get_img_util().write_frame_jpg(frame, source, &e_time, dims, &im_id)){
im_id = -1;
}
}
std::string ptime = std::to_string(Util::pack_time(e_time));
std::string sql = "INSERT INTO events (camera, img, source, starttime, x0, y0, x1, y1, score) VALUES ("
+ cfg.get_value("camera-id") + "," + std::to_string(im_id) + ",'" + db.escape(e.get_source()) + "'," + ptime + ","
+ std::to_string(pos[0]) + "," + std::to_string(pos[1]) + "," + std::to_string(pos[2]) + "," + std::to_string(pos[3]) + "," +
std::to_string(e.get_score()) + ")";
DatabaseResult* res = db.query(sql);
if (res){
delete res;
} else {
return false;
}
return true;
}
const std::string& EventDB::get_mod_name(void){
return algo_name;
}
| 2,671
|
C++
|
.cpp
| 64
| 36.765625
| 133
| 0.569888
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,942
|
motion_cvdetect.cpp
|
edman007_chiton/motion_cvdetect.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "motion_cvdetect.hpp"
#ifdef HAVE_OPENCV
#include "util.hpp"
#include <opencv2/imgproc.hpp>
#include <opencv2/video/tracking.hpp>
static const std::string algo_name = "cvdetect";
MotionCVDetect::MotionCVDetect(Config &cfg, Database &db, MotionController &controller) : MotionAlgo(cfg, db, controller, algo_name) {
masked_objects = NULL;
ocv = NULL;
ocvr = NULL;
min_dist = cfg.get_value_double("motion-cvdetect-dist");
if (min_dist <= 0 || min_dist > 10000){
min_dist = 150.0;
}
min_dist *= min_dist;//multiply it here to skip the sq root later
min_area = cfg.get_value_double("motion-cvdetect-area");
if (min_area < 0){
min_area = 150.0;
}
tracking_time_send = cfg.get_value_int("motion-cvdetect-tracking");
if (tracking_time_send < 1){
tracking_time_send = 1;
}
}
MotionCVDetect::~MotionCVDetect(){
masked_objects = NULL;
ocv = NULL;
ocvr = NULL;
}
bool MotionCVDetect::process_frame(const AVFrame *frame, bool video){
if (!video || !masked_objects){
return true;
}
try {
//find contours
//float thresh = 150.0;
//cv::Canny(masked_objects->get_masked(), canny, thresh, thresh*2 );
//cv::findContours(canny, contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
cv::findContours(masked_objects->get_masked(), contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
} catch (cv::Exception &e){
LWARN("MotionCVDetect::process_frame failed, error: " + e.msg);
return false;
}
std::vector<TargetRect> new_targets;
//compute the bounding rect for all
for (auto ctr : contours){
auto new_rect = cv::minAreaRect(ctr);
if (new_rect.size.area() < min_area){
continue;//toss the small spots
}
bool found_new = false;
for (auto &old_target : targets){
if (!old_target.is_valid()){
continue;
}
float x = old_target.get_rect().center.x - new_rect.center.x;
float y = old_target.get_rect().center.y - new_rect.center.y;
x *= x;
y *= y;
float dist = x + y;
if (dist < min_dist){
//too close, just replace this target with the new contour
new_targets.push_back(TargetRect(old_target, new_rect, frame));
old_target.mark_invalid();
found_new = true;
break;
}
}
if (!found_new){
new_targets.push_back(TargetRect(new_rect));
}
}
targets = std::move(new_targets);
if (targets.size() > 0){
LDEBUG("Tracking " + std::to_string(targets.size()) + " targets");
}
send_events();
display_objects();
return true;
}
bool MotionCVDetect::set_video_stream(const AVStream *stream, const AVCodecContext *codec) {
return true;
}
const std::string& MotionCVDetect::get_mod_name(void) {
return algo_name;
}
bool MotionCVDetect::init(void) {
ocv = static_cast<MotionOpenCV*>(controller.get_module_before("opencv", this));
ocvr = static_cast<MotionCVResize*>(controller.get_module_before("cvresize", this));
masked_objects = static_cast<MotionCVMask*>(controller.get_module_before("cvmask", this));
//the settings need to be scalled by the scale factor
if (ocvr){
float scale = ocvr->get_scale_ratio();
if (scale != 1){
scale *= scale;
min_dist *= scale;
min_area *= scale;
}
}
return true;
}
void MotionCVDetect::display_objects(void){
//ocv->get_UMat().copyTo(debug_view);
masked_objects->get_masked().copyTo(debug_view);
cv::RNG rng(12345);
for (auto &target : targets){
if (target.get_count() < 10){
continue;
}
cv::Scalar color = cv::Scalar( rng.uniform(0, 256), rng.uniform(0,256), rng.uniform(0,256) );
cv::Point2f vertices[4];
target.get_rect().points(vertices);
for ( int j = 0; j < 4; j++ ){
line(debug_view, vertices[j], vertices[(j+1)%4], color);
}
LDEBUG("Size: " + std::to_string(target.get_rect().size.area()));
}
}
const cv::UMat &MotionCVDetect::get_debug_view(void){
return debug_view;
}
void MotionCVDetect::send_events(void){
for (auto &target : targets){
if (target.get_count() == tracking_time_send){
Event &e = controller.get_event_controller().get_new_event();
if (!ocvr || ocvr->get_scale_ratio() == 1){
e.set_position(target);
} else {
//scale the target
TargetRect scaled_rect = TargetRect(target);
scaled_rect.scale(ocvr->get_scale_ratio());
e.set_position(scaled_rect);
}
struct timeval time;
controller.get_frame_timestamp(target.get_best_frame(), true, time);
e.set_frame(target.get_best_frame());
e.set_timestamp(time);
e.set_source(algo_name);
float score = target.get_best_rect().size.area();
float max_size = masked_objects->get_masked().cols*masked_objects->get_masked().rows;
score /= max_size;
score *= 100.0;
e.set_score(score);
controller.get_event_controller().send_event(e);
}
}
}
//HAVE_OPENCV
#endif
| 6,336
|
C++
|
.cpp
| 170
| 30.141176
| 134
| 0.591574
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,943
|
util.cpp
|
edman007_chiton/util.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "util.hpp"
#include <sys/time.h>
#include <syslog.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sstream>
thread_local std::string thread_name = "System";
thread_local int thread_cam_id = -1;
std::mutex Util::lock;
#ifdef DEBUG
unsigned int Util::log_level = CH_LOG_DEBUG;/* All Messages */
#else
unsigned int Util::log_level = CH_LOG_INFO;/* WARN and above */
#endif
bool Util::use_syslog = false;
//we store the color stuff so we are not accessing the config so often
//might be premature optimization, but meh
bool Util::use_color = false;
//color codes are mearly suggestions...the terminal decides them
int Util::color_map[5] = {5, 1, 3, 6, 2};
//these are used to track the log messages
std::map<int, std::deque<LogMsg>> Util::log_history;//a log of our messages
unsigned int Util::history_len = 50;
std::mutex Util::history_lock;
void Util::log_msg(const LOG_LEVEL lvl, const std::string& msg){
if (lvl >= log_level){
return;//drop any message above our current logging level
}
std::string prefix;
if (thread_name.length() > 0){
prefix = thread_name + ": ";
}
if (use_syslog){
int priority = LOG_DEBUG;
switch (lvl){
case CH_LOG_FATAL:
priority = LOG_CRIT;
break;
case CH_LOG_ERROR:
priority = LOG_ERR;
break;
case CH_LOG_WARN:
priority = LOG_WARNING;
break;
case CH_LOG_INFO:
priority = LOG_INFO;
break;
case CH_LOG_DEBUG:
priority = LOG_DEBUG;
break;
}
syslog(priority, "%s", (prefix + msg).c_str());
} else {
if (lvl == CH_LOG_ERROR || lvl == CH_LOG_FATAL){
lock.lock();
std::cerr << get_color_txt(lvl) << prefix << msg << std::endl;
lock.unlock();
} else {
lock.lock();
std::cout << get_color_txt(lvl) << prefix << msg << std::endl;
lock.unlock();
}
}
add_history(msg, lvl);
}
void Util::get_videotime(struct timeval &time){
gettimeofday(&time, NULL);
}
void Util::get_time_parts(const struct timeval &time, struct VideoDate &date){
struct tm out;
date.ms = time.tv_usec / 1000;
localtime_r(&time.tv_sec, &out);
//copy it into our format
date.year = out.tm_year + 1900;
date.month = out.tm_mon + 1;
date.day = out.tm_mday;
date.hour = out.tm_hour;
date.min = out.tm_min;
date.sec = out.tm_sec;
}
unsigned long long int Util::pack_time(const struct timeval &time){
unsigned long long int out;
out = time.tv_sec;
out *= 1000;
out += time.tv_usec / 1000;
return out;
}
void Util::unpack_time(const unsigned long long int packed_time, struct timeval &time){
time.tv_usec = (packed_time % 1000) * 1000;
time.tv_sec = packed_time / 1000;
}
void Util::compute_timestamp(const struct timeval &connect_time, struct timeval &out_time, long pts, AVRational &time_base){
double delta = av_q2d(time_base) * pts;
double usec = delta - ((long)delta);
usec *= 1000000;
out_time.tv_sec = connect_time.tv_sec + delta;
out_time.tv_usec = connect_time.tv_usec + usec;
if (out_time.tv_usec >= 1000000){
out_time.tv_usec -= 1000000;
out_time.tv_sec++;
}
}
void Util::set_log_level(unsigned int level){
log_level = level;
}
bool Util::enable_syslog(void){
openlog("chiton", LOG_PID, LOG_USER);
use_syslog = true;
return use_syslog;
}
bool Util::disable_syslog(void){
if (use_syslog){
closelog();
use_syslog = false;
}
return !use_syslog;
}
//reduces the priority of the calling thread
void Util::set_low_priority(void){
#ifdef HAVE_PTHREAD
sched_param sch;
int policy;
pthread_getschedparam(pthread_self(), &policy, &sch);
//set SCHED_IDLE and priority of 0
sch.sched_priority = 0;
policy = SCHED_IDLE;
if (pthread_setschedparam(pthread_self(), policy, &sch)){
LWARN("Could not reduce the scheduling priority");
}
#endif
#ifdef SYS_ioprio_set
//this is actually constants from the kernel source...glibc is missing them,
//we could include them, but I don't know if it's worth making that a dep for this
//source for this is $LINUX_SRC/include/linux/ioprio.h
const int IOPRIO_CLASS_SHIFT = 13;
enum {
IOPRIO_CLASS_NONE,
IOPRIO_CLASS_RT,
IOPRIO_CLASS_BE,
IOPRIO_CLASS_IDLE,
};
enum {
IOPRIO_WHO_PROCESS = 1,
IOPRIO_WHO_PGRP,
IOPRIO_WHO_USER,
};
//reduce IO priority
if (syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0, IOPRIO_CLASS_IDLE << IOPRIO_CLASS_SHIFT, 0)){
LWARN("Could not reduce the IO Priority");
}
#endif
}
AVDictionary* Util::get_dict_options(const std::string &fmt){
AVDictionary *dict = NULL;
if (fmt == ""){
return NULL;
}
int error;
if ((error = av_dict_parse_string(&dict, fmt.c_str(), "=", ":", 0))){
LERROR("Error Parsing ffmpeg options (" + fmt + "): " + std::string(av_err2str(error)));
av_dict_free(&dict);
return NULL;
}
return dict;
}
std::string Util::get_color_txt(enum LOG_LEVEL ll){
if (!use_color){
return "";
}
int color = color_map[ll];
std::stringstream ss;
if (color < 8){
ss << "\u001b[3" << std::to_string(color) << "m";
} else {
ss << "\u001b[38;5;" << std::to_string(color) << "m";
}
return ss.str();
}
void Util::reset_color(void){
lock.lock();
std::cout << "\u001b[0m";
lock.unlock();
}
void Util::load_colors(Config &cfg){
color_map[0] = cfg.get_value_int("log-color-fatal");
color_map[1] = cfg.get_value_int("log-color-error");
color_map[2] = cfg.get_value_int("log-color-warn");
color_map[3] = cfg.get_value_int("log-color-info");
color_map[4] = cfg.get_value_int("log-color-debug");
for (auto &c : color_map){
if (c < 1 || c > 255){
c = 1;
}
}
}
bool Util::enable_color(void){
use_color = true;
return use_color;
}
bool Util::disable_color(void){
if (use_color){
reset_color();
use_color = false;
}
return !use_color;
}
void Util::set_thread_name(int id, Config &cfg){
std::string name;
thread_cam_id = id;
if (id == -1){
name = "System";
} else if (cfg.get_value("display-name") == ""){
name = "Camera " + std::to_string(id);;
} else {
name = cfg.get_value("display-name");
}
int len = cfg.get_value_int("log-name-length");
if (len < 0){
len = 0;
}
thread_name = name.substr(0, len);
}
void Util::add_history(const std::string &msg, enum LOG_LEVEL lvl){
if (history_len == 0){
return;//no history recording, it's a no-op
}
history_lock.lock();
try {
auto &queue = log_history.at(thread_cam_id);
struct timeval time;
get_videotime(time);
queue.emplace(queue.end(), msg, lvl, time);
//delete any excess
while (queue.size() > history_len){
queue.pop_front();
}
} catch (std::out_of_range &e){
//add the queue and do it again
log_history.emplace(std::make_pair(thread_cam_id, std::deque<LogMsg>()));
history_lock.unlock();
return add_history(msg, lvl);
}
history_lock.unlock();
}
void Util::set_history_len(int len){
history_len = len;
if (history_len < 0){
history_len = 0;
}
}
bool Util::get_history(int cam, std::vector<LogMsg> &hist){
history_lock.lock();
bool ret = false;
try {
auto &queue = log_history.at(cam);
hist.clear();
hist.reserve(queue.size());
for (auto &msg : queue){
hist.emplace_back(msg);
}
ret = true;
} catch (std::out_of_range &e){
//nothing, we return false
}
history_lock.unlock();
return ret;
}
| 8,939
|
C++
|
.cpp
| 289
| 25.581315
| 124
| 0.601604
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,944
|
json_encoder.cpp
|
edman007_chiton/json_encoder.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "json_encoder.hpp"
#include <sstream>
JSONEncoder::JSONEncoder(){
valid = false;
}
JSONEncoder::~JSONEncoder(){
//nothing
}
bool JSONEncoder::add(const std::string key, int val){
data[key] = std::to_string(val);
valid = false;
return true;
}
bool JSONEncoder::add(const std::string key, unsigned int val){
data[key] = std::to_string(val);
valid = false;
return true;
}
bool JSONEncoder::add(const std::string key, time_t val){
add(key, (unsigned int)val);//should this be unsigned long?
return true;
}
bool JSONEncoder::add(const std::string key, double val){
data[key] = std::to_string(val);
valid = false;
return true;
}
bool JSONEncoder::add(const std::string key, bool val){
if (val){
data[key] = "true";
} else {
data[key] = "false";
}
valid = false;
return true;
}
bool JSONEncoder::add(const std::string key, const char* val){
std::string str = std::string(val);
return add(key, str);
}
bool JSONEncoder::add(const std::string key, const std::string &val){
//we only bother escaping " and \ as they affect formatting
const std::string esc_chars = "\"\\";//"\"\\\b\f\n\r\t";
std::ostringstream str;
str << '"';
size_t pos = 0;//the start position
do {
//find the next escapable character
size_t end = val.find_first_of(esc_chars, pos);
if (end == std::string::npos){
//the end
str << val.substr(pos);
pos = end;
} else {
str << val.substr(pos, end - pos);
//escape this character
switch (val[end]){
case '"':
str << "\\\"";
break;
case '\\':
str << "\\\\";
break;
default:
str << val[end];//error..should never get here
}
pos = end+1;
}
} while (pos < val.length());
str << '"';
data[key] = str.str();
valid = false;
return true;
}
bool JSONEncoder::add(const std::string key, JSONEncoder &val){
data[key] = val.str();
valid = false;
return true;
}
const std::string& JSONEncoder::str(void){
if (valid){
return output;
}
std::stringstream s;
s << "{";
for (auto it = data.begin(); it != data.end(); it++) {
s << "\"" << it->first << "\":" << it->second;
s << ",";
}
//delete last , and replace with }
s.seekp(-1, std::ios_base::end);
s << "}";
output = s.str();
return output;
}
| 3,492
|
C++
|
.cpp
| 116
| 24.698276
| 75
| 0.561143
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,945
|
camera.cpp
|
edman007_chiton/camera.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "camera.hpp"
#include "util.hpp"
#include "image_util.hpp"
#include "filter.hpp"
#include "motion_controller.hpp"
#include "system_controller.hpp"
Camera::Camera(SystemController &sys, int camera) : sys(sys), id(camera), cfg(sys.get_sys_cfg()), db(sys.get_db()),
stream(cfg), fm(sys, cfg), status(id) {
//load the config
load_cfg();
shutdown = false;
alive = true;
watchdog = false;
startup = true;
pkt = av_packet_alloc();
//variables for cutting files...
last_cut = av_make_q(0, 1);
last_cut_file = av_make_q(0, 1);
last_cut_byte = 0;
int seconds_per_segment_raw = cfg.get_value_int("seconds-per-segment");
if (seconds_per_segment_raw <= 0){
LWARN("seconds-per-segment was invalid");
seconds_per_segment_raw = DEFAULT_SECONDS_PER_SEGMENT;
}
seconds_per_segment = av_make_q(seconds_per_segment_raw, 1);
int seconds_per_file_raw = cfg.get_value_int("seconds-per-file");
if (seconds_per_file_raw <= 0){
LWARN("seconds-per-file was invalid");
seconds_per_file_raw = 60*seconds_per_segment_raw;
}
seconds_per_file = av_make_q(seconds_per_file_raw, 1);
}
Camera::~Camera(){
av_packet_free(&pkt);
}
void Camera::load_cfg(void){
cfg.load_camera_config(id, db);
}
void Camera::run(void){
Util::set_thread_name(id, cfg);
LINFO("Camera " + std::to_string(id) + " starting...");
if (!stream.connect()){
alive = false;
startup = false;
return;
}
watchdog = true;
startup = false;
LINFO("Camera " + std::to_string(id) + " connected...");
const struct timeval& starttime = stream.get_start_time();
std::string out_filename = fm.get_next_path(file_id, id, starttime);
status.set_start_time(starttime.tv_sec);
StreamWriter out = StreamWriter(cfg);
ImageUtil img(sys, cfg);
MotionController motion(db, cfg, stream, img);
out.change_path(out_filename);
out.set_keyframe_callback(std::bind(&Camera::cut_video, this, std::placeholders::_1, std::placeholders::_2));
//look at the stream and settings and see what needs encoding and decoding
bool encode_video = get_vencode();
bool encode_audio = get_aencode();
//determine if motion detection wants to decode
bool decode_video = encode_video || motion.decode_video();
bool decode_audio = encode_audio || motion.decode_audio();
LINFO("Decode <A/V> [" + std::to_string(decode_audio) + "/" + std::to_string(decode_video) +
"] - Encode<A/V> [" + std::to_string(encode_audio) + "/" + std::to_string(encode_video) + "]");
//allocate a frame (we only allocate when we want to decode, an unallocated frame means we skip decoding)
AVFrame *frame = NULL, *filtered_frame = NULL;
if (decode_video || decode_audio){
frame = av_frame_alloc();
if (!frame){
LWARN("Failed to allocate frame");
frame = NULL;
}
filtered_frame = av_frame_alloc();
if (!filtered_frame){
LWARN("Failed to allocate filtered frame");
filtered_frame = NULL;
}
}
Filter vfilter(cfg);//video filter, only initilized when encoding
if (encode_video){
LDEBUG("Charging Decoder");
stream.charge_video_decoder();
watchdog = true;
AVStream *vstream = stream.get_video_stream();
if (!vstream){
LERROR("No Video stream found");
return;
}
//init the filter with the decoded video frame
stream.peek_decoded_vframe(frame);
AVCodecID codec_id;
int codec_profile;
AVPixelFormat pix_fmt;
out.get_video_format(frame, pix_fmt, codec_id, codec_profile);
vfilter.set_target_fmt(pix_fmt, codec_id, codec_profile);
vfilter.set_source_time_base(vstream->time_base);
vfilter.send_frame(frame);
av_frame_unref(frame);
vfilter.peek_frame(filtered_frame);
AVCodecContext *vctx = stream.get_codec_context(vstream);
bool encoded_ret = out.add_encoded_stream(vstream, vctx, filtered_frame);
av_frame_unref(filtered_frame);
if (encoded_ret){
LINFO("Camera " + std::to_string(id) + " transcoding video stream");
} else {
LERROR("Camera " + std::to_string(id) + " transcoding video stream failed!");
return;
}
} else {
if (out.add_stream(stream.get_video_stream())){
LINFO("Camera " + std::to_string(id) + " copying video stream");
} else {
LERROR("Camera " + std::to_string(id) + " copying video stream failed!");
return;
}
}
if (encode_audio){
AVStream *astream = stream.get_audio_stream();
AVCodecContext *actx = stream.get_codec_context(astream);
if (out.add_encoded_stream(astream, actx)){
LINFO("Camera " + std::to_string(id) + " transcoding audio stream");
} else {
LERROR("Camera " + std::to_string(id) + " transcoding audio stream failed!");
return;
}
} else if(cfg.get_value("encode-format-audio") != "none") {
if (out.add_stream(stream.get_audio_stream())){
LINFO("Camera " + std::to_string(id) + " copying audio stream");
} else {
LINFO("Camera " + std::to_string(id) + " copying audio stream failed!");
}
}
out.open();
bool valid_keyframe = false;
//used for calculating shutdown time for the last segment
long last_pts = 0;
long last_stream_index = 0;
bool failed = false;
int frame_cnt = 0;
motion.set_streams();
while (!shutdown && !failed && stream.get_next_frame(pkt)){
watchdog = true;
last_pts = pkt->pts;
last_stream_index = pkt->stream_index;
frame_cnt++;
status.add_bytes_read(pkt->size);
//we skip processing until we get a video keyframe
if (valid_keyframe || (pkt->flags & AV_PKT_FLAG_KEY && stream.is_video(pkt))){
valid_keyframe = true;
} else {
LINFO("Dropping packets before first keyframe");
stream.unref_frame(pkt);
continue;
}
//decode the packets
if (frame && stream.is_video(pkt) && decode_video){
if (stream.decode_packet(pkt)){
while (!failed && stream.get_decoded_frame(pkt->stream_index, frame)){
//LDEBUG("Decoded Video Frame");
bool skipped = false;
motion.process_frame(pkt->stream_index, frame, skipped);
if (skipped) {
status.add_dropped_frame();
}
if (encode_video){
//Filter the frame before encoding
if (vfilter.send_frame(frame)){
while (!failed && vfilter.get_frame(filtered_frame)){
/*
if (frame_cnt == 10){//debug stuff
std::string debug_frame_name = "debug_frame";
img.write_frame_jpg(filtered_frame, debug_frame_name);
LINFO("Wrote " + debug_frame_name);
}
*/
if (!out.write(filtered_frame, stream.get_stream(pkt))){
LERROR("Error Encoding Video!");
failed = true;//error encoding
}
av_frame_unref(filtered_frame);
}
} else {
LERROR("Failed to send frame to video filter");
stream.unref_frame(pkt);
failed = true;
}
}
}
}
if (!encode_video){
if (!out.write(pkt, stream.get_stream(pkt))){//log it
LERROR("Error writing copied video packet");
failed = true;
}
}
} else if (frame && stream.is_audio(pkt) && decode_audio){
if (stream.decode_packet(pkt)){
while (!failed && stream.get_decoded_frame(pkt->stream_index, frame)){
//LDEBUG("Decoded Audio Frame");
bool skipped = false;
motion.process_frame(pkt->stream_index, frame, skipped);
if (skipped){
status.add_dropped_frame();
}
if (encode_audio){
if (!out.write(frame, stream.get_stream(pkt))){
stream.unref_frame(pkt);
LERROR("Error Encoding Audio!");
failed = true;
}
}
}
}
if (!encode_audio){
if (!out.write(pkt, stream.get_stream(pkt))){//log it
stream.unref_frame(pkt);
LERROR("Error writing copied audio packet");
failed = true;
}
}
} else {
//this packet is being copied...
if (!out.write(pkt, stream.get_stream(pkt))){//log it
LERROR("Error writing packet!");
failed = true;
}
}
status.add_bytes_written(out.get_bytes_written());//log the file size written
stream.unref_frame(pkt);
}
LINFO("Camera " + std::to_string(id)+ " is exiting");
struct timeval end;
Util::compute_timestamp(stream.get_start_time(), end, last_pts, stream.get_format_context()->streams[last_stream_index]->time_base);
long long size = out.close();
fm.update_file_metadata(file_id, end, size, out, last_cut_byte);
if (frame){
av_frame_free(&frame);
frame = NULL;
}
if (filtered_frame){
av_frame_free(&filtered_frame);
filtered_frame = NULL;
}
alive = false;
}
void Camera::stop(void){
shutdown = true;
}
bool Camera::ping(void){
return !watchdog.exchange(false) || !alive;
}
int Camera::get_id(void){
return id;
}
bool Camera::in_startup(void){
return startup && alive;
}
std::thread::id Camera::get_thread_id(void){
return thread.get_id();
}
void Camera::cut_video(const AVPacket *cut_pkt, StreamWriter &out){
if (cut_pkt->flags & AV_PKT_FLAG_KEY && stream.is_video(cut_pkt)){
//calculate the seconds:
AVRational sec_raw = av_mul_q(av_make_q(cut_pkt->dts, 1), stream.get_format_context()->streams[cut_pkt->stream_index]->time_base);//current time..
AVRational sec = av_sub_q(sec_raw, last_cut);
if (av_cmp_q(sec, seconds_per_segment) == 1 || (sec.num < 0 && last_cut.num > 0)){
//cutting the video
struct timeval start;
stream.timestamp(cut_pkt, start);
AVRational file_seconds = av_sub_q(sec_raw, last_cut_file);
if (out.is_fragmented() && sec.num >= 0 && av_cmp_q(file_seconds, seconds_per_file) == -1){
LDEBUG("Fragging Segment");
//we just fragment the file
long long size = out.change_path("");
if (last_cut_byte == 0 && out.get_init_len() > 0){
last_cut_byte = out.get_init_len();
}
fm.update_file_metadata(file_id, start, size, out, last_cut_byte);
last_cut_byte = size;
fm.get_next_path(file_id, id, start, true);
} else {
LDEBUG("Cutting File");
//copy the previous metadata
auto old_id = file_id;
auto old_init_len = out.get_init_len();
auto end = start;
if (sec.num < 0){
//this will cause a discontinuity which will be picked up and cause it to play correctly
start.tv_usec += 1000;
}
std::string out_filename = fm.get_next_path(file_id, id, start);
long long size = out.change_path(out_filename);;//apply new filename, and get length of old file
fm.update_file_metadata(old_id, end, size, out, last_cut_byte, old_init_len);
last_cut_byte = 0;
last_cut_file = av_mul_q(av_make_q(cut_pkt->dts, 1), stream.get_format_context()->streams[cut_pkt->stream_index]->time_base);
}
//save out this position
last_cut = av_mul_q(av_make_q(cut_pkt->dts, 1), stream.get_format_context()->streams[cut_pkt->stream_index]->time_base);
}
}
}
bool Camera::get_vencode(void){
AVStream *video_stream = stream.get_video_stream();
if (video_stream == NULL){
LERROR("Camera " + std::to_string(id) + " has no usable video, this will probably not work");
return false;
}
const std::string &user_opt = cfg.get_value("encode-format-video");
if (user_opt == "h264" || user_opt == "hevc"){
return true;//these force encoding
} else {
if (user_opt != "copy"){
LWARN("encode-format-video is '" + user_opt + "' which is not valid, on camera " + std::to_string(id));
}
if (video_stream->codecpar->codec_id == AV_CODEC_ID_H264 || video_stream->codecpar->codec_id == AV_CODEC_ID_HEVC){
return false;
} else {
LINFO("Transcoding audio because camera provided unsupported format");
return true;//there is video, but it's not HLS compatible (MJPEG or something?)
}
}
}
bool Camera::get_aencode(void){
const std::string &user_opt = cfg.get_value("encode-format-audio");
if (user_opt == "none"){
LINFO("encode-format-audio is 'none', skipping audio");
return false;
}
AVStream *audio_stream = stream.get_audio_stream();
if (audio_stream == NULL){
LINFO("Camera " + std::to_string(id) + " has no usable audio");
return false;
}
if (user_opt == "aac" || user_opt == "ac3"){
return true;//these force encoding
} else {
if (user_opt != "copy"){
LWARN("encode-format-audio is '" + user_opt + "' which is not valid, on camera " + std::to_string(id));
}
if (audio_stream->codecpar->codec_id == AV_CODEC_ID_AAC || audio_stream->codecpar->codec_id == AV_CODEC_ID_AC3){
return false;
} else {
LINFO("Transcoding audio because camera provided unsupported format");
return true;//there is audio, but it's not HLS compatible
}
}
}
void Camera::start(void){
thread = std::thread(&Camera::run, this);//start it
}
void Camera::join(void){
stop();//just in case we forgot
thread.join();
}
CameraStatus Camera::get_status(void){
return status;//this is threaded, but the CameraStatus object handles it
}
| 16,179
|
C++
|
.cpp
| 379
| 31.978892
| 154
| 0.549524
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,946
|
main.cpp
|
edman007_chiton/main.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "main.hpp"
#include "system_controller.hpp"
#include "util.hpp"
#include "chiton_config.hpp"
#include <unistd.h>
#include <stdlib.h>
#include <csignal>
#include <sys/types.h>
#include <pwd.h>
#include <fstream>
#include <iostream>
static int exit_count = 0;//multiple exit requests will kill the application with this
static SystemController* global_sys_controller = NULL;
void shutdown_signal(int sig){
if (global_sys_controller){
global_sys_controller->request_exit();
}
exit_count++;
if (exit_count > 2){
std::exit(SYS_EXIT_SIG_SHUTDOWN);
}
}
void reload_signal(int sig){
if (global_sys_controller){
global_sys_controller->request_reload();
}
}
//fork to the background (returns false if fork failed or this is the parent process)
bool fork_background(void){
pid_t pid = fork();
if (pid < 0){
LFATAL("Failed to fork");
return false;
}
if (pid != 0){
return false;
}
pid_t sid = setsid();
if (sid < 0){
LFATAL("Failed to setsid()");
return false;
}
if (chdir("/")){
LWARN("chdir / failed");
}
//Close stdin. stdout and stderr
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
return true;
}
bool drop_privs(const std::string& username){
if (getuid() != 0){
LFATAL("Cannot drop privleges because you are not root!");
return false;
}
struct passwd* user = getpwnam(username.c_str());
if (user == NULL){
LFATAL("Could not find user " + username);
return false;
}
if (setgid(user->pw_gid)){
LFATAL("Could not switch group " + std::to_string(user->pw_gid) + ", " + strerror(errno));
return false;
}
if (setuid(user->pw_uid)){
LFATAL("Could not switch user");
return false;
}
return true;
}
//write the pid to a file
bool write_pid(const std::string& path){
pid_t pid = getpid();
std::ofstream out;
out.open(path, std::ofstream::out | std::ofstream::trunc);
if (out.rdstate() & std::ifstream::failbit){
LWARN("Could not open pid file: " + path);
}
out << pid;
out.close();
return true;
}
//this reads the arguments, writes the Config object for received parameters
void process_args(Config& arg_cfg, int argc, char **argv){
//any system wide defaults...these are build-time defaults
arg_cfg.set_value("cfg-path", SYSCFGPATH);
arg_cfg.set_value("log-color-enabled", "0");//CLI option is disabled by default, against the default setting
arg_cfg.set_value("verbosity", "");//we set it to this to suppress the default value, the default is taken after loading the cfg
char options[] = "c:vVdqsp:fP:l";//update man/chiton.1 if you touch this!
int opt;
while ((opt = getopt(argc, argv, options)) != -1){
switch (opt) {
case 'c':
arg_cfg.set_value("cfg-path", optarg);
break;
case 'v':
arg_cfg.set_value("verbosity", "3");
break;
case 'V':
arg_cfg.set_value("verbosity", "4");
break;
case 'd':
arg_cfg.set_value("verbosity", "5");
break;
case 'q':
arg_cfg.set_value("verbosity", "0");
break;
case 's':
Util::enable_syslog();
break;
case 'p':
arg_cfg.set_value("pid-file", optarg);
break;
case 'f':
arg_cfg.set_value("fork", "1");
Util::enable_syslog();
break;
case 'P':
arg_cfg.set_value("privs-user", optarg);
break;
case 'l':
arg_cfg.set_value("log-color-enabled", "1");
Util::enable_color();
break;
}
}
}
int main (int argc, char **argv){
Config args;
process_args(args, argc, argv);
if (args.get_value("privs-user") != ""){
if (!drop_privs(args.get_value("privs-user"))){
return SYS_EXIT_PRIVS_ERROR;//exit
}
}
if (args.get_value_int("fork")){
if (!fork_background()){
return SYS_EXIT_SUCCESS;//exit!
}
}
if (args.get_value("pid-file") != ""){
write_pid(args.get_value("pid-file"));
}
if (args.get_value("verbosity") != ""){
Util::set_log_level(args.get_value_int("verbosity"));
}
LWARN("Starting Chiton...");
LWARN(std::string("\tVersion ") + BUILD_VERSION);
LWARN(std::string("\tBuilt ") + BUILD_DATE);
Util::set_thread_name(-1, args);
gcff_util.load_ffmpeg();
//load the signal handlers
std::signal(SIGINT, shutdown_signal);
std::signal(SIGHUP, reload_signal);
SystemController controller(args);
global_sys_controller = &controller;
int ret = controller.run();
gcff_util.free_hw();
Util::disable_syslog();//does nothing if it's not enabled
Util::disable_color();
return ret;
}
| 6,035
|
C++
|
.cpp
| 184
| 26.11413
| 132
| 0.576943
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,947
|
image_util.cpp
|
edman007_chiton/image_util.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2021-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "image_util.hpp"
#include "util.hpp"
#include "file_manager.hpp"
#include "filter.hpp"
#include "system_controller.hpp"
ImageUtil::ImageUtil(SystemController &sys, Config &cfg) : sys(sys), db(sys.get_db()), cfg(cfg) {
codec_id = AV_CODEC_ID_NONE;
codec_profile = FF_PROFILE_UNKNOWN;
pkt = av_packet_alloc();
}
ImageUtil::~ImageUtil(){
av_packet_free(&pkt);
}
void ImageUtil::set_profile(AVCodecID id, int profile){
codec_id = id;
codec_profile = profile;
}
bool ImageUtil::write_frame_jpg(const AVFrame *frame, std::string &name, const struct timeval *start_time /* = NULL */, rect src/* = {-1, -1, 0, 0}*/, long *file_id/* = NULL*/){
LDEBUG("Writing JPEG");
//check if it's valid
if (!frame){
LWARN("Cannot write frame out as image, invalid format");
return false;
}
const AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG);
if (!codec) {
LWARN("Cannot find MJPEG encoder!");
return false;
}
AVFrame *cropped_frame = NULL;
if (format_supported(frame, codec)){
LDEBUG("Format is supported" + std::to_string(frame->format));
cropped_frame = apply_rect(frame, src);
} else {
//run it through a single loop of the filter
LDEBUG("Filtering prior to writing");
Filter flt(cfg);
flt.set_target_fmt(get_pix_mpjeg_fmt(codec->pix_fmts), AV_CODEC_ID_MJPEG, FF_PROFILE_MJPEG_HUFFMAN_BASELINE_DCT);
flt.set_source_time_base({1, 1});//I don't think it actually matters...
flt.set_source_codec(codec_id, codec_profile);
flt.send_frame(frame);
AVFrame *filtered_frame = av_frame_alloc();
flt.get_frame(filtered_frame);
cropped_frame = apply_rect(filtered_frame, src);
av_frame_free(&filtered_frame);
}
if (!cropped_frame){
LWARN("Failed to get cropped frame, not writing image");
return false;
}
AVCodecContext* c = avcodec_alloc_context3(codec);
if (!c) {
LWARN("Could not allocate video codec context");
return false;
}
//should do avcodec_parameters_to_context or something?
c->bit_rate = 400000;
c->width = cropped_frame->width - cropped_frame->crop_left - cropped_frame->crop_right;
c->height = cropped_frame->height - cropped_frame->crop_top - cropped_frame->crop_bottom;
c->time_base = (AVRational){1,1};
c->pix_fmt = static_cast<enum AVPixelFormat>(cropped_frame->format);
c->sample_aspect_ratio = frame->sample_aspect_ratio;
c->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;//new ffmpeg complains about our YUV range, this makes it happy enough
LINFO("Exporting JPEG " + std::to_string(c->width) + "x" + std::to_string(c->height));
gcff_util.lock();
if (avcodec_open2(c, codec, NULL) < 0){
gcff_util.unlock();
avcodec_free_context(&c);
LWARN("Failed to open MJPEG codec");
return false;
}
gcff_util.unlock();
int ret = avcodec_send_frame(c, cropped_frame);
if (ret){
//failed...free and exit
LWARN("Failed to Send Frame for encoding");
avcodec_free_context(&c);
av_packet_unref(pkt);
av_frame_free(&cropped_frame);
return false;
}
ret = avcodec_receive_packet(c, pkt);
avcodec_free_context(&c);
av_frame_free(&cropped_frame);
if (ret){
LWARN("Failed to receive decoded frame");
//failed...free and exit
av_packet_unref(pkt);
return false;
}
//write out the packet
FileManager fm(sys, cfg);
std::string path;
bool success = false;
if (fm.get_image_path(path, name, ".jpg", start_time, file_id)){
std::ofstream out_s = fm.get_fstream_write(name, path);
LWARN("Writing to " + name);
if (out_s.is_open()){
out_s.write(reinterpret_cast<char*>(pkt->data), pkt->size);
success = out_s.good();
out_s.close();
} else {
LWARN("Couldn't open JPG");
}
} else {
LWARN("Failed to get image path");
}
av_packet_unref(pkt);
return success;
}
bool ImageUtil::write_frame_png(const AVFrame *frame, std::string &name, const struct timeval *start_time /* = NULL */, rect src/* = {-1, -1, 0, 0}*/, long *file_id/* = NULL*/){
LWARN("Can't write out PNGs");
return false;
}
AVFrame* ImageUtil::apply_rect(const AVFrame *frame, rect &src){
//copy the frame
AVFrame* out = av_frame_clone(frame);
if (!out){
LWARN("av_frame_clone() failed");
return NULL;
}
//adjust rect and apply if x is not negative
if (src.x >= 0){
//correct any numbers
if (static_cast<unsigned int>(src.x) < frame->crop_left){
src.x = frame->crop_left;
}
if (static_cast<unsigned int>(src.y) < frame->crop_bottom){
src.y = frame->crop_bottom;
}
if (static_cast<unsigned int>(src.w) > (frame->width - src.x - frame->crop_right)){
src.w = frame->width - src.x - frame->crop_right;
}
if (static_cast<unsigned int>(src.h) > (frame->height - src.y - frame->crop_top)){
src.h = frame->height - src.y - frame->crop_top;
}
//and apply the new numbers
out->crop_left = src.x;
out->crop_top = src.y;
out->crop_right = out->width - out->crop_left - src.w;
out->crop_bottom = out->height - out->crop_top - src.h;
if (av_frame_apply_cropping(out, AV_FRAME_CROP_UNALIGNED) < 0){
LWARN("av_frame_apply_cropping returned an error");
}
}
return out;
}
bool ImageUtil::format_supported(const AVFrame *frame, const AVCodec *codec){
if (!codec->pix_fmts){
return true;//is this right? it's actually unknown...but I guess the filter won't help
}
for (const enum AVPixelFormat *p = codec->pix_fmts; *p != AV_PIX_FMT_NONE; p++){
if (*p == static_cast<const enum AVPixelFormat>(frame->format)){
return true;
}
}
return false;
}
AVPixelFormat ImageUtil::get_pix_mpjeg_fmt(const AVPixelFormat *pix_list){
for (int i = 0; pix_list[i] != AV_PIX_FMT_NONE; i++){
//switch is based on libswscale depracated pix format check for jpeg in utils.c
switch (pix_list[i]) {
//these are deprecated
case AV_PIX_FMT_YUVJ420P:
case AV_PIX_FMT_YUVJ411P:
case AV_PIX_FMT_YUVJ422P:
case AV_PIX_FMT_YUVJ444P:
case AV_PIX_FMT_YUVJ440P:
continue;
default:
return pix_list[i];
}
}
return pix_list[0];//all of them were deprecated, return the first
}
| 7,604
|
C++
|
.cpp
| 196
| 32.438776
| 178
| 0.61081
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,948
|
motion_cvbackground.cpp
|
edman007_chiton/motion_cvbackground.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "motion_cvbackground.hpp"
#ifdef HAVE_OPENCV
#include "util.hpp"
#include <opencv2/imgproc.hpp>
static const std::string algo_name = "cvbackground";
MotionCVBackground::MotionCVBackground(Config &cfg, Database &db, MotionController &controller) : MotionAlgo(cfg, db, controller, algo_name) {
ocvr = NULL;
tau = cfg.get_value_double("motion-cvbackground-tau");
if (tau < 0 || tau > 1){
tau = 0.01;
}
}
MotionCVBackground::~MotionCVBackground(){
ocvr = NULL;//we don't own it
}
bool MotionCVBackground::process_frame(const AVFrame *frame, bool video){
if (!video){
return true;
}
if (!ocvr){
return false;
}
try {
//always do the math in CV_16U for extra precision
if (avg.empty()){
ocvr->get_UMat().convertTo(avg, CV_16U, 256.0);
ocvr->get_UMat().copyTo(low_res);
} else {
//compute the frame average
cv::UMat buf16;
ocvr->get_UMat().convertTo(buf16, CV_16U, 256.0);
cv::addWeighted(avg, 1-tau, buf16, tau, 0, avg);
avg.convertTo(low_res, CV_8U, 1.0/256.0);
}
} catch (cv::Exception &e){
LWARN("MotionCVBackground::process_frame failed, error: " + e.msg);
return false;
}
return true;
}
bool MotionCVBackground::set_video_stream(const AVStream *stream, const AVCodecContext *codec) {
return true;
}
const std::string& MotionCVBackground::get_mod_name(void){
return algo_name;
}
bool MotionCVBackground::init(void) {
ocvr = static_cast<MotionCVResize*>(controller.get_module_before("cvresize", this));
return true;
}
const cv::UMat MotionCVBackground::get_background(void){
return low_res;
}
//HAVE_OPENCV
#endif
| 2,667
|
C++
|
.cpp
| 76
| 30.671053
| 142
| 0.634354
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,949
|
event_console.cpp
|
edman007_chiton/event_console.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "event_console.hpp"
#include <sstream>
#include <ctime>
static std::string algo_name = "console";
EventConsole::EventConsole(Config &cfg, Database &db, EventController &controller) : EventNotification(cfg, db, controller, algo_name){
}
EventConsole::~EventConsole(){
}
bool EventConsole::send_event(Event &e){
std::ostringstream s;
s << "EVENT: " << e.get_source() << " @ \"";
const struct timeval &etime = e.get_timestamp();
struct tm real_time;
localtime_r(&etime.tv_sec, &real_time);
const int date_len = 64;
char date_str[date_len];
size_t ret = strftime(date_str, date_len - 1, "%c", &real_time);
if (ret > 0){
s << date_str << "";
} else {
s << "??";
}
s << "\", position: ";
const std::vector<float>& pos = e.get_position();
s << pos[0] << "x" << pos[1] << "-" << pos[2] << "x" << pos[3];
s << ", score: " << e.get_score();
LINFO(s.str());
return true;
}
const std::string& EventConsole::get_mod_name(void){
return algo_name;
}
| 1,948
|
C++
|
.cpp
| 53
| 33.54717
| 135
| 0.600212
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,950
|
stream_unwrap.cpp
|
edman007_chiton/stream_unwrap.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "stream_unwrap.hpp"
#include "util.hpp"
#include "chiton_ffmpeg.hpp"
StreamUnwrap::StreamUnwrap(Config& cfg) : cfg(cfg) {
input_format_context = NULL;
max_sync_offset = cfg.get_value_int("max-sync-offset");
timeshift_mean_delay = 0;
timeshift_mean_duration = 0;
}
StreamUnwrap::~StreamUnwrap(){
close();
for (auto &ctx : decode_ctx){
avcodec_free_context(&ctx.second);
}
}
bool StreamUnwrap::close(void){
//the reorder queue should be freed
for (auto pkt : reorder_queue){
unref_frame(pkt);
av_packet_free(&pkt);
}
reorder_queue.clear();
reorder_len = 0;
for (auto &pkt : decoded_packets){
av_packet_unref(pkt);
av_packet_free(&pkt);
}
for (auto &frame : decoded_video_frames){
av_frame_free(&frame);
}
avformat_close_input(&input_format_context);
input_format_context = NULL;
return true;
}
bool StreamUnwrap::connect(IOWrapper &io) {
if (input_format_context){
return false;
}
input_format_context = avformat_alloc_context();
if (!input_format_context){
return false;
}
input_format_context->pb = io.get_pb();
return connect();
}
bool StreamUnwrap::connect(void) {
LINFO("Reorder queue was first set at " + cfg.get_value("reorder-queue-len"));
const std::string& url = cfg.get_value("video-url");
if (!url.compare("") && !input_format_context){
LERROR( "Camera was not supplied with a URL" + url);
return false;
}
int error;
AVDictionary *opts = Util::get_dict_options(cfg.get_value("ffmpeg-demux-options"));
#ifdef DEBUG
if (av_dict_count(opts)){
LWARN("Setting Options:");
dump_options(opts);
}
#endif
/* Open the input file to read from it. */
error = avformat_open_input(&input_format_context, url.c_str(), NULL, &opts);
if (error < 0) {
LERROR( "Could not open camera url '" + url + "' (error '" + std::string(av_err2str(error)) +")");
input_format_context = NULL;
av_dict_free(&opts);
return false;
}
Util::get_videotime(connect_time);
#ifdef DEBUG
if (av_dict_count(opts)){
LWARN("Invalid Options:");
dump_options(opts);
}
#endif
av_dict_free(&opts);
/* Get information on the input file (number of streams etc.). */
if ((error = avformat_find_stream_info(input_format_context, NULL)) < 0) {
LERROR( "Could not open find stream info (error '" + std::string(av_err2str(error)) + "')");
avformat_close_input(&input_format_context);
return false;
}
LINFO("Video Stream has " + std::to_string(input_format_context->nb_streams) + " streams");
#ifdef DEBUG
//print all the stream info
for (unsigned int i = 0; i < input_format_context->nb_streams; i++){
LINFO("Stream " + std::to_string(i) + " details, codec " + std::to_string(input_format_context->streams[i]->codecpar->codec_type)+ ":");
av_dump_format(input_format_context, i, url.c_str(), 0);
}
#endif
input_format_context->flags |= AVFMT_FLAG_GENPTS;//fix the timestamps...
//start reading frames
reorder_len = cfg.get_value_int("reorder-queue-len");
LINFO("Reorder queue was set at " + cfg.get_value("reorder-queue-len"));
return charge_reorder_queue();
}
AVFormatContext* StreamUnwrap::get_format_context(void){
return input_format_context;
}
unsigned int StreamUnwrap::get_stream_count(void){
return input_format_context->nb_streams;
}
bool StreamUnwrap::alloc_decode_context(unsigned int stream){
AVCodecContext *avctx;
const AVCodec *input_codec;
int error;
if (decode_ctx.find(stream) != decode_ctx.end()){
LDEBUG("Not generating decode context, it already exists");
return true;//already exists, bail early
}
if (stream >= get_stream_count()){
LERROR("Attempted to access stream that doesn't exist");
return false;
}
AVCodecParameters *stream_codecpar = input_format_context->streams[stream]->codecpar;
bool using_v4l2 = false;
//check if we need to do V4L2
if ((cfg.get_value("video-decode-method") == "auto" &&
!gcff_util.have_vaapi(stream_codecpar->codec_id, stream_codecpar->profile, stream_codecpar->height, stream_codecpar->width) &&
!gcff_util.have_vdpau(stream_codecpar->codec_id, stream_codecpar->profile, stream_codecpar->height, stream_codecpar->width)) ||
cfg.get_value("video-decode-method") == "v4l2"){
LDEBUG("Attempting V4L2");
//use v4l2
using_v4l2 = gcff_util.have_v4l2(stream_codecpar->codec_id, stream_codecpar->profile, stream_codecpar->height, stream_codecpar->width);
}
//locate a decoder for the codec
input_codec = avcodec_find_decoder(input_format_context->streams[stream]->codecpar->codec_id);
if (!input_codec){
LWARN("Could not find decoder");
return false;
}
if (using_v4l2){
//check if this codec has a v4l2 version
std::string v4l2_name = std::string(input_codec->name) + std::string("_v4l2m2m");
const AVCodec *v4l_codec = avcodec_find_decoder_by_name(v4l2_name.c_str());
if (v4l_codec){
LINFO("Using ffmpeg " + std::string(v4l_codec->long_name) + " for decoding");
input_codec = v4l_codec;
} else {
using_v4l2 = false;
LINFO("You seem to have V4L2 support for " + std::string(input_codec->long_name) + " but ffmpeg was not compiled with the associated support");
}
}
if (!using_v4l2 && cfg.get_value("video-decode-method") == "v4l2"){
LWARN("V4L2 decoding was requested but is not available, falling back to SW");
}
/* Allocate a new decoding context. */
avctx = avcodec_alloc_context3(input_codec);
if (!avctx) {
LERROR("Could not allocate a decoding context");
return false;
}
/* Initialize the stream parameters with demuxer information. */
error = avcodec_parameters_to_context(avctx, input_format_context->streams[stream]->codecpar);
if (error < 0) {
avcodec_free_context(&avctx);
return false;
}
if (avctx->codec_type == AVMEDIA_TYPE_VIDEO){
//connect decoder
if (!using_v4l2 && !avctx->hw_device_ctx &&
(cfg.get_value("video-decode-method") == "auto" || cfg.get_value("video-decode-method") == "vaapi")){
avctx->hw_device_ctx = gcff_util.get_vaapi_ctx(avctx->codec_id, avctx->profile, avctx->height, avctx->width);
if (avctx->hw_device_ctx){
avctx->get_format = get_vaapi_format;
LINFO("Using VA-API for decoding");
}
}
if (!using_v4l2 && !avctx->hw_device_ctx &&
(cfg.get_value("video-decode-method") == "auto" || cfg.get_value("video-decode-method") == "vdpau")){
avctx->hw_device_ctx = gcff_util.get_vdpau_ctx(avctx->codec_id, avctx->profile, avctx->height, avctx->width);
if (avctx->hw_device_ctx){
avctx->get_format = get_vdpau_format;
LINFO("Using VDPAU for decoding");
}
}
//if both fail we get the SW decoder
if (!avctx->hw_device_ctx){
avctx->opaque = this;
avctx->get_format = get_frame_format;//do any format, but prefer VAAPI compatible formats
if (!using_v4l2){
LINFO("Using SW Decoding");
}
}
}
/* Open the decoder. */
gcff_util.lock();
error = avcodec_open2(avctx, input_codec, NULL);
gcff_util.unlock();
if (error < 0) {
LERROR("Could not open input codec (error '" + std::string(av_err2str(error)) + "')");
avcodec_free_context(&avctx);
return false;
}
/* Save the decoder context for easier access later. */
decode_ctx[stream] = avctx;
return true;
}
bool StreamUnwrap::get_next_frame(AVPacket *packet){
if (!decoded_packets.empty()){
av_packet_move_ref(packet, decoded_packets.front());
av_packet_free(&decoded_packets.front());
decoded_packets.pop_front();
return true;
}
return get_next_packet(packet);
}
bool StreamUnwrap::get_next_packet(AVPacket *packet){
read_frame();
if (reorder_queue.size() > 0){
av_packet_move_ref(packet, reorder_queue.front());
av_packet_free(&reorder_queue.front());
reorder_queue.pop_front();
//fixup the duration
if (packet->duration == 0 || packet->duration == AV_NOPTS_VALUE){
packet->duration = 0;
for (const auto &next : reorder_queue){
if (next->stream_index == packet->stream_index){
packet->duration = next->pts - packet->pts;
break;
}
}
}
return true;
} else {
LWARN("Reorder Queue is 0");
return false;
}
}
void StreamUnwrap::unref_frame(AVPacket *packet){
av_packet_unref(packet);
}
void StreamUnwrap::dump_options(AVDictionary* dict){
AVDictionaryEntry *en = NULL;
while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
LWARN("\t" + std::string(en->key) + "=" + std::string(en->value));
}
}
bool StreamUnwrap::charge_reorder_queue(void){
while (reorder_queue.size() < reorder_len){
if (!read_frame()){
break;//error reading a frame we exit
}
}
return true;
}
void StreamUnwrap::sort_reorder_queue(void){
if (reorder_queue.size() < 2){
//nothing to sort if it's this small
return;
}
auto av_old_back = reorder_queue.end();
std::advance(av_old_back, -2);
AVPacket *old_back = *av_old_back;
long back_dts_in_old_back = av_rescale_q_rnd(reorder_queue.back()->dts,
input_format_context->streams[reorder_queue.back()->stream_index]->time_base,
input_format_context->streams[old_back->stream_index]->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
if (old_back->dts > back_dts_in_old_back){
//need to walk the queue and insert it in the right spot...
bool back_is_video = input_format_context->streams[reorder_queue.back()->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
//FIXME: this loop should be optimized to run back to front, as that's the short direction
for (std::list<AVPacket*>::iterator itr = reorder_queue.begin(); itr != reorder_queue.end() ; itr++){
long back_dts_in_itr = av_rescale_q_rnd(reorder_queue.back()->dts,
input_format_context->streams[reorder_queue.back()->stream_index]->time_base,
input_format_context->streams[(*itr)->stream_index]->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
if (((*itr)->dts > reorder_queue.back()->dts && (*itr)->stream_index == reorder_queue.back()->stream_index) || //same stream and dts is out of order
((*itr)->stream_index != reorder_queue.back()->stream_index && (*itr)->dts > back_dts_in_itr) || // different stream and out of order
((*itr)->stream_index != reorder_queue.back()->stream_index && (*itr)->dts == back_dts_in_itr && back_is_video)){ //different stream and video and same time
if (itr == reorder_queue.begin() && reorder_queue.size() == reorder_len){
//itr is the front here
//estimate what it would take
long dts_itr_to_front = (*itr)->dts - back_dts_in_itr;//this is how far ahead the packet was from the queue
auto av_back = reorder_queue.end();
std::advance(av_back, -2);
AVPacket *back = *av_back;
AVPacket *front = reorder_queue.front();
long back_dts_in_itr = av_rescale_q_rnd(back->dts,
input_format_context->streams[back->stream_index]->time_base,
input_format_context->streams[(*itr)->stream_index]->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
long front_dts_in_itr = av_rescale_q_rnd(front->dts,
input_format_context->streams[front->stream_index]->time_base,
input_format_context->streams[(*itr)->stream_index]->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
double que_lent = av_q2d(input_format_context->streams[(*itr)->stream_index]->time_base) * ( back_dts_in_itr - front_dts_in_itr);
double target_addational_lent = av_q2d(input_format_context->streams[(*itr)->stream_index]->time_base) * ( dts_itr_to_front );
double target_change = (target_addational_lent/que_lent) + 1.0;
LINFO("Reorder queue is short by " + std::to_string(target_addational_lent) + "s, recommend making reorder-queue-len at least " +
std::to_string((int)(target_change * reorder_queue.size())) + " for camera " /*+ cfg.get_value("camera-id") */);
}
reorder_queue.splice(itr, reorder_queue, std::prev(reorder_queue.end()));
break;
}
}
}
}
bool StreamUnwrap::read_frame(void){
reorder_queue.emplace_back(av_packet_alloc());
struct timeval start_recv_time;
Util::get_videotime(start_recv_time);
if (av_read_frame(input_format_context, reorder_queue.back())){
av_packet_free(&reorder_queue.back());
reorder_queue.pop_back();
LINFO("av_read_frame() failed or hit EOF");
return false;
}
struct timeval recv_time;
Util::get_videotime(recv_time);
//fixup this data...maybe limit it to the first one?
if (reorder_queue.back()->dts == AV_NOPTS_VALUE){
reorder_queue.back()->dts = 0;
}
if (reorder_queue.back()->pts == AV_NOPTS_VALUE){
reorder_queue.back()->pts = 0;
}
//compute the delay
record_delay(start_recv_time, recv_time);
sort_reorder_queue();
//FIXME: This only considers whole seconds
recv_time.tv_sec -= connect_time.tv_sec;
//check if this is a file, if yes we skip timestamp resyncing
if (input_format_context->url && input_format_context->url[0] == '/'){
return true;
}
//check the time of the youngest packet...
double delta = recv_time.tv_sec;
delta -= av_q2d(input_format_context->streams[reorder_queue.back()->stream_index]->time_base) * reorder_queue.back()->dts;
if (delta > max_sync_offset || delta < -max_sync_offset){
connect_time.tv_sec += delta;
LWARN("Input stream has drifted " + std::to_string(delta) + "s from wall time on camera " + cfg.get_value("camera-id") + ", resyncing..." );
}
return true;
}
const struct timeval& StreamUnwrap::get_start_time(void){
return connect_time;
}
bool StreamUnwrap::decode_packet(AVPacket *packet){
int ret;
if (decode_ctx.find(packet->stream_index) == decode_ctx.end()){
if (!alloc_decode_context(packet->stream_index)){
return false;
}
}
ret = avcodec_send_packet(decode_ctx[packet->stream_index], packet);
if (ret == AVERROR(EAGAIN)){
//probably should return ret instead of this as it's a soft error
LWARN("Attempted to decode data without reading all frames");
return false;
} else if (ret == AVERROR(EINVAL)){
return false;
LWARN("Codec error: needs a flush?");
} else if (ret == AVERROR(ENOMEM)){
//probably need to think about restarting the camera
LWARN("Error Decoding Packet, buffer is full");
return false;
} else if (ret < 0){
//probably should restart the camera
LWARN("Unknown decoding error");
return false;
}
return true;
}
bool StreamUnwrap::get_decoded_frame(int stream, AVFrame *frame){
if (!decoded_video_frames.empty() && input_format_context->streams[stream]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO){
av_frame_move_ref(frame, decoded_video_frames.front());
av_frame_free(&decoded_video_frames.front());
decoded_video_frames.pop_front();
return true;
}
return get_decoded_frame_int(stream, frame);
}
bool StreamUnwrap::peek_decoded_vframe(AVFrame *frame){
if (!decoded_video_frames.empty()){
av_frame_ref(frame, decoded_video_frames.front());
return true;
}
LWARN("No Frame to peek");
return false;
}
bool StreamUnwrap::get_decoded_frame_int(int stream, AVFrame *frame){
if (decode_ctx.find(stream) == decode_ctx.end()){
LWARN("Tried to decode a frame without a decoder!");
return false;
}
int ret = avcodec_receive_frame(decode_ctx[stream], frame);
if (ret == 0){
return true;
} else if (ret == AVERROR(EAGAIN)){
//need to call decode packet
return false;
} else {
//probably need to think about restarting the camera
LWARN("Error reading frame");
return false;
}
}
void StreamUnwrap::timestamp(const AVPacket *packet, struct timeval &time){
Util::compute_timestamp(get_start_time(), time, packet->pts, input_format_context->streams[packet->stream_index]->time_base);
}
void StreamUnwrap::timestamp(const AVFrame *frame, int stream_idx, struct timeval &time){
if (stream_idx < 0 || stream_idx >= static_cast<int>(input_format_context->nb_streams)){
time.tv_sec = 0;
time.tv_usec = 0;
LWARN("StreamUnwrap timestamp() received invalid streamindex");
return;
}
Util::compute_timestamp(get_start_time(), time, frame->pts, input_format_context->streams[stream_idx]->time_base);
}
bool StreamUnwrap::is_audio(const AVPacket *packet){
return input_format_context->streams[packet->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
}
bool StreamUnwrap::is_video(const AVPacket *packet){
return input_format_context->streams[packet->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
}
AVStream *StreamUnwrap::get_stream(const AVPacket *packet){
return get_stream(packet->stream_index);
}
AVStream *StreamUnwrap::get_stream(const int id){
return input_format_context->streams[id];
}
AVStream *StreamUnwrap::get_audio_stream(void){
int best_stream = av_find_best_stream(input_format_context, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
if (best_stream == AVERROR_STREAM_NOT_FOUND || best_stream == AVERROR_DECODER_NOT_FOUND){
return NULL;
}
return get_stream(best_stream);
}
AVStream *StreamUnwrap::get_video_stream(void){
int best_stream = av_find_best_stream(input_format_context, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
if (best_stream == AVERROR_STREAM_NOT_FOUND || best_stream == AVERROR_DECODER_NOT_FOUND){
return NULL;
}
return get_stream(best_stream);
}
AVCodecContext* StreamUnwrap::get_codec_context(AVStream *stream){
if (!stream){
return NULL;
}
if (decode_ctx.find(stream->index) == decode_ctx.end()){
if (!alloc_decode_context(stream->index)){
return NULL;
}
}
return decode_ctx[stream->index];
}
bool StreamUnwrap::charge_video_decoder(void){
do {
decoded_packets.emplace_back(av_packet_alloc());
if (!get_next_packet(decoded_packets.back())){
av_packet_free(&decoded_packets.back());
decoded_packets.pop_back();
return false;
}
AVPacket *pkt = decoded_packets.back();
if (decoded_video_frames.empty() && is_video(pkt)){
LDEBUG("Decoding packet");
if (decode_packet(pkt)){
LDEBUG("Decoded packet");
bool ret;
do {
AVFrame* next_frame = av_frame_alloc();
ret = get_decoded_frame_int(pkt->stream_index, next_frame);
if (ret){
decoded_video_frames.push_back(next_frame);
LDEBUG("Decoded frame");
next_frame = NULL;
break;
} else {
av_frame_free(&next_frame);
}
} while (ret);
} else {
LWARN("Failed to decode video during charge");
return false;
}
}
} while (decoded_video_frames.empty());
return true;
}
enum AVPixelFormat StreamUnwrap::get_frame_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts){
StreamUnwrap* stream = static_cast<StreamUnwrap*>(ctx->opaque);
const std::string &cfg_fmt = stream->cfg.get_value("video-hw-pix-fmt");
if (cfg_fmt != "auto"){
const enum AVPixelFormat target_fmt = av_get_pix_fmt(cfg_fmt.c_str());
if (target_fmt != AV_PIX_FMT_NONE){
const enum AVPixelFormat *p;
for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++){
if (target_fmt == *p){
return *p;
}
}
}
}
return get_sw_format(ctx, pix_fmts);
}
void StreamUnwrap::record_delay(const struct timeval &start, const struct timeval &end){
double timeshift_beta = 0.01;
if (timeshift_mean_delay == 0){
timeshift_beta = 1;//first run initilization
}
//compute the packet read delay
double delay = end.tv_sec - start.tv_sec;
delay += (end.tv_usec - start.tv_usec)/1000000.0;
//compute the mean time of the packets received
double duration = av_q2d(input_format_context->streams[reorder_queue.back()->stream_index]->time_base) * reorder_queue.back()->duration;
duration /= input_format_context->nb_streams;
if (timeshift_mean_delay != 0){
timeshift_mean_delay = timeshift_mean_delay*(1-timeshift_beta) + delay*timeshift_beta;
timeshift_mean_duration = timeshift_mean_duration*(1-timeshift_beta) + duration*timeshift_beta;
} else {
//initilize to duration so frames are not dropped
timeshift_mean_delay = duration;
timeshift_mean_duration = duration;
}
//LINFO("Delay: " + std::to_string(timeshift_mean_delay) + " Duration: " + std::to_string(timeshift_mean_duration));
}
double StreamUnwrap::get_mean_delay(void) const{
return timeshift_mean_delay;
}
double StreamUnwrap::get_mean_duration(void) const{
return timeshift_mean_duration;
}
| 23,719
|
C++
|
.cpp
| 541
| 35.561922
| 172
| 0.612029
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,951
|
export.cpp
|
edman007_chiton/export.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "export.hpp"
#include "util.hpp"
#include "stream_unwrap.hpp"
#include "stream_writer.hpp"
#include "io/cfmp4.hpp"
#include "system_controller.hpp"
#include <memory>
Export::Export(SystemController &sys) : sys(sys), db(sys.get_db()), cfg(sys.get_sys_cfg()), g_fm(sys.get_fm()) {
force_exit = false;
export_in_progress = false;
id = 0;
reserved_bytes = 0;
camera_cfg = nullptr;
pkt = av_packet_alloc();
}
Export::~Export(void){
lock.lock();
force_exit = true;
if (runner.joinable()){
runner.join();//always join holding the lock since it could be joined from different threads
}
lock.unlock();
delete camera_cfg;
av_packet_free(&pkt);
}
bool Export::check_for_jobs(void){
if (export_in_progress){
return true;//return true because it's already in progress
}
lock.lock();
//check if the job is running
if (runner.joinable()){
runner.join();
}
const std::string sql = "SELECT id, starttime, endtime, camera, path, progress FROM exports WHERE progress != 100 LIMIT 1";
DatabaseResult *res = db.query(sql);
if (res && res->next_row()){
id = res->get_field_long(0);
starttime = res->get_field_ll(1);
endtime = res->get_field_ll(2);
camera = res->get_field_long(3);
path = std::string(res->get_field(4));
progress = res->get_field_long(5);
delete res;
return start_job();
} else if (res){
delete res;
}
lock.unlock();
return false;
}
//should always be called while holding the lock
bool Export::start_job(void){
export_in_progress = true;
force_exit = false;
lock.unlock();
runner = std::thread(&Export::run_job, this);
return runner.joinable();
}
void Export::run_job(void){
Util::set_low_priority();//reduce the thread priority
delete camera_cfg;
camera_cfg = new Config(cfg);//reinit the config with the system config
camera_cfg->load_camera_config(camera, db);
FileManager fm(sys, *camera_cfg);
if (path != ""){
fm.rm_file(path + std::to_string(id) + EXPORT_EXT);
path = "";
}
//generate a path
struct timeval start;
Util::unpack_time(starttime, start);
path = fm.get_export_path(id, camera, start);
progress = 1;
LINFO("Performing Export for camera " + std::to_string(camera));
update_progress();
//query all segments we need
std::string sql = "SELECT id, path, endtime, extension, name, init_byte, start_byte, end_byte, codec FROM videos WHERE camera = " + std::to_string(camera) + " AND ( "
"( endtime >= " + std::to_string(starttime) + " AND endtime <= " + std::to_string(endtime) + " ) "
" OR (starttime >= " + std::to_string(starttime) + " AND starttime <= " + std::to_string(endtime) + " )) "
" ORDER BY starttime ASC ";
DatabaseResult *res = db.query(sql);
if (!res){
LWARN("Failed to query segments for export");
export_in_progress = false;
return;
}
StreamUnwrap in = StreamUnwrap(*camera_cfg);
StreamWriter out = StreamWriter(*camera_cfg);
out.change_path(path);
long long total_time_target = endtime - starttime;
reserved_bytes = 0;
bool output_opened = false;
std::string prev_ext = "", prev_codec;
while (res->next_row()){
if (prev_ext == "" && prev_codec == ""){
prev_ext = res->get_field(3);
prev_codec = res->get_field(8);
} else if (prev_ext != res->get_field(3) || prev_codec != res->get_field(8)){
if (!split_export(res->get_field_long(0))){
LWARN("Error Splitting Export");
}
out.close();
progress = 100;
update_progress();
export_in_progress = false;
return;
}
std::string segment = fm.get_path(res->get_field_long(4), res->get_field(1), res->get_field(3));
LDEBUG("Exporting " + segment);
//we control the input stream by replacing the video-url with the segment
camera_cfg->set_value("video-url", segment);
std::unique_ptr<IOWrapper> io;
if (res->get_field(3) == ".ts"){
//get the filesize of the segment and subtrack from reserved bytes
reserve_space(fm, fm.get_filesize(segment));
if (!in.connect()){
//try the next one...
continue;
}
} else if (res->get_field(3) == ".mp4") {
reserve_space(fm, res->get_field_long(7) - res->get_field_long(6));
io = std::unique_ptr<CFMP4>(new CFMP4(segment, res->get_field_long(5), res->get_field_long(6), res->get_field_long(7)));
camera_cfg->set_value("video-url", io->get_url());
if (!in.connect(*io.get())){
//try the next one...
continue;
}
} else {
LWARN(res->get_field(3) + " is not supported for export");
continue;
}
if (!output_opened){
if (!out.copy_streams(in)){
continue;
}
output_opened = out.open();
if (!output_opened){
//failed to open it, we need to bail
force_exit = true;//this will cause the job to be retried, assuming the issue was maybe drive space?
break;
}
}
while (in.get_next_frame(pkt)){
out.write(pkt, in.get_stream(pkt));
in.unref_frame(pkt);
}
in.close();
if (force_exit){
LWARN("Export was canceled due to shutdown");
break;
}
//compute the progress
if (res->get_field(2) != "NULL"){//do not compute the progress if we don't know how long this is
long new_progress = 100 - (100*(endtime - res->get_field_long(2))) / total_time_target;
if (new_progress > progress && new_progress < 100){//this can result in number over 100, we don't put 100 in until it's actually done
progress = new_progress;
update_progress();
}
}
}
out.close();
if (!force_exit){
//if we are force exiting then we didn't finish
progress = 100;
update_progress();
}
id = 0;
export_in_progress = false;
}
bool Export::update_progress(){
long affected = 0;
std::string sql = "UPDATE exports SET progress = " + std::to_string(progress) + " WHERE id = " + std::to_string(id);
DatabaseResult *res = db.query(sql, &affected, NULL);
if (res){
delete res;
}
return affected != 0;
}
bool Export::rm_export(int export_id){
//rm the export
lock.lock();
if (id == export_id){
force_exit = true;//but we do not need to wait
}
std::string sql = "SELECT path, id FROM exports WHERE id = " + std::to_string(export_id);
DatabaseResult *res = db.query(sql);
long del_count = 0;
if (res){
if (res->next_row()){
std::string path = res->get_field(0) + res->get_field(1) + EXPORT_EXT;
g_fm.rm_file(path);
delete res;
sql = "DELETE FROM exports WHERE id = " + std::to_string(export_id);
res = db.query(sql, &del_count, NULL);
}
delete res;
}
lock.unlock();
return del_count > 0;
}
void Export::reserve_space(FileManager &fm, long size){
if (size <= 0){
LINFO("reserve_space called with invalid size");
return;
}
if (reserved_bytes < size){
//reserve more bytes
long req_bytes = 50*size;//should be 5min of video
fm.reserve_bytes(req_bytes, camera);
reserved_bytes += req_bytes;
}
reserved_bytes -= size;
}
bool Export::split_export(long seg_id){
std::string query = "INSERT INTO exports (camera, path, starttime, endtime) "
"SELECT e.camera, e.path, s.starttime + 1, e.endtime "
"FROM exports AS e, videos AS s "
"WHERE e.id = " + std::to_string(id) + " AND s.id = " + std::to_string(seg_id);
long affected;
DatabaseResult *res = db.query(query, &affected, NULL);
delete res;
bool ret = affected != 0;
query = "UPDATE exports SET endtime = (SELECT starttime FROM videos WHERE id = " + std::to_string(seg_id) + ") WHERE id = " + std::to_string(id);
res = db.query(query, &affected, NULL);
delete res;
return affected != 0 && ret;
}
| 9,392
|
C++
|
.cpp
| 249
| 30.610442
| 170
| 0.581852
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,952
|
config_parser.cpp
|
edman007_chiton/config_parser.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_parser.hpp"
#include "util.hpp"
void ConfigParser::parse(void){
reset_parser();
while (next()){
if ((state == IN_COMMENT || state == AFTER_VAL || state == BEFORE_VAL) && c == '\n'){
reset_parser();
continue;//no use in continuing if we are in a comment
}
if (c == '\n' && (state == IN_KEY || state == BEFORE_VAL || state == AFTER_KEY)){
report_parse_error();
return;
}
if (c == '\n' && !doublequote && !singlequote && state == IN_VAL){
//set the value
cfg.set_value(key.str(), value.str());
reset_parser();
continue;
}
if (c == '\n' && !doublequote && !singlequote && state == BEFORE_KEY){
reset_parser();
continue;
}
//check for the comment
if (!doublequote && !singlequote && c == '#'){
//starting a comment...
if (state == IN_KEY ||
state == AFTER_KEY ||
state == BEFORE_VAL){
//invalid
report_parse_error();
return;
}
if (state == IN_VAL && !doublequote && !singlequote){
//set the value
cfg.set_value(key.str(), value.str());
state = IN_COMMENT;
continue;
}
state = IN_COMMENT;
continue;
}
switch (state){
case BEFORE_KEY:
if (c != ' ' && c != '\t'){
key.sputc(c);
state = IN_KEY;
}
break;
case IN_KEY:
if (c == '=') {
state = BEFORE_VAL;
} else if (c == ' ' || c == '\t'){
state = AFTER_KEY;
} else {
key.sputc(c);
}
break;
case AFTER_KEY:
if (c == '='){
state = BEFORE_VAL;
}
break;
case BEFORE_VAL:
if (c == '\''){
singlequote = true;
state = IN_VAL;
} else if (c == '"'){
doublequote = true;
state = IN_VAL;
} else if (c != ' ' && c != '\t'){
value.sputc(c);
state = IN_VAL;
}
break;
case IN_VAL:
if (c == '\\' && (singlequote || doublequote )){
if (escape){
value.sputc('\\');
escape = false;
continue;
} else {
escape = true;
continue;
}
}
if (c == '"' && escape && doublequote){
value.sputc('"');
escape = false;
continue;
} else if (c == '"' && doublequote){
//we are done
cfg.set_value(key.str(), value.str());
state = AFTER_VAL;
doublequote = false;
continue;
}
if (c == '\'' && escape && singlequote){
value.sputc('\'');
escape = false;
continue;
} else if (c == '\'' && singlequote){
//we are done
cfg.set_value(key.str(), value.str());
state = AFTER_VAL;
singlequote = false;
continue;
}
if ((c == ' ' || c == '\t') && (singlequote || doublequote)){
//we are done
cfg.set_value(key.str(), value.str());
state = AFTER_VAL;
continue;
}
if (escape){
//nothing else is escapable, so we add the \ back in
value.sputc('\\');
escape = false;
//and continue, because we are on a new character...
}
value.sputc(c);
break;
case AFTER_VAL:
//anything after the value might as well be a comment
if (c == '#'){
state = IN_COMMENT;
}
case IN_COMMENT:
//it's a comment, nothing to do
break;
}
}
if (state == IN_VAL && !singlequote && !doublequote){
//end of file in a value means we are done
cfg.set_value(key.str(), value.str());
} else if (singlequote || doublequote || (state != BEFORE_KEY && state != AFTER_VAL && state != IN_COMMENT && state != IN_VAL)){
//file ended in the middle of parsing
report_parse_error();
}
}
void ConfigParser::reset_parser(void){
//the default for the start of a line:
key.str("");
value.str("");
state = BEFORE_KEY;
escape = false;
doublequote = false;
singlequote = false;
}
bool ConfigParser::next(void){
ifs.get(c);
pos++;
if (c == '\n'){
line++;
pos = 0;
}
return ifs.good();
}
void ConfigParser::report_parse_error(void){
LWARN( "Parse error in config file, line " + std::to_string(line) + ", char " + std::to_string(pos));
}
| 6,226
|
C++
|
.cpp
| 182
| 22.472527
| 132
| 0.442901
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,953
|
motion_cvmask.cpp
|
edman007_chiton/motion_cvmask.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "motion_cvmask.hpp"
#ifdef HAVE_OPENCV
#include "util.hpp"
#include <opencv2/imgproc.hpp>
static const std::string algo_name = "cvmask";
MotionCVMask::MotionCVMask(Config &cfg, Database &db, MotionController &controller) : MotionAlgo(cfg, db, controller, algo_name), sensitivity_it(sensitivity_db.begin()) {
ocvr = NULL;
background = NULL;
//FIXME: Make config parameters
tau = cfg.get_value_double("motion-cvmask-tau");
if (tau < 0 || tau > 1){
tau = 0.0001;
}
beta = cfg.get_value_double("motion-cvmask-beta");
if (beta < 0 || beta > 255){
beta = 30.0;
}
thresh = cfg.get_value_int("motion-cvmask-threshold");
if (thresh < 1 || thresh > 255){
thresh = 5;
}
int sens_cnt = cfg.get_value_int("motion-cvmask-delay");
if (sens_cnt < 1 || sens_cnt > 600){
thresh = 30;
}
//initilize the sensitivity_db
sensitivity_db.reserve(sens_cnt);
sensitivity_it = sensitivity_db.begin();
sensitivity_db.insert(sensitivity_it, sens_cnt, cv::UMat());
sensitivity_it = sensitivity_db.end() - 1;
}
MotionCVMask::~MotionCVMask(){
ocvr = NULL;//we don't own it
background = NULL;//we don't own it
}
bool MotionCVMask::process_frame(const AVFrame *frame, bool video){
if (!video){
return true;
}
if (!ocvr || !background){
return false;
}
try {
auto sensitivity_prev_it = sensitivity_it;
sensitivity_it++;
if (sensitivity_it == sensitivity_db.end()){
sensitivity_it = sensitivity_db.begin();
}
cv::UMat diff;
cv::absdiff(ocvr->get_UMat(), background->get_background(), diff);//difference between the background
if ((*sensitivity_it).empty()){
*sensitivity_it = cv::UMat(diff.size(), CV_32FC1);
diff.convertTo(*sensitivity_it, CV_32FC1);
if ((*sensitivity_prev_it).empty()){
(*sensitivity_it).copyTo(*sensitivity_prev_it);
}
}
cv::subtract(diff, *sensitivity_it, masked, cv::noArray(), CV_8U);//compare to current
cv::threshold(masked, masked, thresh, 255, cv::THRESH_BINARY);
cv::addWeighted(*sensitivity_prev_it, 1-tau, diff, beta*tau, 0, *sensitivity_it, CV_32FC1);//add to previous and make that the new current
cv::medianBlur(masked, masked, 5);//this will despeckle the image
} catch (cv::Exception &e){
LWARN("MotionCVMask::process_frame failed, error: " + e.msg);
return false;
}
return true;
}
bool MotionCVMask::set_video_stream(const AVStream *stream, const AVCodecContext *codec) {
return true;
}
const std::string& MotionCVMask::get_mod_name(void) {
return algo_name;
}
bool MotionCVMask::init(void) {
ocvr = static_cast<MotionCVResize*>(controller.get_module_before("cvresize", this));
background = static_cast<MotionCVBackground*>(controller.get_module_before("cvbackground", this));
return true;
}
const cv::UMat MotionCVMask::get_masked(void){
return masked;
}
const cv::UMat MotionCVMask::get_sensitivity(void){
return *sensitivity_it;
}
//HAVE_OPENCV
#endif
| 4,071
|
C++
|
.cpp
| 107
| 33.121495
| 170
| 0.638298
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,954
|
chiton_ffmpeg.cpp
|
edman007_chiton/chiton_ffmpeg.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2023 Ed Martin <edman007@edman007.com>
*
* Portions of this file have been borrowed and modified from FFmpeg,
* these portions have been origionally licensed under GPL 2.1
*
**************************************************************************
*/
#include "util.hpp"
#include <cstdio>
#include <sstream>
#include <vector>
#ifdef HAVE_VAAPI
#include <va/va.h>
#endif
#ifdef HAVE_OPENCL
#ifdef HAVE_OPENCL_CL_H
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
#endif
#ifdef HAVE_OPENCV
#include <opencv2/core/ocl.hpp>
#endif
#ifdef HAVE_V4L2
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <libv4l2.h>
#endif
thread_local std::string last_line;//contains the continuation of any line that doesn't have a \n
CFFUtil gcff_util;//global instance of our util class
// For converting from FFMPEG codecs to VAAPI codecs (see ffmpeg_vaapi.c from FFmpeg)
static const struct {
enum AVCodecID codec_id;
int codec_profile;
VAProfile va_profile;
} vaapi_profile_map[] = {
#define MAP(c, p, v) { AV_CODEC_ID_ ## c, FF_PROFILE_ ## p, VAProfile ## v }
MAP(H264, H264_MAIN, H264Main ),
MAP(H264, H264_HIGH, H264High ),
MAP(H264, H264_CONSTRAINED_BASELINE, H264ConstrainedBaseline),
#if !VA_CHECK_VERSION(1, 0, 0)
MAP(H264, H264_BASELINE, H264Baseline),
#endif
#if VA_CHECK_VERSION(0, 37, 0)
MAP(HEVC, HEVC_MAIN, HEVCMain ),
#endif
/* These codecs might be used for decoding */
MAP(WMV3, VC1_SIMPLE, VC1Simple ),
MAP(WMV3, VC1_MAIN, VC1Main ),
MAP(WMV3, VC1_COMPLEX, VC1Advanced ),
MAP(WMV3, VC1_ADVANCED, VC1Advanced ),
MAP(MPEG2VIDEO, MPEG2_SIMPLE, MPEG2Simple ),
MAP(MPEG2VIDEO, MPEG2_MAIN, MPEG2Main ),
MAP(VC1, VC1_SIMPLE, VC1Simple ),
MAP(VC1, VC1_MAIN, VC1Main ),
MAP(VC1, VC1_COMPLEX, VC1Advanced ),
MAP(VC1, VC1_ADVANCED, VC1Advanced ),
MAP(H263, UNKNOWN, H263Baseline),
MAP(MPEG4, MPEG4_SIMPLE, MPEG4Simple ),
MAP(MPEG4, MPEG4_ADVANCED_SIMPLE, MPEG4AdvancedSimple),
MAP(MPEG4, MPEG4_MAIN, MPEG4Main ),
#if VA_CHECK_VERSION(0, 35, 0)
MAP(VP8, UNKNOWN, VP8Version0_3 ),
#endif
#if VA_CHECK_VERSION(0, 37, 1)
MAP(VP9, VP9_0, VP9Profile0 ),
#endif
#undef MAP
};
/*
From the va.h, should support all?
VAProfileNone = -1,
VAProfileMPEG2Simple = 0,
VAProfileMPEG2Main = 1,
VAProfileMPEG4Simple = 2,
VAProfileMPEG4AdvancedSimple = 3,
VAProfileMPEG4Main = 4,
VAProfileH264Baseline va_deprecated_enum = 5,
VAProfileH264Main = 6,
VAProfileH264High = 7,
VAProfileVC1Simple = 8,
VAProfileVC1Main = 9,
VAProfileVC1Advanced = 10,
VAProfileH263Baseline = 11,
VAProfileJPEGBaseline = 12,
VAProfileH264ConstrainedBaseline = 13,
VAProfileVP8Version0_3 = 14,
VAProfileH264MultiviewHigh = 15,
VAProfileH264StereoHigh = 16,
VAProfileHEVCMain = 17,
VAProfileHEVCMain10 = 18,
VAProfileVP9Profile0 = 19,
VAProfileVP9Profile1 = 20,
VAProfileVP9Profile2 = 21,
VAProfileVP9Profile3 = 22,
VAProfileHEVCMain12 = 23,
VAProfileHEVCMain422_10 = 24,
VAProfileHEVCMain422_12 = 25,
VAProfileHEVCMain444 = 26,
VAProfileHEVCMain444_10 = 27,
VAProfileHEVCMain444_12 = 28,
VAProfileHEVCSccMain = 29,
VAProfileHEVCSccMain10 = 30,
VAProfileHEVCSccMain444 = 31,
VAProfileAV1Profile0 = 32,
VAProfileAV1Profile1 = 33,
VAProfileHEVCSccMain444_10 = 34
*/
void ffmpeg_log_callback(void * avcl, int level, const char * fmt, va_list vl){
if (level > gcff_util.get_ff_log_level()){
return;//ignore stuff that is too verbose
}
//compute the level first...
enum LOG_LEVEL chiton_level;
if (level <= AV_LOG_FATAL){
chiton_level = CH_LOG_FATAL;
} else if (level <= AV_LOG_ERROR){
chiton_level = CH_LOG_WARN;
} else if (level <= AV_LOG_WARNING){
chiton_level = CH_LOG_INFO;
} else if (level <= AV_LOG_INFO){
chiton_level = CH_LOG_INFO;
} else {
chiton_level = CH_LOG_DEBUG;
}
//format the message
char buf[1024];
int len = std::vsnprintf(buf, sizeof(buf), fmt, vl);
if (len >= 1){
//strip out the \n...
if (buf[len - 1] == '\n'){
buf[len - 1] = '\0';
} else {
last_line += buf;
return;
}
//and write it
Util::log_msg(chiton_level, last_line + buf);
last_line.clear();
}
}
void CFFUtil::load_ffmpeg(void){
av_log_set_callback(ffmpeg_log_callback);
//init vaapi
vaapi_ctx = NULL;
//we need to always try to load to avoid calling them avcodec_open2() which will cause a deadlock
load_vaapi();
load_vdpau();
}
void CFFUtil::load_vaapi(void){
if (vaapi_ctx || vaapi_failed){
return;//quick check, return if not required
}
lock();//lock and re-check (for races)
if (vaapi_ctx || vaapi_failed){
unlock();
return;//don't double alloc it
}
//FIXME: these NULLs should be user options
int ret = av_hwdevice_ctx_create(&vaapi_ctx, AV_HWDEVICE_TYPE_VAAPI, NULL, NULL, 0);
if (ret < 0) {
vaapi_ctx = NULL;
vaapi_failed = true;
unlock();
return;
}
unlock();
}
void CFFUtil::free_vaapi(void){
lock();
av_buffer_unref(&vaapi_ctx);
vaapi_failed = false;
unlock();
}
//ripped from vaapi_transcode.c ffmpeg demo
enum AVPixelFormat get_vaapi_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) {
const enum AVPixelFormat *p;
for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++){
if (*p == AV_PIX_FMT_VAAPI){
return *p;
}
}
return AV_PIX_FMT_NONE;//should this be pix_fmts?
}
void CFFUtil::load_vdpau(void){
if (vdpau_ctx || vdpau_failed){
return;//quick check
}
lock();//recheck holding the lock
if (vdpau_ctx || vdpau_failed){
unlock();
return;//don't double alloc it
}
//FIXME: these NULLs should be user options
int ret = av_hwdevice_ctx_create(&vdpau_ctx, AV_HWDEVICE_TYPE_VDPAU, NULL, NULL, 0);
if (ret < 0) {
vdpau_ctx = NULL;
vdpau_failed = true;
unlock();
return;
}
unlock();
}
void CFFUtil::free_vdpau(void){
lock();
av_buffer_unref(&vdpau_ctx);
vdpau_failed = false;
unlock();
}
//ripped from vdpau_transcode.c ffmpeg demo
enum AVPixelFormat get_vdpau_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) {
const enum AVPixelFormat *p;
for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++){
if (*p == AV_PIX_FMT_VDPAU){
return *p;
}
}
return AV_PIX_FMT_NONE;//should this be pix_fmts?
}
//Modified list, based on ffmpeg's hwcontext_vaapi.c
static const struct {
unsigned int va;//vaapi fourcc
AVPixelFormat ff;//ffmpeg
} vaapi_format_map[] = {
{VA_FOURCC_NV12, AV_PIX_FMT_NV12},
#ifdef VA_FOURCC_I420
{VA_FOURCC_I420, AV_PIX_FMT_YUV420P},
#endif
{VA_FOURCC_YV12, AV_PIX_FMT_YUV420P},
{VA_FOURCC_IYUV, AV_PIX_FMT_YUV420P},
{VA_FOURCC_422H, AV_PIX_FMT_YUV422P},
#ifdef VA_FOURCC_YV16
{VA_FOURCC_YV16, AV_PIX_FMT_YUV422P},
#endif
{VA_FOURCC_UYVY, AV_PIX_FMT_UYVY422},
{VA_FOURCC_YUY2, AV_PIX_FMT_YUYV422},
#ifdef VA_FOURCC_Y210
{VA_FOURCC_Y210, AV_PIX_FMT_Y210},
#endif
#if defined(VA_FOURCC_Y212) && defined(AV_PIX_FMT_Y212)
{VA_FOURCC_Y212, AV_PIX_FMT_Y212},
#endif
{VA_FOURCC_411P, AV_PIX_FMT_YUV411P},
{VA_FOURCC_422V, AV_PIX_FMT_YUV440P},
{VA_FOURCC_444P, AV_PIX_FMT_YUV444P},
#if defined(VA_FOURCC_XYUV) && defined(AV_PIX_FMT_VUYX)
{VA_FOURCC_XYUV, AV_PIX_FMT_VUYX},
#endif
{VA_FOURCC_Y800, AV_PIX_FMT_GRAY8},
#ifdef VA_FOURCC_P010
{VA_FOURCC_P010, AV_PIX_FMT_P010},
#endif
#if defined(VA_FOURCC_P012) && defined(AV_PIX_FMT_P012)
{VA_FOURCC_P012, AV_PIX_FMT_P012},
#endif
{VA_FOURCC_BGRA, AV_PIX_FMT_BGRA},
{VA_FOURCC_BGRX, AV_PIX_FMT_BGR0},
{VA_FOURCC_RGBA, AV_PIX_FMT_RGBA},
{VA_FOURCC_RGBX, AV_PIX_FMT_RGB0},
#ifdef VA_FOURCC_ABGR
{VA_FOURCC_ABGR, AV_PIX_FMT_ABGR},
{VA_FOURCC_XBGR, AV_PIX_FMT_0BGR},
#endif
{VA_FOURCC_ARGB, AV_PIX_FMT_ARGB},
{VA_FOURCC_XRGB, AV_PIX_FMT_0RGB},
#if defined(VA_FOURCC_X2R10G10B10) && defined(AV_PIX_FMT_X2RGB10)
{VA_FOURCC_X2R10G10B10, AV_PIX_FMT_X2RGB10},
#endif
#if defined(VA_FOURCC_Y410) && defined(AV_PIX_FMT_XV30)
{VA_FOURCC_Y410, AV_PIX_FMT_XV30},
#endif
#if defined(VA_FOURCC_Y412) && defined(AV_PIX_FMT_XV36)
{VA_FOURCC_Y412, AV_PIX_FMT_XV36},
#endif
{0, AV_PIX_FMT_NONE}
};
//check if we have a VAAPI compatible format to use, use the list from hwcontext_vaapi.c
enum AVPixelFormat get_sw_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) {
const enum AVPixelFormat *p;
AVPixelFormat first = pix_fmts[0];
#ifdef HAVE_VAAPI
for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++){
if (gcff_util.sw_format_is_hw_compatable(*p)){
return *p;
}
}
LDEBUG("No VAAPI compatble pixel formats available for decoder");
#endif
return first;//just whatever...
}
bool CFFUtil::sw_format_is_hw_compatable(const enum AVPixelFormat pix_fmt){
load_vaapi();
if (!vaapi_ctx){
return false;
}
AVHWFramesConstraints* c = av_hwdevice_get_hwframe_constraints(vaapi_ctx, NULL);
if (!c){
return false;
}
const enum AVPixelFormat *v;
for (v = c->valid_sw_formats; *v != AV_PIX_FMT_NONE; v++){
if (*v == pix_fmt){
av_hwframe_constraints_free(&c);
return true;
}
}
av_hwframe_constraints_free(&c);
return false;
}
std::string CFFUtil::get_sw_hw_format_list(Config &cfg, const AVFrame *frame, AVCodecID codec_id, int codec_profile){
load_vaapi();
if (!vaapi_ctx){
return "";
}
const std::string &cfg_fmt = cfg.get_value("video-hw-pix-fmt");
if (cfg_fmt != "auto"){
if (av_get_pix_fmt(cfg_fmt.c_str()) != AV_PIX_FMT_NONE){
return std::string(cfg_fmt);
}
}
std::stringstream ss;
void* hw_config = NULL;
#ifdef HAVE_VAAPI
if (frame && frame->format == AV_PIX_FMT_VAAPI && frame->hw_frames_ctx){
AVVAAPIDeviceContext *hwctx = get_vaapi_ctx_from_frames(frame->hw_frames_ctx);;
AVHWFramesContext *frames = reinterpret_cast<AVHWFramesContext*>(frame->hw_frames_ctx->data);
hw_config = av_hwdevice_hwconfig_alloc(frames->device_ref);
if (hw_config){
AVVAAPIHWConfig *va_hw_config = static_cast<AVVAAPIHWConfig*>(hw_config);
//the stupid defaults
VAEntrypoint entry = VAEntrypointVLD;//this is correct for FFMPeg decode, but does NOT work with VAProfileNone
VAProfile prof = VAProfileNone;
if (codec_id != AV_CODEC_ID_NONE){
prof = get_va_profile(hwctx, codec_id, codec_profile);
}
if (prof == VAProfileNone){
entry = VAEntrypointVideoProc;//if we didn't get a profile, we set to this to be more generic
}
VAStatus cfg_stat = vaCreateConfig(hwctx->display, prof, entry, NULL, 0, &va_hw_config->config_id);
if (cfg_stat != VA_STATUS_SUCCESS){
LWARN("vaCreateConfig Failed");
av_free(hw_config);
hw_config = NULL;
}
}
}
#endif
AVHWFramesConstraints* c = av_hwdevice_get_hwframe_constraints(vaapi_ctx, hw_config);
if (hw_config){
//free the hw config
#ifdef HAVE_VAAPI
if (frame && frame->format == AV_PIX_FMT_VAAPI){
AVVAAPIDeviceContext *hwctx = get_vaapi_ctx_from_frames(frame->hw_frames_ctx);;
if (hwctx){
AVVAAPIHWConfig *va_hw_config = static_cast<AVVAAPIHWConfig*>(hw_config);
vaDestroyConfig(hwctx->display, va_hw_config->config_id);
}
}
#endif
av_free(hw_config);
}
if (!c){
return "";
}
const enum AVPixelFormat *v;
for (v = c->valid_sw_formats; *v != AV_PIX_FMT_NONE; v++){
if (v != c->valid_sw_formats){
ss << "|";
}
ss << av_get_pix_fmt_name(*v);
}
av_hwframe_constraints_free(&c);
return ss.str();
}
bool CFFUtil::have_vaapi(AVCodecID codec_id, int codec_profile, int width, int height){
load_vaapi();
if (!vaapi_ctx){
return NULL;
}
//this section is only used to see if VAAPI supports our codec, without VAAPI we can still ask libavcodec to do it, but we won't known
//if it's going to work, this will result in is just failing if we try it and it's not supported
#ifdef HAVE_VAAPI
AVVAAPIDeviceContext* hwctx = reinterpret_cast<AVVAAPIDeviceContext*>((reinterpret_cast<AVHWDeviceContext*>(vaapi_ctx->data))->hwctx);
//query VAAPI profiles for this codec
const AVCodecDescriptor *codec_desc;
codec_desc = avcodec_descriptor_get(codec_id);
if (!codec_desc) {
return NULL;
}
VAProfile profile = get_va_profile(hwctx, codec_id, codec_profile);
//if we couldn't find a matching profile we bail
if (profile == VAProfileNone){
const char* codec_cstr = avcodec_get_name(codec_id);
const char* profile_cstr = avcodec_profile_name(codec_id, codec_profile);
std::string codec_name = "Unknown";
if (codec_cstr != NULL){
codec_name = std::string(codec_cstr);
}
std::string profile_name = "Unknown";
if (profile_cstr != NULL){
profile_name = std::string(profile_cstr);
}
LINFO("VA-API does not support this codec (" + codec_name + "/" + profile_name + "), no profile found");
return NULL;
}
#endif
bool found = false;
AVHWFramesConstraints* c = av_hwdevice_get_hwframe_constraints(vaapi_ctx, NULL);
if (!c){
return NULL;
}
//check if this is supported
if (c->min_width <= width || c->max_width >= width ||
c->min_height <= height || c->max_height >= height){
//we assume the pixel formats are ok for us
found = true;
}
av_hwframe_constraints_free(&c);
return found;
}
AVBufferRef *CFFUtil::get_vaapi_ctx(AVCodecID codec_id, int codec_profile, int width, int height){
if (have_vaapi(codec_id, codec_profile, width, height)){
return av_buffer_ref(vaapi_ctx);
} else {
//not supported
return NULL;
}
}
bool CFFUtil::have_vdpau(AVCodecID codec_id, int codec_profile, int width, int height){
load_vdpau();
if (!vdpau_ctx){
return NULL;
}
#ifdef HAVE_VDPAU
//Check if VDPAU supports this codec
AVVDPAUDeviceContext* hwctx = reinterpret_cast<AVVDPAUDeviceContext*>((reinterpret_cast<AVHWDeviceContext*>(vdpau_ctx->data))->hwctx);
uint32_t max_width, max_height;
VdpBool supported;
VdpDecoderProfile vdpau_profile;
//get profile
int ret = get_vdpau_profile(codec_id, codec_profile, &vdpau_profile);
if (ret){
//something didn't work, don't use VDPAU
return NULL;
}
VdpDecoderQueryCapabilities *vdpau_query_caps;
VdpStatus status = hwctx->get_proc_address(hwctx->device, VDP_FUNC_ID_DECODER_QUERY_CAPABILITIES, reinterpret_cast<void**>(&vdpau_query_caps));
if (status != VDP_STATUS_OK){
return NULL;
}
status = vdpau_query_caps(hwctx->device, vdpau_profile, &supported, NULL, NULL, &max_width, &max_height);
if (status != VDP_STATUS_OK){
return NULL;
}
if (supported != VDP_TRUE){
return NULL;
}
if (static_cast<uint32_t>(width) > max_width || static_cast<uint32_t>(height) > max_height){
return NULL;
}
#endif
bool found = false;
AVHWFramesConstraints* c = av_hwdevice_get_hwframe_constraints(vdpau_ctx, NULL);
//check if this is supported
if (c->min_width <= width || c->max_width >= width ||
c->min_height <= height || c->max_height >= height){
//we assume the pixel formats are ok for us
found = true;
}
av_hwframe_constraints_free(&c);
return found;
}
AVBufferRef *CFFUtil::get_vdpau_ctx(AVCodecID codec_id, int codec_profile, int width, int height){
if (have_vdpau(codec_id, codec_profile, width, height)){
return av_buffer_ref(vdpau_ctx);
} else {
//not supported
return NULL;
}
}
CFFUtil::CFFUtil(void){
vaapi_failed = false;
vdpau_failed = false;
max_ffmpeg_log_level = AV_LOG_VERBOSE;
}
CFFUtil::~CFFUtil(void){
free_hw();
}
void CFFUtil::lock(void){
codec_lock.lock();
}
void CFFUtil::unlock(void){
codec_lock.unlock();
}
void CFFUtil::free_hw(void){
free_vdpau();
free_vaapi();
}
#ifdef HAVE_VDPAU
//borrowed from FFMPeg's vdpau.c, deprecated so we'll do it ourselves
int CFFUtil::get_vdpau_profile(const AVCodecID codec_id, const int codec_profile, VdpDecoderProfile *profile){
#define PROFILE(prof) \
do { \
*profile = VDP_DECODER_PROFILE_##prof; \
return 0; \
} while (0)
switch (codec_id) {
case AV_CODEC_ID_MPEG1VIDEO: PROFILE(MPEG1);
case AV_CODEC_ID_MPEG2VIDEO:
switch (codec_profile) {
case FF_PROFILE_MPEG2_MAIN: PROFILE(MPEG2_MAIN);
case FF_PROFILE_MPEG2_SIMPLE: PROFILE(MPEG2_SIMPLE);
default: return AVERROR(EINVAL);
}
case AV_CODEC_ID_H263: PROFILE(MPEG4_PART2_ASP);
case AV_CODEC_ID_MPEG4:
switch (codec_profile) {
case FF_PROFILE_MPEG4_SIMPLE: PROFILE(MPEG4_PART2_SP);
case FF_PROFILE_MPEG4_ADVANCED_SIMPLE: PROFILE(MPEG4_PART2_ASP);
default: return AVERROR(EINVAL);
}
case AV_CODEC_ID_H264:
switch (codec_profile & ~FF_PROFILE_H264_INTRA) {
case FF_PROFILE_H264_BASELINE: PROFILE(H264_BASELINE);
case FF_PROFILE_H264_CONSTRAINED_BASELINE:
case FF_PROFILE_H264_MAIN: PROFILE(H264_MAIN);
case FF_PROFILE_H264_HIGH: PROFILE(H264_HIGH);
#ifdef VDP_DECODER_PROFILE_H264_EXTENDED
case FF_PROFILE_H264_EXTENDED: PROFILE(H264_EXTENDED);
#endif
default: return AVERROR(EINVAL);
}
case AV_CODEC_ID_WMV3:
case AV_CODEC_ID_VC1:
switch (codec_profile) {
case FF_PROFILE_VC1_SIMPLE: PROFILE(VC1_SIMPLE);
case FF_PROFILE_VC1_MAIN: PROFILE(VC1_MAIN);
case FF_PROFILE_VC1_ADVANCED: PROFILE(VC1_ADVANCED);
default: return AVERROR(EINVAL);
}
default:
return AVERROR(EINVAL);
}
return AVERROR(EINVAL);
}
#endif
AVBufferRef *CFFUtil::get_opencl_ctx(AVCodecID codec_id, int codec_profile, int width, int height){
if (have_opencl(codec_id, codec_profile, width, height)){
return av_buffer_ref(opencl_ctx);
} else {
//not supported
return NULL;
}
}
bool CFFUtil::have_opencl(AVCodecID codec_id, int codec_profile, int width, int height){
load_opencl();
if (!opencl_ctx){
return NULL;
}
bool found = false;
AVHWFramesConstraints* c = av_hwdevice_get_hwframe_constraints(opencl_ctx, NULL);
if (!c){
return NULL;
}
//check if this is supported
if (c->min_width <= width || c->max_width >= width ||
c->min_height <= height || c->max_height >= height){
//we assume the pixel formats are ok for us
found = true;
}
av_hwframe_constraints_free(&c);
return found;
}
void CFFUtil::load_opencl(void){
if (opencl_ctx || opencl_failed || vaapi_failed){
return;//quick check, return if not required
}
load_vaapi();//vaapi is required for opencl as we derive it from our opencl instance
lock();//lock and re-check (for races)
if (opencl_ctx || opencl_failed || !vaapi_ctx || vaapi_failed){
unlock();
return;//don't double alloc it
}
//this maps opencl to vaapi
int ret = av_hwdevice_ctx_create_derived(&opencl_ctx, AV_HWDEVICE_TYPE_OPENCL, vaapi_ctx, 0);
if (ret < 0) {
opencl_ctx = NULL;
opencl_failed = true;
unlock();
return;
}
//this maps opencv to opencl
#if defined(HAVE_OPENCV) && defined(HAVE_OPENCL)
//opencv must use this context
AVOpenCLDeviceContext * ocl_device_ctx = get_opencl_ctx_from_device(opencl_ctx);
size_t param_value_size;
//Get context properties
clGetContextInfo(ocl_device_ctx->context, CL_CONTEXT_PROPERTIES, 0, NULL, ¶m_value_size);
std::vector<cl_context_properties> props(param_value_size/sizeof(cl_context_properties));
clGetContextInfo(ocl_device_ctx->context, CL_CONTEXT_PROPERTIES, param_value_size, props.data(), NULL);
//Find the platform prop
cl_platform_id platform = 0;
for (int i = 0; props[i] != 0; i = i + 2) {
if (props[i] == CL_CONTEXT_PLATFORM) {
platform = reinterpret_cast<cl_platform_id>(props[i + 1]);
}
}
// Get the name for the platform
clGetPlatformInfo(platform, CL_PLATFORM_NAME, 0, NULL, ¶m_value_size);
std::vector <char> platform_name(param_value_size);
clGetPlatformInfo(platform, CL_PLATFORM_NAME, param_value_size, platform_name.data(), NULL);
//Finally: attach the context to OpenCV
cv::ocl::attachContext(platform_name.data(), platform, ocl_device_ctx->context, ocl_device_ctx->device_id);
#endif
unlock();
}
void CFFUtil::free_opencl(void){
lock();
av_buffer_unref(&opencl_ctx);
opencl_failed = false;
unlock();
}
AVVAAPIDeviceContext *get_vaapi_ctx_from_device(AVBufferRef *buf){
if (!buf || !buf->data){
return NULL;
}
AVHWDeviceContext *device = reinterpret_cast<AVHWDeviceContext*>(buf->data);
if (device->type != AV_HWDEVICE_TYPE_VAAPI){
return NULL;
}
return static_cast<AVVAAPIDeviceContext*>(device->hwctx);
}
AVVAAPIDeviceContext *get_vaapi_ctx_from_frames(AVBufferRef *buf){
if (!buf || !buf->data){
return NULL;
}
AVHWFramesContext *frames = reinterpret_cast<AVHWFramesContext*>(buf->data);
return get_vaapi_ctx_from_device(frames->device_ref);
}
#ifdef HAVE_OPENCL
AVOpenCLDeviceContext *get_opencl_ctx_from_device(AVBufferRef *buf){
if (!buf || !buf->data){
return NULL;
}
AVHWDeviceContext *device = reinterpret_cast<AVHWDeviceContext*>(buf->data);
if (device->type != AV_HWDEVICE_TYPE_OPENCL){
return NULL;
}
return static_cast<AVOpenCLDeviceContext*>(device->hwctx);
}
#endif
#ifdef HAVE_OPENCL
AVOpenCLDeviceContext *get_opencl_ctx_from_frames(AVBufferRef *buf){
if (!buf || !buf->data){
return NULL;
}
AVHWFramesContext *frames = reinterpret_cast<AVHWFramesContext*>(buf->data);
return get_opencl_ctx_from_device(frames->device_ref);
}
#endif
bool CFFUtil::have_v4l2(AVCodecID codec_id, int codec_profile, int width, int height){
#ifdef HAVE_V4L2
//we need to check all devices
DIR *dirp = opendir("/dev");
if (!dirp){
LWARN("Can't open /dev");
return false;
}
bool ret = false;
struct dirent *entry;
while (!ret && (entry = readdir(dirp))){
std::string dev_name = std::string(entry->d_name);
if (dev_name.find("video") != 0){
continue;
}
int fd = v4l2_open(std::string("/dev/" + dev_name).c_str(), O_RDWR | O_NONBLOCK, 0);
if (fd < 0){
LWARN("Cannot open /dev/" + dev_name + " (" + std::to_string(errno) + ")");
continue;
}
ret = have_v4l2_dev(fd, codec_id, codec_profile, width, height);
if (v4l2_close(fd)){
LWARN("close() failed (" + std::to_string(errno) + ")");
}
}
closedir(dirp);
LDEBUG("Completed dev check");
return ret;
//query pixel formats first
#else
return false;//no v4l2 enabled
#endif
}
#ifdef HAVE_V4L2
bool CFFUtil::have_v4l2_dev(int dev, AVCodecID codec_id, int codec_profile, int width, int height){
bool ret = false;
//check if it supports M2M
struct v4l2_capability caps;
if (!vioctl(dev, VIDIOC_QUERYCAP, &caps)){
return false;
}
LDEBUG("Found V4L2 device " + std::string(reinterpret_cast<char*>(caps.card)) + "[" + std::string(reinterpret_cast<char*>(caps.bus_info)) + "]");
bool splane = caps.device_caps & V4L2_CAP_VIDEO_M2M;
bool mplane = caps.device_caps & V4L2_CAP_VIDEO_M2M_MPLANE;
if (!splane && !mplane){
LDEBUG("...Does not support M2M");
return false;
}
struct v4l2_fmtdesc pixfmt;
for (int pix_idx = 0;; pix_idx++){
pixfmt.index = pix_idx;
pixfmt.type = splane ? V4L2_BUF_TYPE_VIDEO_OUTPUT : V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
if (!vioctl(dev, VIDIOC_ENUM_FMT, &pixfmt)){
if (splane && mplane){
//not sure if anyone supports both on the same driver, but we do!
//this repeates the loop for mplane
splane = false;
pix_idx = -1;
continue;
}
break;//hit the end
}
if (pixfmt.flags & V4L2_FMT_FLAG_EMULATED){
continue;//we don't care about SW formats
}
if (!is_v4l2_hw_codec(codec_id, pixfmt.pixelformat)){
continue;//now the requested codec, irrelevant
}
struct v4l2_frmsizeenum frsize;
for (int fr_idx = 0; ; fr_idx++){
frsize.index = fr_idx;
frsize.pixel_format = pixfmt.pixelformat;
if (!vioctl(dev, VIDIOC_ENUM_FRAMESIZES, &frsize)){
break;
}
if (frsize.type == V4L2_FRMSIZE_TYPE_DISCRETE){
if (width == static_cast<int>(frsize.discrete.width) && height == static_cast<int>(frsize.discrete.height)){
return true;
}
break;//DISCRETE is only one
} else if (frsize.type == V4L2_FRMSIZE_TYPE_STEPWISE || frsize.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) {
if (width >= static_cast<int>(frsize.stepwise.min_width) &&
width <= static_cast<int>(frsize.stepwise.max_width) &&
width % frsize.stepwise.step_width == 0 &&
height >= static_cast<int>(frsize.stepwise.min_height) &&
height <= static_cast<int>(frsize.stepwise.max_height) &&
height % frsize.stepwise.step_height == 0){
return true;
}
} else {
LWARN("Unknown V4L2 Type - " + std::to_string(frsize.type));
return false;
}
}
}
return ret;
}
#endif
#ifdef HAVE_V4L2
bool CFFUtil::vioctl(int fh, int request, void *arg){
int r;
do {
r = v4l2_ioctl(fh, request, arg);
} while (r == -1 && ((errno == EINTR) || (errno == EAGAIN)));
if (r == -1){
return false;
}
return true;
}
#endif
#ifdef HAVE_V4L2
bool CFFUtil::is_v4l2_hw_codec(const AVCodecID av_codec, const uint32_t v4l2_pix_fmt){
//i hate these things
//we only use this to determine if FFMpeg will probably succeed, so it doesn't have to be 100% accurate
switch (av_codec){
case AV_CODEC_ID_MPEG1VIDEO:
return v4l2_pix_fmt == V4L2_PIX_FMT_MPEG1;
case AV_CODEC_ID_MPEG2VIDEO:
return v4l2_pix_fmt == V4L2_PIX_FMT_MPEG2;
case AV_CODEC_ID_H263:
return v4l2_pix_fmt == V4L2_PIX_FMT_H263;
case AV_CODEC_ID_H264:
return v4l2_pix_fmt == V4L2_PIX_FMT_H264 ||
v4l2_pix_fmt == V4L2_PIX_FMT_H264_NO_SC ||
v4l2_pix_fmt == V4L2_PIX_FMT_H264_MVC;
case AV_CODEC_ID_MPEG4:
return v4l2_pix_fmt == V4L2_PIX_FMT_MPEG4 ||
v4l2_pix_fmt == V4L2_PIX_FMT_XVID;
case AV_CODEC_ID_VC1:
return v4l2_pix_fmt == V4L2_PIX_FMT_VC1_ANNEX_G ||
v4l2_pix_fmt == V4L2_PIX_FMT_VC1_ANNEX_L;
case AV_CODEC_ID_HEVC:
return v4l2_pix_fmt == V4L2_PIX_FMT_HEVC;
case AV_CODEC_ID_VP8:
return v4l2_pix_fmt == V4L2_PIX_FMT_VP8;
case AV_CODEC_ID_VP9:
return v4l2_pix_fmt == V4L2_PIX_FMT_VP9;
default:
return false;
}
}
#endif
#ifdef HAVE_VAAPI
AVPixelFormat CFFUtil::get_pix_fmt_from_va(const VAImageFormat &fmt){
for (unsigned int i = 0; i < (sizeof(vaapi_format_map)/sizeof(vaapi_format_map[0])); i++){
if (fmt.fourcc == vaapi_format_map[i].va){
return vaapi_format_map[i].ff;
}
}
return AV_PIX_FMT_NONE;
}
#endif
#ifdef HAVE_VAAPI
VAProfile CFFUtil::get_va_profile(AVVAAPIDeviceContext* hwctx, AVCodecID codec_id, int codec_profile){
VAProfile profile, *profile_list;
int profile_count;
VAStatus vas;
profile = VAProfileNone;
profile_count = vaMaxNumProfiles(hwctx->display);
profile_list = new VAProfile[profile_count];
if (!profile_list){
return VAProfileNone;
}
vas = vaQueryConfigProfiles(hwctx->display, profile_list, &profile_count);
if (vas != VA_STATUS_SUCCESS) {
delete[] profile_list;
return VAProfileNone;
}
//search all known codecs to see if there is a matching profile
for (unsigned int i = 0; i < FF_ARRAY_ELEMS(vaapi_profile_map); i++) {
if (codec_id != vaapi_profile_map[i].codec_id){
continue;
}
for (int j = 0; j < profile_count; j++) {
if (vaapi_profile_map[i].va_profile == profile_list[j] &&
vaapi_profile_map[i].codec_profile == codec_profile) {
profile = profile_list[j];
break;//exact found, we are done
} else if (vaapi_profile_map[i].va_profile == profile_list[j]){
profile = profile_list[j];//inexact found
}
}
}
delete[] profile_list;
return profile;
}
#endif
int CFFUtil::get_ff_log_level(void) const{
return max_ffmpeg_log_level;
}
void CFFUtil::set_ff_log_level(int lvl){
if (lvl < AV_LOG_QUIET || lvl > AV_LOG_TRACE){
LINFO("ffmpeg-log-level appears unreasonable, typically between " + std::to_string(AV_LOG_QUIET) + " and " + std::to_string(AV_LOG_TRACE));
}
max_ffmpeg_log_level = lvl;
av_log_set_level(lvl);
}
| 32,008
|
C++
|
.cpp
| 877
| 30.521095
| 149
| 0.610433
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,955
|
file_manager.cpp
|
edman007_chiton/file_manager.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "file_manager.hpp"
#include "util.hpp"
#include "system_controller.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/statvfs.h>
#include <dirent.h>
//static globals
std::mutex FileManager::cleanup_mtx;//lock when cleanup is in progress, locks just the clean_disk() to prevent iterating over the same database results twice
std::atomic<long long> FileManager::reserved_bytes(0);
FileManager::FileManager(SystemController &sys) : FileManager(sys, sys.get_sys_cfg()) {
//no-op, calls detailed version
}
FileManager::FileManager(SystemController &sys, Config &cfg) : sys(sys), db(sys.get_db()), cfg(cfg) {
bytes_per_segment = 1024*1024;//1M is our default guess
min_free_bytes = -1;
}
void FileManager::init(void){
//we correct this if it's wrong now, so we can assume it's always right
const std::string &ext = cfg.get_value("output-extension");
if (ext != ".ts" && ext != ".mp4"){
LWARN("output-extension MUST be .ts or .mp4, using .mp4");
cfg.set_value("output-extension", ".mp4");
}
}
std::string FileManager::get_next_path(long int &file_id, int camera, const struct timeval &start_time, bool extend_file /* = false */){
const std::string base = get_output_dir();
std::string dir = get_date_path(camera, start_time);
std::string ptime = std::to_string(Util::pack_time(start_time));
std::string name;
if (extend_file && !last_filename.empty()){
name = last_filename;
dir = last_dir;
} else {
name = ptime;
last_filename = name;
last_dir = dir;
}
//make sure dir exists
std::string path = base + dir;
mkdir_recursive(path);
const std::string &ext = cfg.get_value("output-extension");
std::string sql = "INSERT INTO videos (path, starttime, camera, extension, name) VALUES ('" + db.escape(dir + "/") + "'," + ptime + ", " + std::to_string(camera) + ",'"
+ db.escape(ext) + "'," + name + " )";
DatabaseResult* res = db.query(sql, NULL, &file_id);
delete res;
return path + "/" + name + ext;
}
std::string FileManager::get_export_path(long int export_id, int camera, const struct timeval &start_time){
const std::string base = get_output_dir();
const std::string dir = get_date_path(camera, start_time);
//make sure dir exists
std::string path = base + dir;
mkdir_recursive(path);
std::string sql = "UPDATE exports SET path = '" + dir + "/' WHERE id = " + std::to_string(export_id);
DatabaseResult* res = db.query(sql);
delete res;
return path + "/" + std::to_string(export_id) + EXPORT_EXT;
}
//returns the path for the file referenced as id
std::string FileManager::get_path(long long name, const std::string &db_path, const std::string &ext){
std::string path;
path = db_path + std::to_string(name) + ext;
return get_output_dir() + path;
}
bool FileManager::mkdir_recursive(std::string path){
struct stat buf;
if (stat(path.c_str(), &buf)){
//does not exist, make it if the parent exists:
auto new_len = path.find_last_of("/", path.length() - 1);
auto parent_dir = path.substr(0, new_len);
if (new_len != std::string::npos || !parent_dir.compare("")){
if (!mkdir_recursive(parent_dir)){
return false;
}
}
if (mkdir(path.c_str(), 0755)){
LERROR("Cannot make directory " + path + " (errno: " + std::to_string(errno) + ")");
return false;
}
return true;
} else if (buf.st_mode | S_IFDIR) {
return true;
}
return false;
}
void FileManager::clean_disk(void){
cleanup_mtx.lock();
long long target_clear = get_target_free_bytes();
if (target_clear){
LINFO("Cleaning the disk, removing " + std::to_string(target_clear));
//estimate the number of segments, add 10
long segment_count = target_clear/bytes_per_segment + 10;
std::string sql = "SELECT v.camera, v.path, c.value, MIN(v.starttime), v.extension, v.name FROM videos AS v LEFT JOIN config AS c ON v.camera=c.camera AND c.name = 'output-dir' "
" GROUP BY v.name, v.camera HAVING MAX(v.locked) = 0 ORDER BY starttime ASC LIMIT " + std::to_string(segment_count);
segment_count = 0;
long long actual_segment_bytes = 0;
unsigned long long oldest_record = 0;
DatabaseResult* res = db.query(sql);
while (target_clear > 0 && res && res->next_row()){
segment_count++;
long long rm_size = 0;//size of file deleted
const std::string &name = res->get_field(5);
rm_size = rm_segment(res->get_field(2), res->get_field(1), name, res->get_field(4));
if (rm_size > 0){
target_clear -= rm_size;
actual_segment_bytes += rm_size;
}
//delete it from the database
sql = "DELETE FROM videos WHERE name = " + res->get_field(5) + " AND camera = " + res->get_field(0);
DatabaseResult* del_res = db.query(sql);
delete del_res;
//record the starttime of this
oldest_record = res->get_field_ll(3);
}
delete res;
if (segment_count > 0){
bytes_per_segment = actual_segment_bytes/segment_count;
if (bytes_per_segment < 100){
//probably some issue, set to 1M
LINFO("Deleting Segments, average segment size appears to be below 100b");
bytes_per_segment = 1024*1024;
}
LDEBUG("Average segment was " + std::to_string(bytes_per_segment) + " bytes");
//clean the images
target_clear -= clean_images(oldest_record);
clean_events(oldest_record);
}
if (target_clear > 0){
//this may mean that we are not going to clear out the reserved space
//but we don't add it to the reserved count because it could be more than the reserved space
//we don't want it to snowball so we just print a warning
LWARN(std::to_string(target_clear) + " bytes were not removed from the disk as requested");
}
}
cleanup_mtx.unlock();
}
long long FileManager::rm_segment(const std::string &base, const std::string &path, const std::string &id, const std::string &ext){
long long filesize = 0;
std::string target_file = path;
target_file += id + ext;
filesize = rm_file(target_file, base);
return filesize;
}
void FileManager::delete_broken_segments(void){
LINFO("Removing Broken Segments");
//get the current time, plus some time
struct timeval curtime;
Util::get_videotime(curtime);
long long broken_offset = cfg.get_value_ll("broken-time-offset");
if (broken_offset > 0){
curtime.tv_sec += broken_offset;
}
std::string future_time = std::to_string(Util::pack_time(curtime));
std::string sql = "SELECT v.name, v.path, c.value, v.extension, v.camera, v.starttime FROM videos AS v LEFT JOIN config AS c ON v.camera=c.camera AND c.name = 'output-dir' WHERE "
"v.endtime IS NULL OR v.endtime < v.starttime OR v.starttime > " + future_time;
DatabaseResult* res = db.query(sql);
if (res && res->num_rows() > 0){
LWARN("Found " + std::to_string(res->num_rows()) + " broken segments, deleting them");
}
while (res && res->next_row()){
const std::string &name = res->get_field(0);
//delete this segment from the database
sql = "DELETE FROM videos WHERE starttime = " + res->get_field(5) + " AND name = " + name + " AND camera = " + res->get_field(4);
DatabaseResult* del_res = db.query(sql);
delete del_res;
//check if that was the last segment in this file, and only if it is, delete it
sql = "SELECT COUNT(*) FROM videos WHERE name = " + name + " AND camera = " + res->get_field(4);
del_res = db.query(sql);
if (res->get_field_long(0) == 0){
rm_segment(res->get_field(2), res->get_field(1), name, res->get_field(3));
}
delete del_res;
}
delete res;
}
long long FileManager::get_target_free_bytes(void){
long long free_bytes = get_free_bytes();
long long min_free = get_min_free_bytes();
min_free += reserved_bytes.exchange(0);
if (free_bytes < min_free){
return min_free - free_bytes;
}
return 0;
}
long long FileManager::get_free_bytes(void){
std::string check_path = cfg.get_value("output-dir");
struct statvfs info;
if (!statvfs(check_path.c_str(), &info)){
long long free_bytes = info.f_bsize * info.f_bavail;
return free_bytes;
} else {
LWARN("Failed to get filesystem info for " + check_path + " ( " +std::to_string(errno)+" ) will assume it is full");
}
return 0;
}
long long FileManager::get_min_free_bytes(void){
if (min_free_bytes > 0){
return min_free_bytes;
}
//we only perform this syscall on the first call
long long min_free = cfg.get_value_ll("min-free-space");
if (cfg.get_value("min-free-space").find('%') != std::string::npos){
std::string check_path = cfg.get_value("output-dir");
struct statvfs info;
if (!statvfs(check_path.c_str(), &info)){
double min_freed = cfg.get_value_double("min-free-space");//absolute bytes are set
min_freed /= 100;
long long total_bytes = info.f_bsize * (info.f_blocks - info.f_bfree + info.f_bavail);//ignore root's space we can't use when calculating filesystem space
min_free = total_bytes * min_freed;
if (min_free < 0){
min_free = 0;//they set something wrong...I don't know, this will result in the defualt
}
} else {
min_free = 0;//use the default
}
}
//absolute byte mode
if (min_free <= 1024){
LWARN("min-free-space was set too small");
min_free = DEFAULT_MIN_FREE_SPACE;
}
min_free_bytes = min_free;
return min_free_bytes;
}
void FileManager::rmdir_r(const std::string &path){
LINFO("Deleting " + path);
DIR *dir = opendir(path.c_str());
if (dir){
struct dirent* dir_info;
bool dir_is_empty = true;
while ((dir_info = readdir(dir))){
if (std::string(dir_info->d_name) == "." || std::string(dir_info->d_name) == ".."){
continue;
}
dir_is_empty = false;
break;
}
closedir(dir);
if (dir_is_empty && path != get_output_dir()){
//dir is empty, delete it
if (rmdir(path.c_str())){
LWARN("Failed to delete empty directory " + path + " (" + std::to_string(errno) + ")");
} else {
if (path.length() > 2){
std::string parent_dir = path.substr(0, path.find_last_of('/', path.length() - 2));
rmdir_r(parent_dir);
}
}
}
} else {
LWARN("Could not open directory " + path + " to delete it (" +std::to_string(errno) + ")");
}
}
bool FileManager::update_file_metadata(long int file_id, struct timeval &end_time, long long end_byte, const StreamWriter &out_file,
long long start_byte /*= 0 */, long long init_len /*= -1*/){
long affected;
std::string ptime = std::to_string(Util::pack_time(end_time));
std::string sql = "UPDATE videos SET endtime = " + ptime;
if (init_len == -1){
init_len = out_file.get_init_len();
}
if (init_len >= 0){
sql += ", init_byte = " + std::to_string(init_len);
}
if (start_byte >= 0){
sql += ", start_byte = " + std::to_string(start_byte);
}
if (end_byte > 0){
sql += ", end_byte = " + std::to_string(end_byte);
}
if (out_file.get_codec_str() != ""){
sql += ", codec = '" + db.escape(out_file.get_codec_str()) + "'";
}
if (out_file.have_video() && out_file.have_audio()){
sql += ", av_type = 'audiovideo'";
} else if (out_file.have_video()) {
sql += ", av_type = 'video'";
} else if (out_file.have_audio()){
sql += ", av_type = 'audio'";
}
if (out_file.get_width() > 0){
sql += ", width = " + std::to_string(out_file.get_width());
}
if (out_file.get_height() > 0){
sql += ", height = " + std::to_string(out_file.get_height());
}
if (out_file.get_framerate() > 0){
sql += ", framerate = " + std::to_string(out_file.get_framerate());
}
sql += " WHERE id = " + std::to_string(file_id);
DatabaseResult* res = db.query(sql, &affected, NULL);
delete res;
return affected == 1;
}
long long FileManager::rm(const std::string &path){
struct stat statbuf;
if (!stat(path.c_str(), &statbuf)){
//and delete it
LINFO("Deleting " + path);
if (unlink(path.c_str())){
LWARN("Cannot delete file " + path + " (" + std::to_string(errno) + ")");
return -2;
}
return statbuf.st_size;
} else {
LWARN("Cannot stat " + path + " (" + std::to_string(errno) + ")");
return -1;
}
}
long long FileManager::get_filesize(const std::string &path){
struct stat statbuf;
if (!stat(path.c_str(), &statbuf)){
return statbuf.st_size;
}
return -1;
}
long long FileManager::rm_file(const std::string &path, const std::string &base/* = std::string("NULL")*/){
std::string real_base = get_real_base(base);
long long filesize = rm(real_base + path);
std::string dir = real_base;
dir += path.substr(0, path.find_last_of('/', path.length()));
rmdir_r(dir);
return filesize;
}
std::string FileManager::get_date_path(int camera, const struct timeval &start_time){
VideoDate date;
Util::get_time_parts(start_time, date);
std::string dir = std::to_string(camera) + "/"
+ std::to_string(date.year) + "/"
+ std::to_string(date.month) + "/"
+ std::to_string(date.day) + "/"
+ std::to_string(date.hour);
return dir;
}
std::string FileManager::get_output_dir(void){
const std::string base = cfg.get_value("output-dir");
//make sure the config value is correct
std::string modified_base = std::string(base);
if (modified_base == ""){
modified_base = "./";
} else if (modified_base.back() != '/'){
modified_base += "/";
}
return modified_base;
}
bool FileManager::reserve_bytes(long long bytes, int camera){
auto free_space = get_free_bytes();
auto min_space = get_min_free_bytes();
reserved_bytes += bytes;
free_space -= min_space/2;
free_space -= reserved_bytes;
//if this reservation would eat up more than half our free space we clean the disk
if (free_space < 0){
clean_disk();
return true;
}
//otherwise we leave it as is
return true;
}
std::ofstream FileManager::get_fstream_write(const std::string &name, const std::string &path /* = "" */, const std::string &base/* = "NULL" */){
std::ofstream s;
std::string real_base = get_real_base(base);
mkdir_recursive(real_base + path);
s.open(real_base + path + name, std::ios::binary | std::fstream::out | std::fstream::trunc);
if (!s.is_open()){
LWARN("Failed to open '" + real_base + path + name + "', " + std::to_string(errno));
}
return s;
}
std::ifstream FileManager::get_fstream_read(const std::string &name, const std::string &path /* = "" */, const std::string &base/* = "NULL"*/){
std::ifstream s;
std::string real_base = get_real_base(base);
s.open(real_base + path + name, std::ios::binary | std::fstream::in);
if (!s.is_open()){
LWARN("Failed to open '" + real_base + path + name + "', " + std::to_string(errno));
}
return s;
}
std::string FileManager::get_real_base(const std::string base){
std::string real_base;
if (base == "NULL"){
real_base = get_output_dir();
} else if (real_base.back() != '/'){
real_base += "/";
}
return real_base;
}
bool FileManager::get_image_path(std::string &path, std::string &name, const std::string &extension, const struct timeval *start_time /* = NULL */, long *file_id /* = NULL */){
if (start_time != NULL){
path = get_date_path(cfg.get_value_int("camera-id"), *start_time) + "/";
if (name != ""){
name += "-";
}
std::string ptime = std::to_string(Util::pack_time(*start_time));
std::string sql = "INSERT INTO images (camera, path, prefix, extension, starttime) VALUES (" +
cfg.get_value("camera-id") + ",'" + db.escape(path) + "','" + db.escape(name) + "','" + db.escape(extension) + "'," + ptime + ")";
long db_file_id = 0;
DatabaseResult* res = db.query(sql, NULL, &db_file_id);
if (res){
name += std::to_string(db_file_id) + extension;
if (file_id){
*file_id = db_file_id;
}
delete res;
} else {
return false;
}
} else {
name += extension;
}
return true;
}
long long FileManager::clean_images(unsigned long long start_time){
if (start_time == 0){
return 0;//bail if it's invalid
}
long long bytes_deleted = 0;
std::string sql = "SELECT id, path, prefix, extension, c.value FROM images as i LEFT JOIN config AS c ON i.camera=c.camera AND c.name = 'output-dir' "
" WHERE starttime < " + std::to_string(start_time);
DatabaseResult *res = db.query(sql);
while (res && res->next_row()){
std::string img_id = res->get_field(0);
std::string path = res->get_field(1);
std::string name = res->get_field(2) + img_id + res->get_field(3);
std::string base = res->get_field(4);
long long del_bytes = rm_file(path + name, base);
if (del_bytes > 0){
bytes_deleted++;
}
LWARN("Deleting image " + name);
//delete it from the database
sql = "DELETE FROM images WHERE id = " + img_id;
DatabaseResult* del_res = db.query(sql);
delete del_res;
}
delete res;
return bytes_deleted;
}
long FileManager::clean_events(unsigned long long start_time){
if (start_time == 0){
return 0;//bail if it's invalid
}
long events_deleted = 0;
std::string sql ="DELETE FROM events WHERE starttime < " + std::to_string(start_time);
DatabaseResult *res = db.query(sql, &events_deleted, NULL);
delete res;
return events_deleted;
}
| 19,603
|
C++
|
.cpp
| 471
| 34.726115
| 186
| 0.590644
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,956
|
system_controller.cpp
|
edman007_chiton/system_controller.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "system_controller.hpp"
#include "util.hpp"
#include "mariadb.hpp"
#include "camera.hpp"
#include <thread>
#include <stdlib.h>
#include "chiton_ffmpeg.hpp"
#include "database_manager.hpp"
#include "remote.hpp"
#include "export.hpp"
#include <atomic>
#include <chrono>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <functional>
SystemController::SystemController(Config &args) :
system_args(args),
db(std::unique_ptr<Database>(new MariaDB())),
fm(*this),
expt(*this),
remote(*this),
exit_requested(false),
reload_requested(false){
}
SystemController::~SystemController(){
}
int SystemController::run(void){
int ret = 0;
while (!exit_requested && !ret){
reload_requested = false;
ret = run_instance();
}
return ret;
}
int SystemController::run_instance(void){
if (!cfg.load_config(system_args.get_value("cfg-path"))){
exit_requested = true;//this is a fatal error
return SYS_EXIT_CFG_ERROR;
}
//set the correct verbosity if it is not supplied on the command line
if (system_args.get_value("verbosity") == "" && cfg.get_value("verbosity") != ""){
Util::set_log_level(cfg.get_value_int("verbosity"));
}
if (db->connect(cfg.get_value("db-host"), cfg.get_value("db-database"), cfg.get_value("db-user"), cfg.get_value("db-password"),
cfg.get_value_int("db-port"), cfg.get_value("db-socket"))){
LFATAL("Could not connect to the database! Check your configuration");
exit_requested = true;
return SYS_EXIT_DB_ERROR;
}
DatabaseManager dbm(*db);
if (!dbm.check_database()){
//this is fatal, cannot get the database into a usable state
exit_requested = true;
return SYS_EXIT_DB_UPDATE_ERROR;
}
launch_cams();//launch all configured cameras
loop();//main loop
remote.shutdown();
cams_lock.lock();
//shutdown all cams
for (auto &c : cams){
c.stop();
}
for (auto &c : cams){
c.join();
}
//destruct everything
cams.clear();
cam_set_lock.lock();
stop_cams_list.clear();
start_cams_list.clear();
cam_set_lock.unlock();
cams_lock.unlock();
db->close();
return SYS_EXIT_SUCCESS;
}
Config& SystemController::get_sys_cfg(void){
return cfg;
}
Database& SystemController::get_db(void){
return *db;
}
Export& SystemController::get_export(void){
return expt;
}
Remote& SystemController::get_remote(void){
return remote;
}
FileManager& SystemController::get_fm(void){
return fm;
}
void SystemController::launch_cams(void){
//load the default config from the database
DatabaseResult *res = db->query("SELECT name, value FROM config WHERE camera = -1");
while (res && res->next_row()){
cfg.set_value(res->get_field(0), res->get_field(1));
}
delete res;
//load system config
load_sys_cfg(cfg);
Util::load_colors(cfg);
if (cfg.get_value_int("log-color-enabled") || system_args.get_value_int("log-color-enabled") ){
Util::enable_color();
} else {
Util::disable_color();
}
fm.init();
remote.init();
//Launch all cameras
res = db->query("SELECT camera FROM config WHERE camera != -1 AND name = 'active' AND value = '1' GROUP BY camera");
while (res && res->next_row()){
start_cam(res->get_field_long(0));//delayed start
}
delete res;
//delete broken segments
fm.delete_broken_segments();
}
void SystemController::loop(){
//camera maintance
do {
//we should check if they are running and restart anything that froze
cams_lock.lock();
//clear the list of cameras in startup
cam_set_lock.lock();
startup_cams_list.clear();
cam_set_lock.unlock();
for (auto &c : cams){
if (c.ping()){
int id = c.get_id();
if (!c.in_startup()){
LWARN("Lost connection to cam " + std::to_string(id) + ", restarting...");
restart_cam(id);
} else {
LWARN("Camera stalled, but appears to be in startup");
cam_set_lock.lock();
startup_cams_list.insert(id);
cam_set_lock.unlock();
}
}
}
cam_set_lock.lock();
stop_cams();
start_cams();
cam_set_lock.unlock();
cams_lock.unlock();
fm.clean_disk();
expt.check_for_jobs();
std::this_thread::sleep_for(std::chrono::seconds(10));
} while (!exit_requested && !remote.get_reload_request() && !reload_requested);
}
void SystemController::request_exit(void){
exit_requested = true;
}
void SystemController::request_reload(void){
reload_requested = true;
}
void SystemController::load_sys_cfg(Config &cfg) {
std::string timezone = cfg.get_value("timezone");
if (timezone.compare("")){
LINFO("Setting Timezone to " + timezone);
timezone = "TZ=" + timezone;
auto len = timezone.copy(timezone_env, sizeof timezone_env, 0);
timezone_env[len] = '\0';
putenv(timezone_env);
}
tzset();
//set the history length
Util::set_history_len(cfg.get_value_int("log-history-len"));
//set the ffmpeg log level
gcff_util.set_ff_log_level(cfg.get_value_int("ffmpeg-log-level"));
}
bool SystemController::stop_cam(int id){
cam_set_lock.lock();
auto p = stop_cams_list.insert(id);
cam_set_lock.unlock();
return p.second;
}
bool SystemController::start_cam(int id){
cam_set_lock.lock();
startup_cams_list.insert(id);
auto p = start_cams_list.insert(id);
cam_set_lock.unlock();
return p.second;
}
bool SystemController::restart_cam(int id){
cam_set_lock.lock();
stop_cams_list.insert(id);
auto p = start_cams_list.insert(id);
cam_set_lock.unlock();
return p.second;
}
void SystemController::stop_cams(void){
for (auto &stop : stop_cams_list){
for (auto &c : cams){
if (c.get_id() == stop){
c.stop();
break;
}
}
}
for (auto &join : stop_cams_list){
for (auto it = cams.begin(); it != cams.end(); it++){
auto &c = *it;
if (c.get_id() == join){
c.join();
cams.erase(it);
break;
}
}
}
stop_cams_list.clear();
}
void SystemController::start_cams(void){
for (auto &start : start_cams_list){
//check if cam is already running and refuse to start a duplicate camera
bool dup = false;
for (auto &c : cams){
if (c.get_id() == start){
dup = true;
break;
}
}
if (dup){
LDEBUG("Cam " + std::to_string(start) + " already started");
continue;
}
DatabaseResult *res = db->query("SELECT camera FROM config WHERE camera = '" + std::to_string(start) +
"' AND name = 'active' AND value = '1' LIMIT 1");
if (res && res->next_row()){
LINFO("Loading camera " + std::to_string(res->get_field_long(0)));
cams.emplace_back(*this, res->get_field_long(0));//create camera
auto &cam = cams.back();
cam.start();
}
delete res;
}
start_cams_list.clear();
}
void SystemController::list_state(std::map<int, CAMERA_STATE> &stat){
stat.clear();
//assign all as running
cams_lock.lock();
cam_set_lock.lock();
for (auto &c : cams){
stat[c.get_id()] = CAMERA_STATE::RUNNING;
}
cams_lock.unlock();//unlocking here is ok, but can't be relocked withot unlocking cam_set_lock first
//mark the ones still in startup
for (auto s : startup_cams_list){
stat[s] = CAMERA_STATE::STARTING;
}
//mark the ones stopping
for (auto s : stop_cams_list){
stat[s] = CAMERA_STATE::STOPPING;
}
//mark the ones starting or restarting
for (auto s : start_cams_list){
if (stop_cams_list.find(s) == start_cams_list.end()){
//not on stop list, so starting
stat[s] = CAMERA_STATE::STARTING;
} else {
//on stop and start list, restarting
stat[s] = CAMERA_STATE::RESTARTING;
}
}
cam_set_lock.unlock();
}
bool SystemController::get_camera_status(int id, CameraStatus &status){
bool ret = false;
//special case for -1, it sums all the cameras
if (id == -1){
ret = true;
struct timeval req_time;
Util::get_videotime(req_time);
status = CameraStatus(-1);
status.set_start_time(req_time.tv_sec);//to prevent finding the min time incorrectly
}
cams_lock.lock();
for (auto &c : cams){
if (c.get_id() == id){
status = c.get_status();
ret = true;
break;
} else if (id == -1){
//sum the cameras
status += c.get_status();
}
}
cams_lock.unlock();
return ret;
}
| 10,141
|
C++
|
.cpp
| 315
| 25.669841
| 131
| 0.588422
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,957
|
camera_status.cpp
|
edman007_chiton/camera_status.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "camera_status.hpp"
CameraStatus::CameraStatus(int id) : id(id) {
bytes_written = 0;
bytes_read = 0;
dropped_frames = 0;
start_time = 0;
}
CameraStatus::CameraStatus(const CameraStatus &in){
*this = in;//same as copy operator
}
CameraStatus& CameraStatus::operator=(const CameraStatus &in){
//everything in here is atomics, so this is safe, as this is typically run while in may be modified
//100% synchronizing isn't needed here
id = in.id.load(std::memory_order_relaxed);
bytes_written = in.bytes_written.load(std::memory_order_relaxed);
bytes_read = in.bytes_read.load(std::memory_order_relaxed);
dropped_frames = in.dropped_frames.load(std::memory_order_relaxed);
start_time = in.start_time.load(std::memory_order_relaxed);
return *this;
}
CameraStatus& CameraStatus::operator+=(const CameraStatus &in){
//everything in here is atomics, so this is safe, as this is typically run while in may be modified
//100% synchronizing isn't needed here
//id; //id is not copied
//counters are added
bytes_written.fetch_add(in.bytes_written.load(std::memory_order_relaxed), std::memory_order_relaxed);
bytes_read.fetch_add(in.bytes_read.load(std::memory_order_relaxed), std::memory_order_relaxed);
dropped_frames.fetch_add(in.dropped_frames.load(std::memory_order_relaxed), std::memory_order_relaxed);
//unuiqe are min/max'd
auto old_start = start_time.load(std::memory_order_relaxed);
bool retry = false;
do {
auto in_start = in.start_time.load(std::memory_order_relaxed);
if (in_start < old_start){
retry = !start_time.compare_exchange_weak(old_start, in_start, std::memory_order_release, std::memory_order_relaxed);
}
} while (retry);
return *this;
}
CameraStatus::~CameraStatus(){
//nothing
}
void CameraStatus::add_bytes_written(unsigned int bytes){
bytes_written += bytes;
}
void CameraStatus::add_bytes_read(unsigned int bytes){
bytes_read += bytes;
}
void CameraStatus::add_dropped_frame(void){
dropped_frames++;
}
unsigned int CameraStatus::get_bytes_written(void){
return bytes_written;
}
unsigned int CameraStatus::get_bytes_read(void){
return bytes_read;
}
unsigned int CameraStatus::get_dropped_frames(void){
return dropped_frames;
}
void CameraStatus::set_start_time(time_t start){
start_time = start;
}
time_t CameraStatus::get_start_time(void){
return start_time;
}
int CameraStatus::get_id(void){
return id;
}
| 3,436
|
C++
|
.cpp
| 90
| 34.755556
| 131
| 0.685697
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,958
|
motion_cvdebugshow.cpp
|
edman007_chiton/motion_cvdebugshow.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "motion_cvdebugshow.hpp"
#ifdef HAVE_OPENCV
#ifdef DEBUG
#include "util.hpp"
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
static const std::string algo_name = "cvdebugshow";
MotionCVDebugShow::MotionCVDebugShow(Config &cfg, Database &db, MotionController &controller) : MotionAlgo(cfg, db, controller, algo_name) {
cvmask = NULL;
cvbackground = NULL;
ocv = NULL;
cvdetect = NULL;
}
MotionCVDebugShow::~MotionCVDebugShow(){
cvmask = NULL;//we don't own it
cvbackground = NULL;
ocv = NULL;
cvdetect = NULL;
cv::destroyWindow("CVDebugShow - Detect");
//cv::destroyWindow("CVDebugShow - Mask");
cv::destroyWindow("CVDebugShow - MaskSens");
//cv::destroyWindow("CVDebugShow - Background");
//cv::destroyWindow("CVDebugShow - Input");
cv::waitKey(1);
}
bool MotionCVDebugShow::process_frame(const AVFrame *frame, bool video){
if (!video){
return true;
}
//return true;
cv::imshow("CVDebugShow - Detect", cvdetect->get_debug_view());
//cv::imshow("CVDebugShow - Mask", cvmask->get_masked());
cv::normalize(cvmask->get_sensitivity(), normalized_buf, 1.0, 0.0, cv::NORM_MINMAX);
cv::imshow("CVDebugShow - MaskSens", normalized_buf);
//cv::imshow("CVDebugShow - Background", cvbackground->get_background());
//cv::imshow("CVDebugShow - Input", ocv->get_UMat());
cv::waitKey(1);
return true;
}
bool MotionCVDebugShow::set_video_stream(const AVStream *stream, const AVCodecContext *codec) {
return true;
}
const std::string& MotionCVDebugShow::get_mod_name(void) {
return algo_name;
}
bool MotionCVDebugShow::init(void) {
ocv = static_cast<MotionOpenCV*>(controller.get_module_before("opencv", this));
cvmask = static_cast<MotionCVMask*>(controller.get_module_before("cvmask", this));
cvbackground = static_cast<MotionCVBackground*>(controller.get_module_before("cvbackground", this));
cvdetect = static_cast<MotionCVDetect*>(controller.get_module_before("cvdetect", this));
return true;
}
//HAVE_OPENCV
#endif
#endif
| 2,985
|
C++
|
.cpp
| 76
| 36.105263
| 140
| 0.676897
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,959
|
mariadb_result.cpp
|
edman007_chiton/mariadb_result.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "mariadb_result.hpp"
#include "util.hpp"
const std::string MariaDBResult::null_txt = "NULL";
MariaDBResult::~MariaDBResult(){
if (res){
mysql_free_result(res);
}
}
long MariaDBResult::num_rows(){
if (!res){
return 0;
}
return mysql_num_rows(res);
}
const std::string& MariaDBResult::col_name(unsigned int col){
if (col_names.empty()){
fetch_col_names();
}
try {
return col_names.at(col);
} catch (std::out_of_range &e){
LWARN( "Requested Column name out of range");
return null_txt;
}
}
int MariaDBResult::field_count(void){
if (!res){
return 0;
}
if (!col_count){
col_count = mysql_num_fields(res);
}
return col_count;
}
void MariaDBResult::fetch_col_names(void){
MYSQL_FIELD *field;
while (res && (field = mysql_fetch_field(res))){
col_names.emplace_back(field->name);
}
}
bool MariaDBResult::next_row(void){
if (!res){
return false;
}
row = mysql_fetch_row(res);
//dump it all into col_data
if (row){
col_data.clear();
for (int i = 0; i < field_count(); i++){
if (row[i] == NULL){
col_data.emplace_back("NULL");
} else {
col_data.emplace_back(row[i]);
}
}
}
return row != NULL;
}
const std::string& MariaDBResult::get_field(unsigned int col){
try {
return col_data.at(col);
} catch (std::out_of_range &e){
LWARN( "Requested column out of range");
return null_txt;
}
}
const long MariaDBResult::get_field_long(unsigned int col){
const std::string& val = get_field(col);
if (!val.compare("")){
//empty
return 0;
}
try {
return std::stol(val);
} catch (const std::invalid_argument& ia){
LWARN( "database value " + col_name(col) + " ( " + val + " ) must be an integer");
} catch (const std::out_of_range& ia) {
LWARN( "database value " + col_name(col) + " ( " + val + " ) is out of range for long");
}
return 0;
}
const long long MariaDBResult::get_field_ll(unsigned int col){
const std::string& val = get_field(col);
if (!val.compare("")){
//empty
return 0;
}
try {
return std::stoll(val);
} catch (const std::invalid_argument& ia){
LWARN( "database value " + col_name(col) + " ( " + val + " ) must be an integer");
} catch (const std::out_of_range& ia) {
LWARN( "database value " + col_name(col) + " ( " + val + " ) is out of range for long");
}
return 0;
}
const double MariaDBResult::get_field_double(unsigned int col){
const std::string& val = get_field(col);
if (!val.compare("")){
//empty
return 0;
}
try {
return std::stod(val);
} catch (const std::invalid_argument& ia){
LWARN( "database value " + col_name(col) + " ( " + val + " ) must be a double");
} catch (const std::out_of_range& ia) {
LWARN( "database value " + col_name(col) + " ( " + val + " ) is out of range for double");
}
return 0;
}
bool MariaDBResult::field_is_null(unsigned int col){
if (col < col_count && col_count != 0){
return row[col] == NULL;
}
LWARN( "Requesting NULL status of field that doesn't exist");
return true;
}
| 4,311
|
C++
|
.cpp
| 139
| 25.661871
| 98
| 0.575574
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,960
|
remote.cpp
|
edman007_chiton/remote.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "remote.hpp"
#include "util.hpp"
#include "system_controller.hpp"
#include "json_encoder.hpp"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <functional>
#include <sstream>
#include <iomanip>
const int socket_backlog = 5;//maxiumn connection backlog for the socket
struct Remote::RemoteCommand {const std::string cmd;
std::function<void(Remote&, int, RemoteCommand&, std::string&)> cbk;
};
Remote::Remote(SystemController &sys) : sys(sys), db(sys.get_db()), cfg(sys.get_sys_cfg()) {
sockfd = -1;
killfd_worker = -1;
killfd_master = -1;
reload_requested = false;
//fill the supproted commands
command_vec.push_back({"RELOAD", &Remote::cmd_reload});
command_vec.push_back({"RM-EXPORT", &Remote::cmd_rm_export});
command_vec.push_back({"CLOSE", &Remote::cmd_close});
command_vec.push_back({"HELP", &Remote::cmd_help});
command_vec.push_back({"LICENSE", &Remote::cmd_license});
command_vec.push_back({"TEAPOT", &Remote::cmd_teapot});
command_vec.push_back({"START", &Remote::cmd_start});
command_vec.push_back({"STOP", &Remote::cmd_stop});
command_vec.push_back({"RESTART", &Remote::cmd_restart});
command_vec.push_back({"LOG", &Remote::cmd_log});
command_vec.push_back({"LIST", &Remote::cmd_list});
command_vec.push_back({"STATUS", &Remote::cmd_status});
}
void Remote::init(void){
if (create_socket()){
spawn_worker();
}
}
void Remote::shutdown(void){
stop_worker();
if (worker.joinable()){
//force the worker to exit...how?
worker.join();
}
if (killfd_worker != -1){
close(killfd_worker);
}
if (killfd_master != -1){
close(killfd_master);
}
killfd_worker = -1;
killfd_master = -1;
if (sockfd != -1){
//shutdown the workers...
close(sockfd);
if (unlink(path.c_str())){
LWARN("unlink of " + path + " failed " + std::to_string(errno));
}
sockfd = -1;
}
//kill all open connections
for (auto it = conn_list.begin(); it != conn_list.end(); ){
auto next_it = it;
next_it++;//grab a reference to the next it
close_conn(*it);
it = next_it;//this is valid, old it is not valid
}
}
Remote::~Remote(){
shutdown();
}
bool Remote::get_reload_request(void){
return reload_requested.exchange(false);
}
bool Remote::create_socket(void){
struct sockaddr_un sockaddr;
path = cfg.get_value("socket-path");
//attempt to create the socket
if (path.length() == 0){
LWARN("socket-path is empty, will not create socket");
return false;
}
if (path.length() > (sizeof(sockaddr.sun_path) - 1)){
LWARN("Path to socket is too long");
return false;
}
//check if the socket exists, and if so delete it, if it exists but it's not a socket bail
struct stat statbuf;
if (!stat(path.c_str(), &statbuf)){
if (S_ISSOCK(statbuf.st_mode)) {
if (unlink(path.c_str())){
LWARN("Could not delete " + path + " (" + std::to_string(errno) + ")");
return false;
}
} else {
LWARN(path + " exists and it's not a socket");
return false;
}
}//we proceed if stat fails, bind will fail later if it's a problem
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd == -1){
LWARN("Creation of UNIX socket failed " + std::to_string(errno));
return false;
}
auto len = path.copy(sockaddr.sun_path, sizeof(sockaddr.sun_path) - 1, 0);
sockaddr.sun_path[len] = '\0';
sockaddr.sun_family = AF_UNIX;
if (bind(sockfd, (const struct sockaddr*)&sockaddr, sizeof(sockaddr)) == -1){
LWARN("Binding socket " + path +" failed " + std::to_string(errno));
close(sockfd);
sockfd = -1;
return false;
}
//chmod it, need to restrict permissions as we currently use this as out only security
if (chmod(path.c_str(), 0660)){
LWARN("chmod of socket failed " + std::to_string(errno));
close(sockfd);
sockfd = -1;
unlink(path.c_str());
return false;
}
if (listen(sockfd, socket_backlog)){
LWARN("listen on socket failed " + std::to_string(errno));
close(sockfd);
sockfd = -1;
unlink(path.c_str());
return false;
}
//make a pipe
int pipefd[2];
if (pipe(pipefd)){
LWARN("Failed to make a pipe " + std::to_string(errno));
close(sockfd);
unlink(path.c_str());
return false;
}
killfd_master = pipefd[1];
killfd_worker = pipefd[0];
LINFO("Socket listening on " + path);
return true;
}
bool Remote::spawn_worker(void){
kill_worker = false;
try {
worker = std::thread(&Remote::run_worker, this);
} catch (const std::system_error& e){
LWARN("System error starting worker socket thread " + std::string(e.what()));
return false;
}
return true;
}
void Remote::run_worker(void){
//main loop
do {
int count = wait_for_activity();
if (count > 0){
if (FD_ISSET(kill_worker, &read_fds)){
continue;//we need to exit
}
if (FD_ISSET(sockfd, &read_fds)){
//open a new connection
LDEBUG("Accepting socket connection");
accept_new_connection();
}
for (auto fd_it = conn_list.begin(); fd_it != conn_list.end();){
auto fd_next = fd_it;//we do this because the below methods may invalidate the iterator
fd_next++;
int fd = *fd_it;
if (FD_ISSET(fd, &write_fds)){
complete_write(fd);
} else if (FD_ISSET(fd, &read_fds)){
process_input(fd);
}
fd_it = fd_next;
}
}
} while (!kill_worker);
}
int Remote::wait_for_activity(void){
nfds = 0;
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
FD_SET(sockfd, &read_fds);
nfds = std::max(nfds, sockfd);
FD_SET(killfd_worker, &read_fds);
nfds = std::max(nfds, killfd_worker);
for (auto fd : conn_list){
FD_SET(fd, &read_fds);
nfds = std::max(nfds, fd);
if (write_buffers.find(fd) != write_buffers.end()){
FD_SET(fd, &write_fds);
}
}
return select(nfds + 1, &read_fds, &write_fds, NULL, NULL);
}
void Remote::stop_worker(void){
kill_worker = true;
if (killfd_master == -1){
return;//no worker to kill
}
int ret;
do {
ret = write(killfd_master, "x", 2);
if (ret < 1){
if (errno == EAGAIN || errno == EINTR){
continue;
} else {
LWARN("Error sending signal to kill socket worker " + std::to_string(errno));
return;
}
}
} while (ret <= 0);
}
void Remote::accept_new_connection(void){
int new_fd = accept(sockfd, NULL, NULL);
if (new_fd >= 0){
conn_list.insert(conn_list.end(), new_fd);
}
}
void Remote::complete_write(int fd){
auto str = write_buffers.find(fd);
if (str == write_buffers.end()){
return;//doesn't exist
}
int ret = write(fd, str->second.c_str(), str->second.length());
if ((unsigned int)ret != str->second.length() && ret >= 0){
//write didn't complete
std::string new_buf = str->second.substr(ret, std::string::npos);
write_buffers[fd] = new_buf;
} else if (ret < 0 && errno != EAGAIN && errno != EINTR){
//fatal error
LWARN("Write to socket connection failed " + std::to_string(errno));
close_conn(fd);
} else {
//good write
write_buffers.erase(fd);
}
}
void Remote::write_data(int fd, std::string str){
auto target = write_buffers.find(fd);
if (target == write_buffers.end()){
write_buffers[fd] = str;
} else {
write_buffers[fd] = write_buffers[fd] + str;
}
complete_write(fd);
}
void Remote::process_input(int fd){
char buf[1024];
int cnt = sizeof(buf);
cnt = read(fd, buf, cnt);
if (cnt <= 0){
if (cnt < 0 && errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK){
LWARN("Read of socket connection failed " + std::to_string(errno));
close_conn(fd);
} else if (cnt == 0 && errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK){
close_conn(fd);//the connection has been closed
}
return;
}
//add the new buffer to the input buffer
auto sbuf = read_buffers.find(fd);
if (sbuf == read_buffers.end()){
read_buffers[fd] = std::string(std::string(buf, cnt));
} else {
read_buffers[fd] = std::string(read_buffers[fd] + std::string(buf, cnt));
}
//now we get the lines and process them
std::string::size_type pos = 0;
std::string::size_type newline = 0;
do {
//check if a newline exists
newline = read_buffers[fd].find('\n', pos);
if (newline != std::string::npos){
//good data, extract it and process
auto cmd = read_buffers[fd].substr(pos, newline - pos);
execute_cmd(fd, cmd);
pos = newline + 1;
} else if ((read_buffers[fd].length() - pos) > 1024){
LWARN("Socket connection received line too long");
close_conn(fd);
return;
}
} while (pos < read_buffers[fd].length() && newline != std::string::npos);
//now delete the bits of the buffer that have been read
if (pos == read_buffers[fd].length()){
read_buffers.erase(fd);
} else if (newline == std::string::npos) {//we had some data left
read_buffers[fd] = read_buffers[fd].substr(pos);
}
}
void Remote::close_conn(int fd){
if (fd < 0){
return;
}
LDEBUG("Closing Socket Connection");
close(fd);
write_buffers.erase(fd);
for (auto it = conn_list.begin(); it != conn_list.end(); it++){
if (*it == fd){
conn_list.erase(it);
break;
}
}
}
void Remote::execute_cmd(int fd, std::string &cmd){
for (auto rc : command_vec){
if (cmd.find(rc.cmd) == 0){
LDEBUG("Calling " + rc.cmd);
rc.cbk(*this, fd, rc, cmd);
return;
}
}
write_data(fd, "Unknown Command: " + cmd +"\n");
}
void Remote::cmd_reload(int fd, RemoteCommand& rc, std::string &cmd){
LINFO("Reload Requested via socket");
reload_requested.exchange(true);
write_data(fd, "OK\n");
}
void Remote::cmd_rm_export(int fd, RemoteCommand& rc, std::string &cmd){
int export_id = 0;
try {
export_id = std::stoi(cmd.substr(rc.cmd.length() + 1));
} catch (std::logic_error &e){
write_data(fd, "INVALID ARGUMENT\n");
return;
}
if (sys.get_export().rm_export(export_id)){
write_data(fd, "OK\n");
} else {
write_data(fd, "ERROR\n");
}
}
void Remote::cmd_close(int fd, RemoteCommand& rc, std::string &cmd){
close_conn(fd);
}
void Remote::cmd_help(int fd, RemoteCommand& rc, std::string &cmd){
std::string supported_commands = "";
for (auto rc : command_vec){
supported_commands += " " + rc.cmd;
}
write_data(fd, "SUPPORTED COMMANDS:" + supported_commands + "\n");
}
void Remote::cmd_license(int fd, RemoteCommand& rc, std::string &cmd){
//FIXME: Date should be pushed from configure
write_data(fd, "chiton Copyright (C) 2020-2023 Ed Martin <edman007@edman007.com> \n"
"This program is free software: you can redistribute it and/or modify "
"it under the terms of the GNU General Public License as published by "
"the Free Software Foundation, either version 3 of the License, or "
"(at your option) any later version. "
"This program is distributed in the hope that it will be useful, "
"but WITHOUT ANY WARRANTY; without even the implied warranty of "
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the "
"GNU General Public License for more details. "
"You should have received a copy of the GNU General Public License "
"along with this program. If not, see <https://www.gnu.org/licenses/>.\n");
}
void Remote::cmd_teapot(int fd, RemoteCommand& rc, std::string &cmd){
write_data(fd, "I'm a teapot! 29b6b3dad9327e74f5bff8259f9965a5\n");//echo -n edman007''@''edman007.com | md5sum -
}
void Remote::cmd_start(int fd, RemoteCommand& rc, std::string &cmd){
int cam_id = 0;
try {
cam_id = std::stoi(cmd.substr(rc.cmd.length() + 1));
} catch (std::logic_error &e){
write_data(fd, "INVALID ARGUMENT\n");
return;
}
bool ret = sys.start_cam(cam_id);
if (ret){
write_data(fd, "OK\n");
} else {
write_data(fd, "BUSY\n");
}
}
void Remote::cmd_stop(int fd, RemoteCommand& rc, std::string &cmd){
int cam_id = 0;
try {
cam_id = std::stoi(cmd.substr(rc.cmd.length() + 1));
} catch (std::logic_error &e){
write_data(fd, "INVALID ARGUMENT\n");
return;
}
bool ret = sys.stop_cam(cam_id);
if (ret){
write_data(fd, "OK\n");
} else {
write_data(fd, "BUSY\n");
}
}
void Remote::cmd_restart(int fd, RemoteCommand& rc, std::string &cmd){
int cam_id = 0;
try {
cam_id = std::stoi(cmd.substr(rc.cmd.length() + 1));
} catch (std::logic_error &e){
write_data(fd, "INVALID ARGUMENT\n");
return;
}
bool ret = sys.restart_cam(cam_id);
if (ret){
write_data(fd, "OK\n");
} else {
write_data(fd, "BUSY\n");
}
}
void Remote::cmd_log(int fd, RemoteCommand& rc, std::string &cmd){
int cam_id = 0;
try {
cam_id = std::stoi(cmd.substr(rc.cmd.length() + 1));
} catch (std::logic_error &e){
write_data(fd, "INVALID ARGUMENT\n");
return;
}
std::vector<LogMsg> hist;
if (!Util::get_history(cam_id, hist)){
write_data(fd, "OK\n");
return;
}
for (auto &msg : hist){
//check and remove newline characters
size_t pos = 0;
do {
pos = msg.msg.find('\n', pos);
if (pos != std::string::npos){
msg.msg[pos] = ' ';
pos++;
}
} while (pos != std::string::npos);
std::ostringstream oss;
oss << cam_id << "\t";
oss << msg.lvl << "\t";
//tv_usec is 0.000001
oss << msg.time.tv_sec << "." << std::setw(6) << std::setfill('0') << msg.time.tv_usec << "\t";
oss << msg.msg;
oss << "\n";
write_data(fd, oss.str());
}
write_data(fd, "OK\n");
}
void Remote::cmd_list(int fd, RemoteCommand& rc, std::string &cmd){
std::map<int, SystemController::CAMERA_STATE> stat;
sys.list_state(stat);
for (auto it = stat.begin(); it != stat.end(); it++){
std::string state;
switch (it->second){
case SystemController::STOPPING:
state = "STOPPING";
break;
case SystemController::STARTING:
state = "STARTING";
break;
case SystemController::RUNNING:
state = "RUNNING";
break;
case SystemController::RESTARTING:
state = "RESTARTING";
break;
default:
state = "UNKNOWN";
}
write_data(fd, std::to_string(it->first) + "\t" + state + "\n");
}
write_data(fd, "OK\n");
}
void Remote::cmd_status(int fd, RemoteCommand& rc, std::string &cmd){
int cam_id = 0;
try {
cam_id = std::stoi(cmd.substr(rc.cmd.length() + 1));
} catch (std::logic_error &e){
write_data(fd, "INVALID ARGUMENT\n");
return;
}
JSONEncoder json;
CameraStatus status(-2);
bool ret = sys.get_camera_status(cam_id, status);
if (!ret){
write_data(fd, "INVALID ARGUMENT\n");
return;
}
json.add("id", status.get_id());
json.add("bytes_written", status.get_bytes_written());
json.add("bytes_read", status.get_bytes_read());
json.add("dropped_frames", status.get_dropped_frames());
json.add("start_time", status.get_start_time());
write_data(fd, std::to_string(json.str().length()) + "\n");
write_data(fd, json.str());
write_data(fd, "\nOK\n");
}
| 17,547
|
C++
|
.cpp
| 512
| 27.363281
| 118
| 0.570443
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,961
|
motion_opencv.cpp
|
edman007_chiton/motion_opencv.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "motion_opencv.hpp"
#ifdef HAVE_OPENCV
#include "util.hpp"
#ifdef HAVE_VAAPI
#include <opencv2/core/va_intel.hpp>
#endif
#define CL_TARGET_OPENCL_VERSION 300
#ifdef HAVE_OPENCL
#ifdef HAVE_OPENCL_CL_H
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
#endif
#include <opencv2/imgproc.hpp>
#include <opencv2/core/ocl.hpp>
//debug things
#include <opencv2/highgui.hpp>
#include "image_util.hpp"
static const std::string algo_name = "opencv";
MotionOpenCV::MotionOpenCV(Config &cfg, Database &db, MotionController &controller) : MotionAlgo(cfg, db, controller, algo_name), fmt_filter(Filter(cfg)) {
input = av_frame_alloc();
map_indirect = cfg.get_value("motion-opencv-map-indirect") != "false";//if true will use libva to copy the brighness
map_cl = cfg.get_value("motion-opencv-map-cl") != "false";//use ffmpeg to convert to opencl and then map that into opencv
map_vaapi = cfg.get_value("motion-opencv-map-vaapi") != "false";//use OpenCV's VA-API mapping implementation
if (cfg.get_value("opencv-opencl-device") != ""){
ocv_cl_ctx = cv::ocl::Context::create(cfg.get_value("opencv-opencl-device"));
if (ocv_cl_ctx.ndevices() > 0){
cv::ocl::Device &dev = ocv_cl_ctx.device(0);
LINFO("OpenCV Selecting OpenCL device: " + dev.name());
ocv_exe_ctx = cv::ocl::OpenCLExecutionContext::create(ocv_cl_ctx, dev);
ocv_exe_ctx.bind();
} else {
LWARN("Could not find OpenCL device matching '" + cfg.get_value("opencv-opencl-device") + "'");
}
}
//disable opencv use if requested
if (cfg.get_value("opencv-disable-opencl") == "true"){
//We only ever disable it (never enable it) because the default OpenCV
//value is effectivitly auto, but the API does not accept auto
cv::ocl::setUseOpenCL(false);
}
}
MotionOpenCV::~MotionOpenCV(){
av_frame_free(&input);
cv::ocl::finish();//call clFinish()
}
bool MotionOpenCV::process_frame(const AVFrame *frame, bool video){
if (!video){
return true;
}
if (invalid_mat.empty()){
invalid_mat = cv::UMat::zeros(cv::Size(frame->width, frame->height), CV_8UC1);
}
buf_mat.release();
input_mat.release();
//opencv libva is HAVE_VA, our libva is HAVE_VAAPI
//while it might be built without va-api, we can detect is runtime, so map_vaapi will be false if support is missing
//check if the incoming frame is VAAPI
if (map_vaapi && frame->format == AV_PIX_FMT_VAAPI && frame->hw_frames_ctx){
AVVAAPIDeviceContext *hwctx = get_vaapi_ctx_from_frames(frame->hw_frames_ctx);;
if (!hwctx){
LERROR("VAAPI frame does not have VAAPI device");
return false;
}
const VASurfaceID surf = reinterpret_cast<uintptr_t const>(frame->data[3]);
try {
cv::va_intel::convertFromVASurface(hwctx->display, surf, cv::Size(frame->width, frame->height), tmp1);
//change to CV_8UC1
if (tmp1.depth() == CV_8U){
cv::cvtColor(tmp1, buf_mat, cv::COLOR_BGR2GRAY);
} else {
double alpha = 1.0;
if (tmp1.depth() == CV_16U){
alpha = 1.0/256;
} else {
LWARN("convertFromVASurface provided unsupported depth, not scaling it");
}
tmp1.convertTo(tmp2, CV_8U, alpha);
cv::cvtColor(tmp2, buf_mat, cv::COLOR_BGR2GRAY);
}
} catch (cv::Exception &e){
LWARN("Error converting image from VA-API To OpenCV: " + e.msg);
return false;
}
} else
#ifdef HAVE_VAAPI
//this is a higher speed indirect (no-interopt) version for non-intel HW
if (map_indirect && frame->format == AV_PIX_FMT_VAAPI && frame->hw_frames_ctx){
indirect_vaapi_map(frame);
} else
#endif
#ifdef HAVE_OPENCL
if (map_cl && frame->format == AV_PIX_FMT_VAAPI && frame->hw_frames_ctx){
//map it to openCL
if (!fmt_filter.send_frame(frame)){
LWARN("OpenCV Failed to Send Frame");
return false;
}
av_frame_unref(input);
if (!fmt_filter.get_frame(input)){
LWARN("OpenCV Failed to Get Frame");
return false;
}
map_ocl_frame(input);
} else
#endif
{
//direct VAAPI conversion not possible
if (!fmt_filter.send_frame(frame)){
LWARN("OpenCV Failed to Send Frame");
return false;
}
av_frame_unref(input);
if (!fmt_filter.get_frame(input)){
LWARN("OpenCV Failed to Get Frame");
return false;
}
//CV_16UC1 matches the format in set_video_stream()
input_mat = cv::Mat(input->height, input->width, CV_8UC1, input->data[0], input->linesize[0]);
input_mat.copyTo(buf_mat);
//buf_mat = input_mat.getUMat(cv::ACCESS_READ);
}
return true;
}
bool MotionOpenCV::set_video_stream(const AVStream *stream, const AVCodecContext *codec) {
//if the codec does not have VA-API then we need to not use opencl
if (codec && codec->hw_device_ctx){
//find the VAAPI Display
AVVAAPIDeviceContext* hw_ctx = get_vaapi_ctx_from_device(codec->hw_device_ctx);
if (map_vaapi && hw_ctx){
//bind this display to this thread
try {
cv::va_intel::ocl::initializeContextFromVA(hw_ctx->display, true);
} catch (cv::Exception &e){
//if we actually don't have va-api, this will fail
LWARN("cv::va_intel::ocl::initializeContextFromVA failed, disable this by setting motion-opencv-map-vaapi to false, error: " + e.msg);
map_vaapi = false;
}
} else if (!hw_ctx){
LINFO("No VA-API Context");
map_cl = false;
}
} else {
LINFO("No HW Context");
if (!codec){
LWARN("No decode codec passed to MotionOpenCV!");
}
map_cl = false;
}
//CODEC is only needed for HW Mapping...we will map it ourself
fmt_filter.set_source_time_base(stream->time_base);
if (map_cl){
LINFO("Setup for OpenCL");
fmt_filter.set_target_fmt(AV_PIX_FMT_OPENCL, AV_CODEC_ID_NONE, 0);//
} else {
fmt_filter.set_target_fmt(AV_PIX_FMT_GRAY8, AV_CODEC_ID_NONE, 0);
}
return true;
}
const std::string& MotionOpenCV::get_mod_name(void) {
return algo_name;
}
const cv::UMat& MotionOpenCV::get_UMat(void) const {
if (buf_mat.empty()){
LWARN("Returning empty OpenCV image due to failure to map, OpenCV motion detection will not work");
return invalid_mat;
}
return buf_mat;
}
#ifdef HAVE_OPENCL
void MotionOpenCV::map_ocl_frame(AVFrame *input){
//Extract the two OpenCL Image2Ds from the opencl frame
cl_mem luma_image = reinterpret_cast<cl_mem>(input->data[0]);
cl_mem chrome_image = reinterpret_cast<cl_mem>(input->data[1]);
size_t luma_w = 0;
size_t luma_h = 0;
size_t chroma_w = 0;
size_t chroma_h = 0;
clGetImageInfo(luma_image, CL_IMAGE_WIDTH, sizeof(size_t), &luma_w, 0);
clGetImageInfo(luma_image, CL_IMAGE_HEIGHT, sizeof(size_t), &luma_h, 0);
clGetImageInfo(chrome_image, CL_IMAGE_WIDTH, sizeof(size_t), &chroma_w, 0);
clGetImageInfo(chrome_image, CL_IMAGE_HEIGHT, sizeof(size_t), &chroma_h, 0);
//FIXME: assumes this is NV12
tmp1.create(luma_h + chroma_h, luma_w, CV_8U);
cl_mem dst_buffer = static_cast<cl_mem>(tmp1.handle(cv::ACCESS_READ));
cl_command_queue queue = static_cast<cl_command_queue>(cv::ocl::Queue::getDefault().ptr());
size_t src_origin[3] = { 0, 0, 0 };
size_t luma_region[3] = { luma_w, luma_h, 1 };
size_t chroma_region[3] = { chroma_w, chroma_h * 2, 1 };
//Copy the contents of each Image2Ds to the right place in the
//OpenCL buffer which backs the Mat
clEnqueueCopyImageToBuffer(queue, luma_image, dst_buffer, src_origin, luma_region, 0, 0, NULL, NULL);
clEnqueueCopyImageToBuffer(queue, chrome_image, dst_buffer, src_origin, chroma_region, luma_w * luma_h * 1, 0, NULL, NULL);
// Block until the copying is done
clFinish(queue);
}
//HAVE_OPENCL
#endif
#ifdef HAVE_VAAPI
//inspired from OpenCVs convertFromvasurface
void MotionOpenCV::indirect_vaapi_map(const AVFrame *input){
AVVAAPIDeviceContext* hw_ctx = get_vaapi_ctx_from_frames(input->hw_frames_ctx);
if (!hw_ctx){
LWARN("No VAAPI context found");
return;
}
const VASurfaceID surface = reinterpret_cast<uintptr_t const>(input->data[3]);
VAStatus status = 0;
status = vaSyncSurface(hw_ctx->display, surface);
if (status != VA_STATUS_SUCCESS){
LWARN("vaSyncSurface: Failed (" + std::to_string(status) + ")");
return;
}
VAImage image;
status = vaDeriveImage(hw_ctx->display, surface, &image);
if (status != VA_STATUS_SUCCESS){
//try vaCreateImage + vaGetImage
//pick a format
int num_formats = vaMaxNumImageFormats(hw_ctx->display);
if (num_formats <= 0){
LWARN("VA-API: vaMaxNumImageFormats failed");
return;
}
std::vector<VAImageFormat> fmt_list(num_formats);
status = vaQueryImageFormats(hw_ctx->display, fmt_list.data(), &num_formats);
if (status != VA_STATUS_SUCCESS){
LWARN("VA-API: vaQueryImageFormats failed");
return;
}
fmt_list.resize(num_formats);
VAImageFormat *selected_format = nullptr;
for (auto &fmt : fmt_list){
if (fmt.fourcc == VA_FOURCC_NV12 || fmt.fourcc == VA_FOURCC_YV12){
selected_format = &fmt;
break;
}
}
if (selected_format == nullptr){
LWARN("VA-API: vaQueryImageFormats did not return a supported format");
return;
}
status = vaCreateImage(hw_ctx->display, selected_format, input->width, input->height, &image);
if (status != VA_STATUS_SUCCESS){
LWARN("VA-API: vaCreateImage failed");
return;
}
status = vaGetImage(hw_ctx->display, surface, 0, 0, input->width, input->height, image.image_id);
if (status != VA_STATUS_SUCCESS){
vaDestroyImage(hw_ctx->display, image.image_id);
LWARN("VA-API: vaPutImage failed");
return;
}
}
unsigned char* buffer = 0;
status = vaMapBuffer(hw_ctx->display, image.buf, (void **)&buffer);
if (status != VA_STATUS_SUCCESS){
LWARN("VA-API: vaMapBuffer failed");
}
if (image.format.fourcc == VA_FOURCC_NV12){
input_mat = cv::Mat(input->height, input->width, CV_8UC1, buffer + image.offsets[0], image.pitches[0]);
} else if (image.format.fourcc == VA_FOURCC_YV12) {
input_mat = cv::Mat(input->height, input->width, CV_8UC1, buffer + image.offsets[0], image.pitches[0]);
} else {
LWARN("VA-API didn't return correct format");
return;
}
input_mat.copyTo(buf_mat);//buf_mat is now the luma channel which is close enough for us
input_mat.release();
status = vaUnmapBuffer(hw_ctx->display, image.buf);
if (status != VA_STATUS_SUCCESS){
LWARN("VA-API: vaUnmapBuffer failed");
return;
}
status = vaDestroyImage(hw_ctx->display, image.image_id);
if (status != VA_STATUS_SUCCESS){
LWARN("VA-API: vaDestroyImage failed");
return;
}
}
//HAVE_VAAPI
#endif
//HAVE_OPENCV
#endif
| 12,498
|
C++
|
.cpp
| 305
| 33.901639
| 155
| 0.618828
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,962
|
motion_algo.cpp
|
edman007_chiton/motion_algo.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "motion_algo.hpp"
| 934
|
C++
|
.cpp
| 22
| 40.545455
| 75
| 0.607456
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,963
|
filter.cpp
|
edman007_chiton/filter.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2021-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "filter.hpp"
#include "util.hpp"
#include <sstream>
extern "C" {
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
};
//supproted HW methods, these trigger hwdownload/hwupload
const AVPixelFormat hw_formats[] = {
AV_PIX_FMT_VAAPI,
AV_PIX_FMT_VDPAU,
AV_PIX_FMT_OPENCL,
AV_PIX_FMT_DRM_PRIME
};
Filter::Filter(Config& cfg) : cfg(cfg) {
target_fmt = AV_PIX_FMT_NONE;
tmp_frame = av_frame_alloc();
init_complete = false;
passthrough = false;
time_base = {1, 1};
filter_graph = NULL;
buffersink_ctx = NULL;
buffersrc_ctx = NULL;
peeked = false;
tmp_frame_filled = false;
target_codec = AV_CODEC_ID_NONE;
target_profile = FF_PROFILE_UNKNOWN;
source_codec = AV_CODEC_ID_NONE;
source_profile = FF_PROFILE_UNKNOWN;
}
Filter::~Filter(){
av_frame_free(&tmp_frame);
avfilter_free(buffersrc_ctx);
buffersrc_ctx = NULL;
avfilter_free(buffersink_ctx);
buffersink_ctx = NULL;
avfilter_graph_free(&filter_graph);
}
bool Filter::set_target_fmt(const AVPixelFormat fmt, AVCodecID codec_id, int codec_profile){
target_fmt = fmt;
target_codec = codec_id;
target_profile = codec_profile;
return fmt != AV_PIX_FMT_NONE && target_codec != AV_CODEC_ID_NONE;
}
bool Filter::set_source_codec(AVCodecID codec_id, int codec_profile){
source_codec = codec_id;
source_profile = codec_profile;
return codec_id != AV_CODEC_ID_NONE;
}
bool Filter::send_frame(const AVFrame *frame){
if (!init_complete){
if (!init_filter(frame)){
return false;
}
}
if (peeked){
LDEBUG("Peeked received again, dropping");
return true;//NO-OP, we actually already got it
}
if (passthrough){
if (tmp_frame_filled){
return false;
} else {
av_frame_ref(tmp_frame, frame);
tmp_frame_filled = true;
return true;
}
}
if (av_buffersrc_write_frame(buffersrc_ctx, frame) < 0) {
LERROR("Error while feeding the filtergraph");
return false;
}
return true;
}
bool Filter::get_frame(AVFrame *frame){
if (passthrough){
if (tmp_frame_filled){
av_frame_unref(frame);
av_frame_move_ref(frame, tmp_frame);
tmp_frame_filled = false;
peeked = false;
return true;
} else {
return false;
}
}
//if peek was called before
if (tmp_frame_filled){
av_frame_move_ref(frame, tmp_frame);
tmp_frame_filled = false;
peeked = false;
return true;
}
int ret = av_buffersink_get_frame(buffersink_ctx, frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF){
//the end, not an error
return false;
}
if (ret < 0){
LWARN("Error getting frame from filter");
return false;
}
return true;
}
bool Filter::peek_frame(AVFrame *frame){
if (passthrough){
if (tmp_frame_filled){
av_frame_ref(frame, tmp_frame);
tmp_frame_filled = false;
return true;
} else {
return false;
}
}
if (tmp_frame_filled){
return false;
}
int ret = av_buffersink_get_frame(buffersink_ctx, tmp_frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF){
//the end, not an error
return false;
}
if (ret < 0){
LWARN("Error getting frame from filter");
return false;
}
av_frame_ref(frame, tmp_frame);
tmp_frame_filled = true;
peeked = true;
return true;
}
bool Filter::init_filter(const AVFrame *frame){
if (frame->format == target_fmt){
//do NO-OP
//FIXME: Check for user options
passthrough = true;
return true;
}
std::stringstream args;
const AVFilter *buffersrc = avfilter_get_by_name("buffer");
const AVFilter *buffersink = avfilter_get_by_name("buffersink");
enum AVPixelFormat pix_fmts[] = { target_fmt, AV_PIX_FMT_NONE };
filter_graph = avfilter_graph_alloc();
if (!filter_graph) {
LWARN("Failed to alloc filter");
return false;
}
args << "video_size=" << frame->width << "x" << frame->height;
args << ":pix_fmt=" << frame->format;
args << ":time_base=" << time_base.num << "/" << time_base.den;
args << ":pixel_aspect=" << frame->sample_aspect_ratio.num << "/" << frame->sample_aspect_ratio.den;
LDEBUG("Source Filter Format: " + args.str());
int ret = 0;
ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
args.str().c_str(), NULL, filter_graph);
if (ret < 0) {
LERROR("Cannot create filter buffer source");
return false;
}
ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out", NULL, NULL, filter_graph);
if (ret < 0) {
LERROR("Cannot create filter buffer sink");
return false;
}
if (frame->hw_frames_ctx){//copy the input device context if one exists
AVBufferSrcParameters *bsp = av_buffersrc_parameters_alloc();
bsp->hw_frames_ctx = frame->hw_frames_ctx;//we do NOT put a new ref here, we own everything in this struct
bsp->format = frame->format;
bsp->width = frame->width;
bsp->height = frame->height;
bsp->sample_aspect_ratio = frame->sample_aspect_ratio;
if (av_buffersrc_parameters_set(buffersrc_ctx, bsp)){
LWARN("Failed to set filter buffersrc parameters");
}
av_free(bsp);
} else if (!is_hw(target_fmt)){
LDEBUG("Performing SW/SW filter");
}//SW->HW is added after
//specify output format
ret = av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts, AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
if (ret < 0) {
LERROR("Cannot set filter output pixel format");
return false;
}
//init the end points
AVFilterInOut *outputs = avfilter_inout_alloc();
if (!outputs){
LERROR("Failed to alloc filter output");
return false;
}
AVFilterInOut *inputs = avfilter_inout_alloc();
if (!inputs){
LERROR("Failed to alloc filter input");
avfilter_inout_free(&outputs);
return false;
}
//connect in/out context
outputs->name = av_strdup("in");
outputs->filter_ctx = buffersrc_ctx;
outputs->pad_idx = 0;
outputs->next = NULL;
inputs->name = av_strdup("out");
inputs->filter_ctx = buffersink_ctx;
inputs->pad_idx = 0;
inputs->next = NULL;
//parse the filter text
ret = avfilter_graph_parse_ptr(filter_graph, get_filter_str(frame).c_str(), &inputs, &outputs, NULL);
if (ret >= 0){
//hwmap specifically needs
for (unsigned int i = 0; i < filter_graph->nb_filters; i++){
AVFilterContext *flt = filter_graph->filters[i];
if (strcmp(flt->filter->name, "hwmap") == 0 || strcmp(flt->filter->name, "hwupload") == 0){
if (!frame->hw_frames_ctx && target_fmt == AV_PIX_FMT_VAAPI) {//source is SW dest is VAAPI
flt->hw_device_ctx = gcff_util.get_vaapi_ctx(target_codec, target_profile, frame->width, frame->height);
}
if (target_fmt == AV_PIX_FMT_OPENCL) {//dest is OpenCL
flt->hw_device_ctx = gcff_util.get_opencl_ctx(target_codec, target_profile, frame->width, frame->height);
}
}
}
ret = avfilter_graph_config(filter_graph, NULL);
if (ret < 0){
LERROR("Failed to validate filter");
}
} else {
LERROR("Failed to parse filter graph");
}
avfilter_inout_free(&inputs);
avfilter_inout_free(&outputs);
if (ret >= 0){
init_complete = true;;
}
return ret >= 0;
}
bool Filter::is_hw(const AVPixelFormat fmt) const{
for (auto &hw : hw_formats){
if (hw == fmt){
return true;
}
}
return false;
}
bool Filter::is_hw(const int fmt) const {
return is_hw(static_cast<AVPixelFormat>(fmt));
}
std::string Filter::get_filter_str(const AVFrame *frame) const {
std::stringstream filters_txt;
//test if we will need to start with a format)
if (is_hw(frame->format) || is_hw(target_fmt)){
//have a SW format and the SW decoder didn't get it into something compatable, so format into something compatable
if (!is_hw(frame->format) &&
(!gcff_util.sw_format_is_hw_compatable(static_cast<enum AVPixelFormat>(frame->format)) || cfg.get_value("video-hw-pix-fmt") != "auto")){
filters_txt << "format=pix_fmts=" << gcff_util.get_sw_hw_format_list(cfg, frame, source_codec, source_profile) << ",";
}
//transfer between HW...HWMap?
//hwmap is supposed to work in all cases here...but in testing it doesn't actually work, not sure why
if (!is_hw(frame->format)){
filters_txt << "hwupload=";
} else if (!is_hw(target_fmt)){
//request to download into supported format, then format later
filters_txt << "hwdownload,format=pix_fmts=" << gcff_util.get_sw_hw_format_list(cfg, frame, source_codec, source_profile);
} else {
filters_txt << "hwmap=mode=read";
}
if (is_hw(target_fmt)){
if (target_fmt == AV_PIX_FMT_VAAPI){
filters_txt << ":derive_device=vaapi";
} else if (target_fmt == AV_PIX_FMT_OPENCL){
filters_txt << ":derive_device=opencl";
} else {//check if we made a mistake, VDPAU is not a HW output format
LWARN("Unknown target HW format");
}
}
filters_txt << ",format=pix_fmts=" << av_get_pix_fmt_name(target_fmt);
} else {
//SW conversion
filters_txt << "format=pix_fmts=" << av_get_pix_fmt_name(target_fmt);
}
LDEBUG("Filter str: " + filters_txt.str());
//FIXME: Take user inputs
return filters_txt.str();
}
void Filter::set_source_time_base(const AVRational tb) {
time_base = tb;
//nothing...
};
| 11,099
|
C++
|
.cpp
| 307
| 29.355049
| 148
| 0.598884
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,964
|
event_notification.cpp
|
edman007_chiton/event_notification.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "event_notification.hpp"
| 941
|
C++
|
.cpp
| 22
| 40.863636
| 75
| 0.610446
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,966
|
mariadb.cpp
|
edman007_chiton/mariadb.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "mariadb.hpp"
#include "util.hpp"
MariaDB::MariaDB(){
conn = NULL;
}
MariaDB::~MariaDB(){
close();
}
void MariaDB::close(void){
mysql_close(conn);
conn = NULL;
}
int MariaDB::connect(const std::string& server, const std::string& db, const std::string& user, const std::string& pass, const int port, const std::string& socket){
int flags = 0;
const char *sock;
my_bool reconnect = 1;
if (!conn){
conn = mysql_init(conn);
}
mysql_options(conn, MYSQL_OPT_RECONNECT, &reconnect);
//doesn't work with an empty string
if (socket.compare("")){
sock = socket.c_str();
} else {
sock = 0;
}
if (!mysql_real_connect(conn, server.c_str(), user.c_str(), pass.c_str(), db.c_str(), port, sock, flags)){
LERROR( "Failed to connect to database: Error: " + std::string(mysql_error(conn)));
return (int)mysql_errno(conn);
}
LINFO( "Connected to Database");
return 0;
}
std::string MariaDB::escape(const std::string& str){
char out_str[str.length()*2+1];
mysql_real_escape_string(conn, out_str, str.c_str(), str.length());
return std::string(out_str);//is this a good idea to copy the string...
}
MariaDBResult* MariaDB::query_nolock(const std::string& sql){
int ret = mysql_real_query(conn, sql.c_str(), sql.length());
if (ret){
//error
LWARN( "Query Failed: " + std::string(mysql_error(conn)));
LINFO( "Query Was: " + sql);
return NULL;
}
MYSQL_RES *res = mysql_store_result(conn);
return new MariaDBResult(res);
}
MariaDBResult* MariaDB::query(const std::string& sql){
return query(sql, NULL, NULL);
}
MariaDBResult* MariaDB::query(const std::string& sql, long* affected_rows, long *insert_id){
mtx.lock();
MariaDBResult *ret = query_nolock(sql);
if (affected_rows){
*affected_rows = mysql_affected_rows(conn);
}
if (insert_id){
*insert_id = mysql_insert_id(conn);
}
mtx.unlock();
return ret;
}
| 2,948
|
C++
|
.cpp
| 85
| 30.458824
| 164
| 0.622136
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,967
|
event_controller.cpp
|
edman007_chiton/event_controller.cpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "event_controller.hpp"
#include "util.hpp"
#include "event_console.hpp"
#include "event_db.hpp"
EventController::EventController(Config &cfg, Database &db, ImageUtil &img) : ModuleController<EventNotification, EventController>(cfg, db, "event"), img(img) {
register_module(new ModuleFactory<EventDB, EventNotification, EventController>());
register_module(new ModuleFactory<EventConsole, EventNotification, EventController>());
add_mods();
};
EventController::~EventController(){
}
ImageUtil& EventController::get_img_util(void){
return img;
}
Event& EventController::get_new_event(void){
for (auto &e : events){
if (!e.is_valid()){
e.clear();
return e;
}
}
events.emplace_back(Event(cfg));
return events.back();
}
bool EventController::send_event(Event& event){
bool ret = true;
for (auto &n : mods){
ret &= n->send_event(event);
}
event.invalidate();
return ret;
}
| 1,891
|
C++
|
.cpp
| 53
| 32.264151
| 160
| 0.644809
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,968
|
cfmp4.cpp
|
edman007_chiton/io/cfmp4.cpp
|
#include "cfmp4.hpp"
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2021 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "io/cfmp4.hpp"
#include "util.hpp"
#include <assert.h>
//I hope this is implied...but maybe not and this will actually help somebody someday
static_assert(sizeof(std::basic_istream<char>::char_type) == sizeof(uint8_t), "libav* uint8_t does NOT match libc++ charT, evaluate the casts in this file");
const int cfmp4_buf_size = 8192;
CFMP4::CFMP4(const std::string &path, int initlen, int start_byte, int end_byte) : initlen(initlen), start_byte(start_byte), end_byte(end_byte) {
LWARN("Will open " + path);
if (end_byte > start_byte){
//open the file
ifs.open(path, std::ios::binary|std::ios::in);
if (!ifs.good()){
LWARN("Failed to open " + path);
}
}
pb = NULL;
if (ifs.is_open()){
buf = static_cast<unsigned char*>(av_malloc(cfmp4_buf_size));
pb = avio_alloc_context(buf, cfmp4_buf_size, 0, this, read_packet, 0, seek);
LWARN("Opened!");
} else {
//failed...just set them to zero
buf = NULL;
pb = NULL;
}
}
CFMP4::~CFMP4(){
avio_context_free(&pb);
}
AVIOContext* CFMP4::get_pb(void){
LWARN("Got PB ");
return pb;
}
int CFMP4::read_packet(void *opaque, uint8_t *buf, int buf_size){
CFMP4* stream = static_cast<CFMP4*>(opaque);
return stream->read(buf, buf_size);
}
int CFMP4::read(uint8_t *buf, int buf_size){
LINFO("Reading from custom IO");
if (ifs.eof()){
LDEBUG("at EOF");
return AVERROR_EOF;
}
if (!ifs.good()){
return AVERROR(EINVAL);
}
auto pos = ifs.tellg();
LDEBUG("pos: " + std::to_string(pos) + " end:" + std::to_string(end_byte));
if (pos < 0){
return AVERROR(EINVAL);//error?
}
if (pos >= end_byte){
LDEBUG("Hit EOF");
//EOF
return AVERROR_EOF;
}
//read up to initlen
if (pos < initlen){
int len = initlen - pos;
if (len > buf_size){
len = buf_size;
}
ifs.read(reinterpret_cast<std::basic_istream<char>::char_type*>(buf), len);
return ifs.gcount();//we don't bother skipping past the init segment
}
if (pos < start_byte){
//seek to the start byte
ifs.seekg(start_byte);
if (!ifs.good()){
LWARN("Failed to seek to segment start");
return AVERROR(EINVAL);
}
pos = start_byte;
}
//and read up to the end
int len = end_byte - pos;
if (len > buf_size){
len = buf_size;
}
ifs.read(reinterpret_cast<std::basic_istream<char>::char_type*>(buf), len);
return ifs.gcount();
}
int64_t CFMP4::seek(void *opaque, int64_t offset, int whence){
CFMP4* stream = static_cast<CFMP4*>(opaque);
return stream->seek(offset, whence);
}
int64_t CFMP4::seek(int64_t offset, int whence){
if (ifs.fail()){
return AVERROR(EINVAL);
}
//should we return an error if the final position is at EOF or our virtual EOF?
if (whence == SEEK_CUR){
auto pos = ifs.tellg();
int target = pos + offset;
if (pos < start_byte && target >= initlen){
target -= start_byte - initlen;
}
ifs.seekg(target);
pos = ifs.tellg();
if (pos > initlen){
pos -= start_byte - initlen;
}
return pos;
} else if (whence == SEEK_SET){
if (offset >= initlen){
offset += start_byte - initlen;
}
ifs.seekg(offset);
auto pos = ifs.tellg();
if (pos > initlen){
pos -= start_byte - initlen;
}
return pos;
} else if (whence == SEEK_END){
auto target = end_byte + offset;
if (target > end_byte){
ifs.seekg(end_byte);
return AVERROR_EOF;
}
if (target >= start_byte){
ifs.seekg(target);
auto start_pos = (start_byte - initlen);
return ifs.tellg() - static_cast<std::streampos>(start_pos);
}
target -= start_byte - initlen;
if (target < 0){
return AVERROR(EINVAL);//error, before the file
}
ifs.seekg(target);
return ifs.tellg();
} else {
return AVERROR(EINVAL);
}
}
std::string CFMP4::get_url(void){
return "cfmp4://" + std::to_string(start_byte);//this isn't really a full URL...currently dead code so meh
}
| 5,299
|
C++
|
.cpp
| 159
| 27.08805
| 157
| 0.575639
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,969
|
event_notification.hpp
|
edman007_chiton/event_notification.hpp
|
#ifndef __EVENT_NOTIFICATION_HPP__
#define __EVENT_NOTIFICATION_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#include "chiton_ffmpeg.hpp"
#include "chiton_config.hpp"
class EventNotification;
#include "event_controller.hpp"
//this class runs all motion detection algorithms
class EventNotification : public Module<EventNotification, EventController> {
public:
EventNotification(Config &cfg, Database &db, EventController &controller, const std::string &name) : Module<EventNotification, EventController>(cfg, db, controller, name) {};
virtual ~EventNotification() {};
virtual bool send_event(Event &e) = 0;//Send the event through notification method
};
#endif
| 1,574
|
C++
|
.h
| 36
| 41.722222
| 178
| 0.677966
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,970
|
mariadb_result.hpp
|
edman007_chiton/mariadb_result.hpp
|
#ifndef __MARIADB_RESULT_HPP__
#define __MARIADB_RESULT_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "database_result.hpp"
#include <mysql/mysql.h>
#include <vector>
class MariaDBResult : public DatabaseResult {
public:
MariaDBResult(MYSQL_RES *res) : res(res) {};
~MariaDBResult();
int field_count(void);
long num_rows(void);
const std::string& col_name(unsigned int col);
const std::string& get_field(unsigned int col);
const long get_field_long(unsigned int col);//get the data from the specified column as a long
const long long get_field_ll(unsigned int col);//get the data from the specified column as a long long
const double get_field_double(unsigned int col);//get the data from the specified column as a double
bool next_row(void);
bool field_is_null(unsigned int col);
private:
MYSQL_RES *res;
MYSQL_ROW row = NULL;
unsigned int col_count = 0;
std::vector<std::string> col_names;
std::vector<std::string> col_data;
void fetch_col_names(void);//fills the vector col_names with the names of all columns
static const std::string null_txt;//we return this NULL string when we hit a bad value to keep on going
};
#endif
| 2,096
|
C++
|
.h
| 49
| 39.571429
| 107
| 0.670113
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,971
|
event.hpp
|
edman007_chiton/event.hpp
|
#ifndef __EVENT_HPP__
#define __EVENT_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#include "chiton_ffmpeg.hpp"
#include "chiton_config.hpp"
#ifdef HAVE_OPENCV
#include "cv_target_rect.hpp"
#endif
//this class is a single event instance
class Event {
public:
Event(Config &cfg);
~Event();
void clear();//initilizes the event for future use
void invalidate(void);//marks the event as invalid
bool is_valid(void);//return if this Event is currently in use
//must set timestamp and source
//frame and position should be set for video
bool set_timestamp(struct timeval &etime);//set the timestamp of the event (currently, the timestamp of the thumbnail)
const struct timeval &get_timestamp(void);//get the timestamp of the event
bool set_position(float x0, float y0, float x1, float y1);//set the position of the event
const std::vector<float>& get_position();//returns a vector of 4 float, in this order: x0, y0, x1, y1
#ifdef HAVE_OPENCV
bool set_position(const TargetRect &rect);//set the position of the event
#endif
bool set_frame(const AVFrame *frame);//set the frame
const AVFrame* get_frame(void);//return the frame that the event was found in
bool set_source(const std::string &name);//set the name of the source module
const std::string& get_source(void);//get the name of the source module
bool set_score(float score);//set the score of the event (0-100)
float get_score(void);//get the score of the event (0-100)
private:
Config &cfg;
AVFrame *src;
struct timeval time;
std::vector<float> pos;
std::string source;
bool valid;
float score;
};
#endif
| 2,563
|
C++
|
.h
| 62
| 38.241935
| 122
| 0.678844
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,972
|
module.hpp
|
edman007_chiton/module.hpp
|
#ifndef __MODULE_HPP__
#define __MODULE_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#include "chiton_ffmpeg.hpp"
#include "chiton_config.hpp"
template <class Mod, class Controller> class Module;
#include "module_controller.hpp"
//this is the base Module that all modules must implement
//Mod is a class derived from Module<> and Controller is a class derived from a ModuleController<>
template <class Mod, class Controller> class Module {
public:
Module(Config &cfg, Database &db, Controller &controller, const std::string &name) : cfg(cfg), db(db), controller(controller), name(name) {};
virtual ~Module() {};
const std::string& get_name(void) const { return name; };//return the name of the algorithm
static const std::string& get_mod_name(void) { return "unknown"; };//return the name of the algorithm (statically)
virtual bool init(void) {return true;};//called immeditly after the constructor to allow dependicies to be setup
protected:
Config &cfg;
Database &db;
Controller &controller;
std::string name;
};
//this is used by the controller to allocate the module (T=DerivedModule, V=DerivedModuleController
template <class T, class U> class ModuleAllocator {
public:
virtual ~ModuleAllocator() {};
virtual T* allocate(Config &cfg, Database &db, U &controller) = 0;//allocate a module, ModuleFactory provides an implementation
virtual const std::string& get_name(void) = 0;//return the name of the module, ModuleFactory provides an implementation
};
//use this to register a new module with the controller
//T=ModuleClass, U=ModuleBase, V=moduleController
template <class T, class U, class V> class ModuleFactory : public ModuleAllocator<U, V> {
U* allocate(Config &cfg, Database &db, V &controller) { return new T(cfg, db, controller); };//constructs a new Module with given base and controller
const std::string& get_name(void) { return T::get_mod_name(); };//returns the name of the referenced Module with given base and controller
};
#endif
| 2,911
|
C++
|
.h
| 57
| 48.631579
| 153
| 0.700843
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,973
|
motion_cvresize.hpp
|
edman007_chiton/motion_cvresize.hpp
|
#ifndef __MOTION_ALGO_CVRESIZE_HPP__
#define __MOTION_ALGO_CVRESIZE_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#ifdef HAVE_OPENCV
#include "motion_algo.hpp"
#include "filter.hpp"
#include "motion_opencv.hpp"
#include <opencv2/core.hpp>
class MotionCVResize : public MotionAlgo {
public:
MotionCVResize(Config &cfg, Database &db, MotionController &controller);
~MotionCVResize();
bool process_frame(const AVFrame *frame, bool video);//process the frame, return false on error
bool set_video_stream(const AVStream *stream, const AVCodecContext *codec);//identify the video stream
bool init(void);//called immeditly after the constructor to allow dependicies to be setup
static const std::string& get_mod_name(void);//return the name of the algorithm
const cv::UMat& get_UMat(void) const;//return the UMat (CV_8UC1) for this frame
float get_scale_ratio(void) const;//return the scale ratio (0-1)
private:
cv::UMat buf_mat;//the output UMat
float scale_ratio;//the configured scale ratio
MotionOpenCV *ocv;//the ocv source object
};
#endif
#endif
| 1,989
|
C++
|
.h
| 46
| 40.76087
| 106
| 0.684889
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,974
|
stream_unwrap.hpp
|
edman007_chiton/stream_unwrap.hpp
|
#ifndef __STREAM_UNWRAP_HPP__
#define __STREAM_UNWRAP_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include "chiton_ffmpeg.hpp"
#include "io/io_wrapper.hpp"
#include <list>
#include <vector>
#include <map>
#include <deque>
class StreamUnwrap {
/*
* Handles the Network half of the video
*
*/
public:
StreamUnwrap(Config& cfg);
~StreamUnwrap();
bool connect(void);//returns true on success
bool connect(IOWrapper &io);//returns true on success, uses IOWrapper as the source
bool close(void);//close the connection
AVCodecContext* get_codec_context(AVStream *stream);//return the decode context for a given stream, creating the context if required
AVFormatContext* get_format_context(void);
unsigned int get_stream_count(void);
bool get_next_frame(AVPacket *packet);//writes the next frame out to packet, returns true on success, false on error (end of file)
bool decode_packet(AVPacket *packet);//reads packet and decodes it
bool get_decoded_frame(int stream, AVFrame *frame);//gets the next decoded frame
bool peek_decoded_vframe(AVFrame *frame);//gets the next previously decoded video frame without popping it off the stack
void unref_frame(AVPacket *packet);//free resources from frame
void timestamp(const AVPacket *packet, struct timeval &time);//write the actual timestamp of packet to time
void timestamp(const AVFrame *frame, int stream_idx, struct timeval &time);//write the actual timestamp of frame to time
bool is_audio(const AVPacket *packet);//return true if packet is audio packet
bool is_video(const AVPacket *packet);//return true if packet is video packet
AVStream *get_stream(const AVPacket *packet);//return a pointer to the stream that packet is part of
AVStream *get_stream(const int id);//return a pointer to the stream given the stream index
AVStream *get_audio_stream(void);//return a pointer to the best audio stream, NULL if none exists
AVStream *get_video_stream(void);//return a pointer to the best video stream, NULL if none exists
bool charge_video_decoder(void);//starts the decoder by decoding the first packet
double get_mean_delay(void) const;//return the mean packet delay (the estimated time it took ffmpeg to receive the packet)
double get_mean_duration(void) const;//return the mean duration of packets received
const struct timeval& get_start_time(void);
private:
const std::string url;//the URL of the camera we are connecting to
Config& cfg;
void dump_options(AVDictionary* dict);
bool charge_reorder_queue(void);//loads frames until the reorder queue is full
void sort_reorder_queue(void);//ensures the last frame is in the correct position in the queue, sorting it if required
bool read_frame(void);//read the next frame (internally used)
bool alloc_decode_context(unsigned int stream);//alloc the codec context, returns true if the context exists or was allocated
bool get_next_packet(AVPacket *packet);//return the next packet, without looking at the previous packets used for encoder charging
bool get_decoded_frame_int(int stream, AVFrame *frame);//get the next decoded frame, without looking at the decoded video buffer
void record_delay(const struct timeval &start, const struct timeval &end);//record the receive delay (to try and guess if it blocked)
AVFormatContext *input_format_context;
std::map<int,AVCodecContext*> decode_ctx;//decode context for each stream
unsigned int reorder_len;//length of the queue that we look to reorder packets in
std::list<AVPacket*> reorder_queue;//the reorder queue
struct timeval connect_time;//time effective time of the connection (adjusted for long term errors)
int max_sync_offset;
double timeshift_mean_delay;//the current mean delay
double timeshift_mean_duration;//the current mean duration
//to support early decoding, we can decode into these
std::deque<AVPacket*> decoded_packets;
std::deque<AVFrame*> decoded_video_frames;
static enum AVPixelFormat get_frame_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts);
};
#endif
| 5,062
|
C++
|
.h
| 86
| 54.988372
| 137
| 0.728814
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,975
|
config_parser.hpp
|
edman007_chiton/config_parser.hpp
|
#ifndef __CONFIG_PARSER_HPP__
#define __CONFIG_PARSER_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include <fstream>
#include <sstream>
class ConfigParser {
public:
ConfigParser(Config& cfg, std::ifstream& ifs) : cfg(cfg), ifs(ifs) {};
void parse(void);//reads the config and sets all values found into cfg
private:
Config& cfg;
std::ifstream& ifs;
void reset_parser(void);
char c;
std::stringbuf key;
std::stringbuf value;
enum {
BEFORE_KEY,
IN_KEY,
AFTER_KEY,
BEFORE_VAL,
IN_VAL,
AFTER_VAL,
IN_COMMENT
} state;
bool escape = false;//if we are escaping the next char
bool doublequote = false;//we are inside double quotes
bool singlequote = false;//we are inside single quotes
//position info
int line = 1;
int pos = 0;
bool next();//gets a character and updates position information
void report_parse_error(void);
};
#endif
| 1,878
|
C++
|
.h
| 56
| 29.428571
| 75
| 0.630846
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,976
|
database_result.hpp
|
edman007_chiton/database_result.hpp
|
#ifndef __DATABASE_RESULT_HPP__
#define __DATABASE_RESULT_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include <map>
#include <string>
class DatabaseResult {
public:
virtual int field_count(void) = 0;
virtual long num_rows(void) = 0;
virtual const std::string& col_name(unsigned int col) = 0;
virtual bool next_row(void) = 0;//preps the next row for access, returns true if one exists
virtual const std::string& get_field(unsigned int col) = 0;//get the data from the specified column as a string, data is valid until next call to next_row()
virtual const long get_field_long(unsigned int col) = 0;//get the data from the specified column as a long
virtual const long long get_field_ll(unsigned int col) = 0;//get the data from the specified column as a long long
virtual const double get_field_double(unsigned int col) = 0;//get the data from the specified column as a double
virtual bool field_is_null(unsigned int col) = 0;
virtual ~DatabaseResult() {};
};
#endif
| 1,884
|
C++
|
.h
| 39
| 45.692308
| 160
| 0.668295
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,977
|
chiton_ffmpeg.hpp
|
edman007_chiton/chiton_ffmpeg.hpp
|
#ifndef __CHITON_FFMPEG_HPP__
#define __CHITON_FFMPEG_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libavutil/timestamp.h>
#include <libavutil/avutil.h>
#include <libavutil/opt.h>
#include <libavutil/channel_layout.h>
#include <libavutil/imgutils.h>
#include <libavutil/hwcontext.h>
};
#include <mutex>
#include <vector>
#include <map>
#ifdef HAVE_VDPAU
#include <vdpau/vdpau.h>
#include <libavutil/hwcontext_vdpau.h>
#endif
#ifdef HAVE_VAAPI
#include <libavutil/hwcontext_vaapi.h>
#endif
#ifdef HAVE_OPENCL
#include <libavutil/hwcontext_opencl.h>
#endif
//fix FFMPEG and c++1x issues
#ifdef av_err2str
#undef av_err2str
av_always_inline char* av_err2str(int errnum){
thread_local static char str[AV_ERROR_MAX_STRING_SIZE];
memset(str, 0, sizeof(str));
return av_make_error_string(str, AV_ERROR_MAX_STRING_SIZE, errnum);
}
#endif
#ifdef av_ts2timestr
#undef av_ts2timestr
av_always_inline char* av_ts2timestr(int64_t ts, AVRational * tb){
thread_local static char str[AV_TS_MAX_STRING_SIZE];
memset(str, 0, sizeof(str));
return av_ts_make_time_string(str, ts, tb);
}
#endif
#ifdef av_ts2str
#undef av_ts2str
av_always_inline char* av_ts2str(int64_t ts){
thread_local static char str[AV_TS_MAX_STRING_SIZE];
memset(str, 0, sizeof(str));
return av_ts_make_string(str, ts);
}
#endif
#ifdef av_fourcc2str
#undef av_fourcc2str
av_always_inline char* av_fourcc2str(uint32_t fourcc){
thread_local static char str[AV_FOURCC_MAX_STRING_SIZE];
memset(str, 0, sizeof(str));
return av_fourcc_make_string(str, fourcc);
}
#endif
//make AVRounding valid in bitwise operations
inline AVRounding operator|(AVRounding a, AVRounding b)
{
return static_cast<AVRounding>(static_cast<int>(a) | static_cast<int>(b));
}
/*
* Utility/Mangement class for libav* and ffmpeg things
*/
class CFFUtil {
public:
CFFUtil(void);
~CFFUtil(void);
void load_ffmpeg(void);//init ffmpeg
void free_hw(void);//free/close HW encoder/decoders
void lock(void);//global ffmpeg lock/unlock
void unlock(void);
//return a ref or null to the context iff it can handle wxh
AVBufferRef *get_vaapi_ctx(AVCodecID codec_id, int codec_profile, int width, int height);
AVBufferRef *get_vdpau_ctx(AVCodecID codec_id, int codec_profile, int width, int height);
AVBufferRef *get_opencl_ctx(AVCodecID codec_id, int codec_profile, int width, int height);
bool have_vaapi(AVCodecID codec_id, int codec_profile, int width, int height);//returns true if VAAPI should work
bool have_vdpau(AVCodecID codec_id, int codec_profile, int width, int height);//returns true if VDPAU should work
bool have_opencl(AVCodecID codec_id, int codec_profile, int width, int height);//returns true if OPENCL should work
bool have_v4l2(AVCodecID codec_id, int codec_profile, int width, int height);//returns true if v4l2 should work
bool sw_format_is_hw_compatable(const enum AVPixelFormat pix_fmt);//return true if the format is HW compatable
std::string get_sw_hw_format_list(Config &cfg, const AVFrame *frame, AVCodecID codec_id, int codec_profile);//return the suggested list of formats for use with later HW functions
int get_ff_log_level(void) const;//return the ffmpeg log level
void set_ff_log_level(int lvl);//set the ffmpeg log level
private:
void load_vaapi(void);//init global vaapi context
void free_vaapi(void);//free the vaapi context
void load_vdpau(void);//init global vdpau context
void free_vdpau(void);//free the vdpau context
void load_opencl(void);//init global opencl context
void free_opencl(void);//free the opencl context
#ifdef HAVE_VDPAU
int get_vdpau_profile(const AVCodecID codec_id, const int codec_profile, VdpDecoderProfile *profile);//get the VDPAU Profile
#endif
#ifdef HAVE_V4L2
bool have_v4l2_dev(int devfd, AVCodecID codec_id, int codec_profile, int width, int height);//check v4l2 capabilities of device
bool vioctl(int fh, int request, void *arg);//run ioctl through v4l2, return false on error
bool is_v4l2_hw_codec(const AVCodecID av_codec, const uint32_t v4l2_pix_fmt);
#endif
#ifdef HAVE_VAAPI
AVPixelFormat get_pix_fmt_from_va(const VAImageFormat &fmt);
VAProfile get_va_profile(AVVAAPIDeviceContext* hwctx, AVCodecID codec_id, int codec_profile);//return the VAProfile for the codec
#endif
AVBufferRef *vaapi_ctx = NULL;
bool vaapi_failed = false;//if we failed to initilize vaapi
AVBufferRef *vdpau_ctx = NULL;
bool vdpau_failed = false;//if we failed to initilize vdpau
AVBufferRef *opencl_ctx = NULL;
bool opencl_failed = false;//if we failed to initilize opencl
std::mutex codec_lock;
int max_ffmpeg_log_level;//max log level for FFMpeg messages
};
enum AVPixelFormat get_vaapi_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts);//global VAAPI format selector
enum AVPixelFormat get_vdpau_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts);//global VDPAU format selector
enum AVPixelFormat get_sw_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts);//global SW format selector that prefers VAAPI compatible formats
//helper functions to cast FFMPeg HW Context to the native context
#ifdef HAVE_VAAPI
AVVAAPIDeviceContext *get_vaapi_ctx_from_device(AVBufferRef *buf);//get VAAPI context from HW Device ctx
AVVAAPIDeviceContext *get_vaapi_ctx_from_frames(AVBufferRef *buf);//get VAAPI context from HW Frames Ctx
#endif
#ifdef HAVE_OPENCL
AVOpenCLDeviceContext *get_opencl_ctx_from_device(AVBufferRef *buf);//get OpenCL context from HW Device ctx
AVOpenCLDeviceContext *get_opencl_ctx_from_frames(AVBufferRef *buf);//get OpenCL context from HW Frames Ctx
#endif
extern CFFUtil gcff_util;//global FFmpeg lib mangement class
//for passing image coordinates
struct rect { int x, y, w, h; };
#endif
| 6,843
|
C++
|
.h
| 153
| 42.130719
| 182
| 0.741157
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,979
|
chiton_config.hpp
|
edman007_chiton/chiton_config.hpp
|
#ifndef __CHITON_CONFIG_HPP__
#define __CHITON_CONFIG_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
//we like new stuff
#define _XOPEN_SOURCE 700
#define CL_TARGET_OPENCL_VERSION 300
#include <string>
#include <map>
/* Autoconf parameters */
#include "config_build.hpp"
#include "database.hpp"
//we have to have valid values for these, these are the defaults when the user sets a bad value
const long DEFAULT_SECONDS_PER_SEGMENT = 6;//Apple recommends 6 seconds per file to make live streaming reasonable
const long DEFAULT_MIN_FREE_SPACE = 1073741824;//1G in bytes
const std::string EXPORT_EXT = ".mp4";
class Config {
public:
Config();//init an empty Config database
Config(const Config &src);//init with the same db as some other Config
bool load_config(const std::string& path);//load the config from the path
bool load_camera_config(int camera, Database &db);//load the config from the database for a specific camera
const std::string& get_value(const std::string& key);
int get_value_int(const std::string& key);//returns the value as an int
long get_value_long(const std::string& key);//returns the value as a long
long long get_value_ll(const std::string& key);//returns the value as a long long
double get_value_double(const std::string& key);//returns the value as an double
void set_value(const std::string& key, const std::string& value);
private:
std::map<std::string,std::string> cfg_db;
const std::string EMPTY_STR = "";
const std::string & get_default_value(const std::string& key);
};
#endif
| 2,450
|
C++
|
.h
| 53
| 43.54717
| 114
| 0.686555
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,980
|
setting.hpp
|
edman007_chiton/setting.hpp
|
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include <vector>
#include "config_build.hpp"
/*
* This file is included by config.cpp to provide default values
*
* This file is also converted to php, as such it must contain just the config
* definitions and no C++ code other than that below the "PHP BELOW" comment
*
*/
// priorties need to be manually copied into web/inc/configdb.php.in
enum SettingPriority {
SETTING_READ_ONLY,//Not settable via the database, cannot be set to anything meaningful after starting, may contain useful information
SETTING_REQUIRED_SYSTEM,//system requirement, that is always used and does not have a sane default
SETTING_OPTIONAL_SYSTEM,//optional system requirement
SETTING_REQUIRED_CAMERA,//required to be set on all cameras
SETTING_OPTIONAL_CAMERA,//optional extra feature for cameras
};
/*
* Defines the format of settings, changes here will drive updates to web_config.php
*/
struct Setting {
std::string key;//the key name
std::string def;//default
std::string short_description;//human readable name
std::string description;//full length description
SettingPriority priority;//priority
};
//comments starting with @key become long documentation
const std::vector<Setting> setting_options {
//DO NOT REMOVE THE COMMENT BELOW
//PHP BELOW
/* Ignore Comment to fix AWK script
*/
{"database-version", "0", "Database Version", "Updated to track the internal state of the database", SETTING_READ_ONLY},
/* @database-version Internal use only
*/
{"cfg-path", "", "Config File", "Path to the config file that is loaded", SETTING_READ_ONLY},
/* @cfg-path Only has effect when set via the command line.
* This is passed on the command line to set the location of the configuration file
*/
{"pid-file", "", "PID File", "path to write the PID to", SETTING_READ_ONLY},
{"fork", "0", "Fork", "Set to non-zero to fork to the background", SETTING_READ_ONLY},
{"privs-user", "", "System User", "System Username to drop privs to (the daemon runs as this user)", SETTING_READ_ONLY},
{"db-host", "", "Database Host", "The hostname of the database to connect to", SETTING_READ_ONLY},
{"db-user", "", "Database User", "The username to use when connecting to the database", SETTING_READ_ONLY},
{"db-password", "", "Database Password", "The password to use when connecting to the database", SETTING_READ_ONLY},
{"db-database", "", "Database Name", "The name of the database on the database server to use", SETTING_READ_ONLY},
{"db-socket", "", "Database Socket", "Socket path to socket for DB server", SETTING_READ_ONLY},
{"db-port", "", "Database Port", "Port to connect to (if not local) of the database", SETTING_READ_ONLY},
{"verbosity", "3", "Verbosity", "Logging verbosity (higher is more verbose, lower is less verbose, range 0-5)", SETTING_OPTIONAL_SYSTEM},
{"log-history-len", "50", "Log History Length <0+>", "Length of the message log (for each camera)", SETTING_OPTIONAL_SYSTEM},
{"timezone", "system", "Timezone", "The timezone to use, if set to \"system\" will use the system timezone)", SETTING_OPTIONAL_SYSTEM},
{"video-url", "", "Video URL", "FFMPEG compatible URL for the camera", SETTING_REQUIRED_CAMERA},
{"active", "0", "Camera Active", "set to 1 when the camera is active", SETTING_REQUIRED_CAMERA},
{"camera-id", "", "Camera ID", "Used internally to track what is the active camera", SETTING_READ_ONLY},
{"output-dir", "", "Output Directory", "The location to store videos", SETTING_REQUIRED_SYSTEM},
/* @output-dir Eventually this is planned to work on a per-camera basis, however this has not been implemented yet,
* setting it for a specific camera may cause undefined behavior
*/
{"ffmpeg-demux-options", "", "FFMPEG demux options", "Options for the ffmpeg demuxer", SETTING_OPTIONAL_CAMERA},
/* @ffmpeg-demux-options These are option passed to libavformat when demuxing (reading a stream), see man ffmpeg-formats
*/
{"ffmpeg-mux-options", "", "FFMPEG mux options", "Options for the ffmpeg muxer", SETTING_OPTIONAL_CAMERA},
/* @ffmpeg-mux-options These are option passed to libavformat when muxing (writing a stream), see man ffmpeg-formats
*/
{"reorder-queue-len", "0", "Reorder queue length", "How many packets to cache to properly resort frames "
"(required for some cameras that give us out of order data even on TCP)", SETTING_OPTIONAL_CAMERA},
/* @reorder-queue-len Specifically implemented for reolink cameras that transmit packets out of order, this will reorder those parkets and correct
* some types of stream corruption
*/
{"interleave-queue-depth", "4", "Interleaving Queue Depth", "How many packets to look when writing to verify the duration is always correct. "
"Should be large enough to ensure the queue contains at least 2 of every packet type", SETTING_OPTIONAL_CAMERA},
/* @reorder-queue-len Specifically implemented for reolink cameras that transmit packets out of order, this will reorder those parkets and correct
* some types of stream corruption
*/
{"seconds-per-file", "360", "Seconds per file", "How long a file should be, files are split at the next opprotunity after this, in seconds", SETTING_OPTIONAL_SYSTEM},
/* @seconds-per-file when using fMP4, this is the length of the individual mp4 files and it is also the unit size that is deleted when removing old videos
*/
{"seconds-per-segment", "6", "Seconds per segment", "How long a segment should be, files are segmented at the next opprotunity after this, in seconds, Apple recommends 6", SETTING_OPTIONAL_SYSTEM},
/* @seconds-per-segment Smaller values can improve latency and give finer control of when skipping the video, however it produces more records in the database
* and results in larger .m3u8 files to the browser. Smaller values can also allow you to view closer to realtime video in the web player. Setting this to a value less than the period
* between keyframes results in the period between keyframes being the controlling factor.
*/
{"min-free-space", "1073741824", "Miniumn Free Space", "How many bytes of free space triggers a cleanup, if it contains a %, "
"it is the target free-percentage of user accessable space", SETTING_OPTIONAL_SYSTEM},
/* @min-free-space Needs to be at least enough to accomidate 10 seconds of recording
*/
{"display-name", "", "Camera Name", "The name of the camera used in displays", SETTING_OPTIONAL_CAMERA},
{"max-sync-offset", "5", "Max Sync Offset", "The maximum drift in camera time tolerated before we resync the clock", SETTING_OPTIONAL_CAMERA},
{"socket-path", DEFAULT_SOCKET_PATH, "Control Socket Path", "The path for the control socket, required to manage the system from the web interface", SETTING_OPTIONAL_SYSTEM},
{"broken-time-offset", "3600", "Broken Segment Future Offset", "Number of seconds in the future that will cause segments to be deleted", SETTING_OPTIONAL_SYSTEM},
{"encode-format-video", "copy", "Video Encoding codec <copy|h264|hevc>", "The codec to save video with, copy will use the camera compressed video if compatible", SETTING_OPTIONAL_CAMERA},
{"encode-format-audio", "copy", "Audio Encoding codec <copy|none|aac|ac3>", "The codec to save video with, copy will use the camera compressed video if compatible", SETTING_OPTIONAL_CAMERA},
{"ffmpeg-encode-audio-opt", "", "FFMPEG audio encode options", "Options for the ffmpeg encoder - audio", SETTING_OPTIONAL_CAMERA},
{"ffmpeg-encode-video-opt", "", "FFMPEG video encode options", "Options for the ffmpeg encoder - video", SETTING_OPTIONAL_CAMERA},
{"ffmpeg-decode-audio-opt", "", "FFMPEG audio decode options", "Options for the ffmpeg decoder - audio", SETTING_OPTIONAL_CAMERA},
{"ffmpeg-decode-video-opt", "", "FFMPEG video decode options", "Options for the ffmpeg decoder - video", SETTING_OPTIONAL_CAMERA},
{"audio-bitrate", "auto", "audio bitrate", "Bitrate, in kbps, to encode the audio at (or 'auto' to autoselect)", SETTING_OPTIONAL_CAMERA},
{"video-bitrate", "auto", "video bitrate", "Bitrate, in kbps, to encode the video at (or 'auto' to autoselect)", SETTING_OPTIONAL_CAMERA},
{"output-extension", ".mp4", "Output Extension <.ts|.mp4>", "HLS Output Format, .ts for mpeg-ts files, .mp4 for fragmented mp4", SETTING_OPTIONAL_CAMERA},
{"video-encode-method", "auto", "Video Encode method <auto|sw|vaapi|v4l2>", "Method to use for encoding, vaapi and v4l2 are the supported HW encoders,"
" auto tries both HW decoders before defaulting to SW, SW is a fallback", SETTING_OPTIONAL_CAMERA},
{"video-decode-method", "auto", "Video Decode method <auto|sw|vaapi|vdpau|v4l2>", "Method to use for decoding, vaapi, vdpau, and v4l2 are supported HW decoders,"
" auto tries both HW decoders before defaulting to SW, SW is a fallback", SETTING_OPTIONAL_CAMERA},
{"video-hw-pix-fmt", "auto", "Video pixel format <auto|[fmt]>", "Pixel format to use, auto or any valid ffmpeg format is accepted,"
" but not all will work with your HW", SETTING_OPTIONAL_CAMERA},
{"log-color-fatal", "5", "Color for CLI FATAL error Messages <1..255>", "ANSI color code for use on CLI", SETTING_OPTIONAL_SYSTEM},
{"log-color-error", "1", "Color for CLI ERROR error Messages <1..255>", "ANSI color code for use on CLI", SETTING_OPTIONAL_SYSTEM},
{"log-color-warn", "3", "Color for CLI WARN error Messages <1..255>", "ANSI color code for use on CLI", SETTING_OPTIONAL_SYSTEM},
{"log-color-info", "6", "Color for CLI INFO error Messages <1..255>", "ANSI color code for use on CLI", SETTING_OPTIONAL_SYSTEM},
{"log-color-debug", "2", "Color for CLI DEBUG error Messages <1..255>", "ANSI color code for use on CLI", SETTING_OPTIONAL_SYSTEM},
{"log-color-enabled", "1", "Enable CLI color <1|0>", "Enable Color Logging", SETTING_OPTIONAL_SYSTEM},
{"log-name-length", "16", " Logging Camera Name Length", "Maxiumn Length of thread name (typically the camera) to copy into log messages", SETTING_OPTIONAL_SYSTEM},
{"motion-mods", "cvdetect", "Motion Algorithms <none|abc[,xyz...]>", "List of motion algorithms to run against, ',' delimited", SETTING_OPTIONAL_CAMERA},
/* @motion-mods Current modules are: cvbackground (computes an average background), cvdebugshow (if compiled with debug support, shows the frames being processed),
cvdetect (performs motion detection), cvmask (subtracts the background to identify changed areas), opencv (converts frames into opencv for processing)
*/
{"event-mods", "db,console", "Event Notification Algorithms <none|abc[,xyz...]>", "List of Event Notification algorithms to run against, ',' delimited", SETTING_OPTIONAL_CAMERA},
/* @event-mods Current modules are db (writes events to the databse) and console (prints events to logs)
*/
{"motion-cvmask-tau", "0.01", "Motion CVMask Tau <0-1>", "Tau parameter for CVMask Algorithm", SETTING_OPTIONAL_CAMERA},
{"motion-cvmask-beta", "15.0", "Motion CVMask Tau <0.0-255.0>", "Beta parameter for CVMask Algorithm", SETTING_OPTIONAL_CAMERA},
{"motion-cvmask-threshold", "20", "Motion CVMask Threshold <1-255>", "Threshold parameter for CVMask Algorithm", SETTING_OPTIONAL_CAMERA},
{"motion-cvmask-delay", "30", "Motion CVMask Threshold <1-600>", "Frame Delay Count before applying sensitivity mask", SETTING_OPTIONAL_CAMERA},
{"motion-cvdetect-dist", "150.0", "Motion CVDetect Miniumn Distance <0-10000>", "Miniumn distance between objects to count as two objects", SETTING_OPTIONAL_CAMERA},
{"motion-cvdetect-area", "1000.0", "Motion CVDetect Miniumn Area <0->", "Miniumn area of an object to send motion events", SETTING_OPTIONAL_CAMERA},
{"motion-cvdetect-tracking", "10", "Motion CVDetect Tracking Time <0->", "Number of frames that an object must be tracked to trigger an event", SETTING_OPTIONAL_CAMERA},
{"motion-cvbackground-tau", "0.001", "Motion CVBackground Tau <0-1>", "Tau parameter for CVBackground Algorithm", SETTING_OPTIONAL_CAMERA},
{"motion-opencv-map-indirect", "true", "Motion OpenCV Indirect Mapping <true|false>", "Use libva to map the image and copy the brightness, "
"recommended for AMD GPUs", SETTING_OPTIONAL_CAMERA},
{"motion-opencv-map-cl", "true", "Motion OpenCV OpenCL Mapping <true|false>", "Use ffmpeg to map it to opencl, and map that buffer directly to opencv", SETTING_OPTIONAL_CAMERA},
{"motion-opencv-map-vaapi", "true", "Motion OpenCV's VA-API Mapping <true|false>", "Use OpenCV to map the direct VA-API buffer", SETTING_OPTIONAL_CAMERA},
{"motioncontroller-skip-ratio", "0.05", "Motion Controller Skip Ratio <0-1>", "The ratio of time that should be spent blocking waiting for packets, 0 disables motion controller "
"skipping, 1 will cause all frames to skip motion processing", SETTING_OPTIONAL_CAMERA},
{"video-encode-b-frame-max", "16", "Video Encode Maximum B-frames <0->", "Maximum B-frames when encoding", SETTING_OPTIONAL_CAMERA},
/* @video-encode-b-frame-max When encoding video, this is the maxium b-frames that the encoder should put out between keyframes
* Some encoders, such as the V4L2 encoder on the raspberry pi do not suppor this and it must be set to 0.
* Lower values generally reduce compression, higher values can cause seconds-per-segment to be exceeded
*/
{"motion-cvresize-scale", "1", "Motion Detection Scale ratio <0-1>", "Scale ratio for motion processing, 1 is no scaling, 0.5 is downscale 50%", SETTING_OPTIONAL_CAMERA},
{"ffmpeg-log-level", "40", "FFMpeg log level <-8-56>", "FFMpeg Log level, ffmpeg messages above this will not be printed", SETTING_OPTIONAL_SYSTEM},
/* @opencv-disable-opencl Useful to set to true when you have a buggy/broken OpenCL implementation. Note: Setting to "false"
* does not re-enable it even with a full system reload, application must be fully restarted to re-enable it.
*/
{"opencv-disable-opencl", "false", "Disable OpenCL Acceleration in OpenCV <true|false>", "Set to true to disable OpenCL use by OpenCV "
"(forces opencv motion detection to SW)", SETTING_OPTIONAL_CAMERA},
/* @opencv-opencl-device this is the same function as the environmental variable OPENCV_OPENCL_DEVICE, DRIVER is the platform reported by clinfo, TYPE is the accelerator type
* which can be CPU, GPU, etc. NAME is either the index <0-9> or the name of the card, leaving a parameter empty acts as a wild card, e.g. ':GPU:' is any GPU.
* See https://github.com/opencv/opencv/wiki/OpenCL-optimizations
*/
{"opencv-opencl-device", "", "OpenCV OpenCL Device <DRIVER:TYPE:NAME>", "OpenCV Device selection string, this is the configuration parameter", SETTING_OPTIONAL_CAMERA},
};
| 15,369
|
C++
|
.h
| 173
| 86.289017
| 198
| 0.730397
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,981
|
mariadb.hpp
|
edman007_chiton/mariadb.hpp
|
#ifndef __MARIADB_HPP__
#define __MARIADB_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "database.hpp"
#include <mysql/mysql.h>
#include "mariadb_result.hpp"
#include <mutex>
class MariaDB : public Database {
public:
int connect(const std::string& server, const std::string& db, const std::string& user, const std::string& pass, const int port, const std::string& socket);
void close(void);
MariaDB();
~MariaDB();
//escape a string
std::string escape(const std::string& str);
MariaDBResult* query(const std::string& query) __wur;
MariaDBResult* query(const std::string& query, long* affected_rows, long *insert_id);
private:
MYSQL *conn;//our server connection
MariaDBResult* query_nolock(const std::string& sql);
std::mutex mtx;
};
#endif
| 1,668
|
C++
|
.h
| 43
| 36.116279
| 159
| 0.650588
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,982
|
event_console.hpp
|
edman007_chiton/event_console.hpp
|
#ifndef __EVENT_CONSOLE_HPP__
#define __EVENT_CONSOLE_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "event_notification.hpp"
//this writes events to the console/logging
class EventConsole : public EventNotification {
public:
EventConsole(Config &cfg, Database &db, EventController &controller);
~EventConsole();
bool send_event(Event &e);//Send the event through notification method
static const std::string& get_mod_name(void);
private:
};
#endif
| 1,343
|
C++
|
.h
| 34
| 37.352941
| 75
| 0.653905
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,983
|
json_encoder.hpp
|
edman007_chiton/json_encoder.hpp
|
#ifndef __JSON_ENCODER_HPP__
#define __JSON_ENCODER_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include <string>
#include <map>
#include <vector>
//intended to be solely a wrapper to convert data to a json string
class JSONEncoder {
public:
JSONEncoder();
~JSONEncoder();
const std::string& str(void);//return the object as a string
//these are the setters
bool add(const std::string key, int val);
bool add(const std::string key, unsigned int val);
bool add(const std::string key, time_t val);
bool add(const std::string key, double val);
bool add(const std::string key, bool val);
bool add(const std::string key, const std::string &val);
bool add(const std::string key, const char* val);
bool add(const std::string key, JSONEncoder &val);
//array is unsupported so far, will implement when required
private:
std::string output;//output string
bool valid;//true if output is fully generated
std::map<std::string, std::string> data;
};
#endif
| 1,910
|
C++
|
.h
| 49
| 36.183673
| 75
| 0.658051
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,984
|
file_manager.hpp
|
edman007_chiton/file_manager.hpp
|
#ifndef __FILE_MANAGER_HPP__
#define __FILE_MANAGER_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include <string>
#include "database.hpp"
#include "chiton_config.hpp"
#include <mutex>
#include <atomic>
#include <iostream>
#include <fstream>
#include "stream_writer.hpp"
#include "system_controller.fwd.hpp"
class FileManager {
public:
FileManager(SystemController &sys);
FileManager(SystemController &sys, Config &cfg);//with alternate config
void init(void);//init's the FileManager
//returns a valid path starting at start_time, writes out it's ID to int &file_id, if extend_file is true, the previous filename is used
std::string get_next_path(long int &file_id, int camera, const struct timeval &start_time, bool extend_file = false);
//returns a path to export a file to, updating the database to include the path
std::string get_export_path(long int export_id, int camera, const struct timeval &start_time);
//generates and writes path and name given start_time and extension, returns true on success
//enters the image into the database if starttime is not NULL
//if starttime is NULL, path is kept as is
//name will be re-written to include the extension, if non-empty will become a prefix
//if file_id is non-null, then the ID is written to it if it was written to the db
bool get_image_path(std::string &path, std::string &name, const std::string &extension, const struct timeval *start_time = NULL, long *file_id = NULL);
//returns the real for the segments referenced as id and path name from the database
std::string get_path(long long name, const std::string &db_path, const std::string &ext);
//update metadata about the file
bool update_file_metadata(long int file_id, struct timeval &end_time, long long end_byte, const StreamWriter &out_file, long long start_byte = 0, long long init_len = -1);
void clean_disk(void);//clean up the disk by deleting files
void delete_broken_segments(void);//looks for impossible segments and wipes them
//delete specific file (not a segment), returns number of bytes removed (-1 if nothing deleted)
long long rm_file(const std::string &path, const std::string &base = std::string("NULL"));
bool reserve_bytes(long long bytes, int camera);//reserve bytes for camera
long long get_filesize(const std::string &path);//return the filesize of the file at path
//open and return a fstream for name located in path, if there was a failure fstream.is_open() will fail, path must end in /
std::ofstream get_fstream_write(const std::string &name, const std::string &path = "" , const std::string &base = "NULL");
std::ifstream get_fstream_read(const std::string &name, const std::string &path = "" , const std::string &base = "NULL");
private:
SystemController &sys;
Database &db;
Config &cfg;
long long bytes_per_segment;//estimate of segment size for our database to optimize our cleanup calls
long long min_free_bytes;//the config setting min-free-space as computed for the output-dir
std::string last_filename;//when extending files, holds the current filename
std::string last_dir;//when extending files, holds the current directory
//global variables for cleanup and space reseverations
static std::mutex cleanup_mtx;//lock when cleanup is in progress, locks just the clean_disk()
static std::atomic<long long> reserved_bytes;//total reserved bytes
bool mkdir_recursive(std::string path);
void rmdir_r(const std::string &path);//delete directory and all empty parent directories
long long get_target_free_bytes(void);//return the bytes that must be deleted
long long get_free_bytes(void);//return the free bytes on the disk
long long get_min_free_bytes(void);//return the miniumn free bytes on the disk
long long rm_segment(const std::string &base, const std::string &path, const std::string &id, const std::string &ext);//deletes a target segment, returns number of bytes removed
long long rm(const std::string &path);//delete a specific file and parent directories, returns negative if there was an error
std::string get_date_path(int camera, const struct timeval &start_time);//returns a path in the form of <camera>/<YYYY>/<MM>/<DD>/<HH>
std::string get_output_dir(void);//returns the output-dir cfg setting, with some fixups/sanity checks ensuring it always ends in a "/"
std::string get_real_base(const std::string base);//given an input base, returns a real path that always ends in a /
long long clean_images(unsigned long long start_time);//deletes images older than start_time, returns bytes deleted
long clean_events(unsigned long long start_time);//deletes events older than start_time, returns number deleted
};
#endif
| 5,663
|
C++
|
.h
| 85
| 62.917647
| 181
| 0.718525
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,985
|
database.hpp
|
edman007_chiton/database.hpp
|
#ifndef __DATABASE_HPP__
#define __DATABASE_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include <string>
#include "database_result.hpp"
class Database {
public:
/*
* Connect to the database, return 0 on success, non-zero on error
*/
virtual int connect(const std::string& server, const std::string& db, const std::string& user, const std::string& pass, const int port, const std::string& socket) = 0;
/*
* Disconnect from the database, following calls to connect() will succeed
*/
virtual void close(void) = 0;
//escape a string
virtual std::string escape(const std::string& str) = 0;
//returns a result if there is one, caller must call delete on it when done
virtual DatabaseResult* query(const std::string& query) __wur = 0;
//returns a result if there is one, caller must call delete on it when done
//if affected_rows is not null, will be set to the affected_row count in a thread safe manner
//if insert_id is not null, will be set to the last insert_id in a thread safe manner
virtual DatabaseResult* query(const std::string& query, long* affected_rows, long *insert_id) __wur = 0;
virtual ~Database() {};
};
#endif
| 2,078
|
C++
|
.h
| 46
| 41.891304
| 171
| 0.657256
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,986
|
system_controller.hpp
|
edman007_chiton/system_controller.hpp
|
#ifndef __SYSTEM_CONTROLLER_HPP__
#define __SYSTEM_CONTROLLER_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "main.hpp"
#include "util.hpp"
//#include "chiton_config.hpp"
#include "mariadb.hpp"
#include "camera.hpp"
#include <unistd.h>
#include <thread>
#include <list>
#include <set>
#include <stdlib.h>
#include "camera_status.hpp"
#include "database_manager.hpp"
#include "remote.hpp"
#include "export.hpp"
/*
* System Exit Codes
*/
const int SYS_EXIT_SUCCESS = 0;
const int SYS_EXIT_CFG_ERROR = 1;
const int SYS_EXIT_DB_ERROR = 2;
const int SYS_EXIT_DB_UPDATE_ERROR = 3;
const int SYS_EXIT_SIG_SHUTDOWN = 4;
const int SYS_EXIT_PRIVS_ERROR = 5;
/*
* SystemController:
* - This class manages all cameras, starting and stopping them
* - This class also manages access between cameras, the remote, and system functions
*/
class SystemController {
public:
enum CAMERA_STATE {
STOPPING = 0,
STARTING,
RUNNING,
RESTARTING
};
//args: initial args to initilize from, cfg-path must be set
SystemController(Config &args);
SystemController(const SystemController&) = delete;
~SystemController();
int run(void);//run the main program
void request_exit(void);//request that the program exits
void request_reload(void);//requests that all cameras are restarted
bool stop_cam(int id);//stop a given camera
bool start_cam(int id);//start the cam with given ID
bool restart_cam(int id);//restart tha cam with a given ID
void list_state(std::map<int, CAMERA_STATE> &stat);//writes to the map the state of all cameras
bool get_camera_status(int id, CameraStatus &status);//writes to status, the current CameraStatus object for the camera
//getters
Config& get_sys_cfg(void);
Database& get_db(void);
Export& get_export(void);
Remote& get_remote(void);
FileManager& get_fm(void);
private:
Config &system_args;
Config cfg;
std::unique_ptr<Database> db;
FileManager fm;
Export expt;
Remote remote;
std::atomic_bool exit_requested;
std::atomic_bool reload_requested;
std::list<Camera> cams;//all the currently running cameras
std::mutex cams_lock;//to manage access to the cameras, never lock after locking cams_set_lock, can only be locked before
//these lists are used to request camera's are stop/restarted and can be set from other threads
std::set<int> stop_cams_list;//cams stopped that need to be joined
std::set<int> start_cams_list;//list of cameras to start
std::set<int> startup_cams_list;//list of cameras currently in startup
std::mutex cam_set_lock;//lock to manage the two above sets
char timezone_env[256];//if timezone is changed from default, we need to store it in memory for putenv()
int run_instance(void);//run an instance of chiton (this exits upon reload)
void launch_cams(void);//launch all configured cameras
void loop(void);//execute the main loop
void load_sys_cfg(Config &cfg);
void stop_cams(void);//stop and join all required cams
void start_cams(void);//start all required cams
};
#endif
| 3,994
|
C++
|
.h
| 102
| 35.803922
| 125
| 0.694946
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,987
|
motion_cvdebugshow.hpp
|
edman007_chiton/motion_cvdebugshow.hpp
|
#ifndef __MOTION_ALGO_CVDEBUGSHOW_HPP__
#define __MOTION_ALGO_CVDEBUGSHOW_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#ifdef HAVE_OPENCV
#ifdef DEBUG
#include "motion_algo.hpp"
#include "motion_cvmask.hpp"
#include "motion_cvbackground.hpp"
#include "motion_cvdetect.hpp"
#include <opencv2/core.hpp>
//this algorithm will make a window and show a UMat
//it is NOT threadsafe in our arch, will will result in a deadlock when the camera restarts
//because imshow seems to reference the initial thread that made a window
class MotionCVDebugShow : public MotionAlgo {
public:
MotionCVDebugShow(Config &cfg, Database &db, MotionController &controller);
~MotionCVDebugShow();
bool process_frame(const AVFrame *frame, bool video);//process the frame, return false on error
bool set_video_stream(const AVStream *stream, const AVCodecContext *codec);//identify the video stream
static const std::string& get_mod_name(void);//return the name of the algorithm
bool init(void);//called immeditly after the constructor to allow dependicies to be setup
private:
MotionOpenCV *ocv;
MotionCVMask *cvmask;
MotionCVBackground *cvbackground;
MotionCVDetect *cvdetect;
cv::UMat normalized_buf;//used to convert float images to normalized
};
#endif
#endif
#endif
| 2,186
|
C++
|
.h
| 52
| 39.75
| 106
| 0.705772
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,988
|
filter.hpp
|
edman007_chiton/filter.hpp
|
#ifndef __HWLOAD_HPP__
#define __HWLOAD_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2021-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include "chiton_ffmpeg.hpp"
extern "C" {
#include <libavfilter/avfilter.h>
};
class Filter {
/*
* Simple Wrapper to implement hwload/unload filter as required
*
*/
public:
Filter(Config& cfg);
~Filter();
//set the target pixel format
//returns true if format was accepted
bool set_target_fmt(const AVPixelFormat fmt, AVCodecID codec_id, int codec_profile);
bool set_source_codec(AVCodecID codec_id, int codec_profile);//set the source codec, used for hinting the best HW download format
void set_source_time_base(const AVRational time_base);
bool send_frame(const AVFrame *frame);//refs the frame into this loader
bool get_frame(AVFrame *frame);//refs a frame into the supplied arg, caller must av_frame_unref() it
bool peek_frame(AVFrame *frame);//refs a frame into the supplied arg, caller must av_frame_unref() it, next send_frame() will be a NO-OP, and get frame will still return this frame
private:
bool is_hw(const AVPixelFormat fmt) const;//return true if format is supproted HW format
bool is_hw(const int fmt) const;//is_hw() with a cast to AVPixelFormat
std::string get_filter_str(const AVFrame *frame) const;//return the string for the filter
bool init_filter(const AVFrame *frame);
Config &cfg;
bool init_complete;//true if init completed successfully
bool passthrough;//true if we are operating in passthrough mode
bool peeked;//true if peek frame was called previously
AVRational time_base;
AVPixelFormat target_fmt;//fmt that we are converting t
AVCodecID target_codec, source_codec;
int target_profile, source_profile;
AVFrame *tmp_frame;//used to passthrough a frame when no conversion is required and to implement peeking
bool tmp_frame_filled;
AVFilterGraph *filter_graph;
AVFilterContext *buffersink_ctx;
AVFilterContext *buffersrc_ctx;
};
#endif
| 2,889
|
C++
|
.h
| 64
| 41.75
| 184
| 0.697056
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,989
|
event_controller.hpp
|
edman007_chiton/event_controller.hpp
|
#ifndef __EVENT_CONTROLLER_HPP__
#define __EVENT_CONTROLLER_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#include "chiton_ffmpeg.hpp"
#include "chiton_config.hpp"
#include "module_controller.hpp"
#include "event.hpp"
#include "image_util.hpp"
class EventController;
#include "event_notification.hpp"
//this class manages events, sending out notifications
class EventController : public ModuleController<EventNotification, EventController> {
public:
EventController(Config &cfg, Database &db, ImageUtil &img);
~EventController();
Event& get_new_event(void);//allocate a new Event, note, Event must be sent via send_event() or marked invalid
bool send_event(Event& event);//send event, it is not valid to access the Event after calling send_event()
//returns the event notification algorithm with name, will be executed before algo, returns null if the algorithm does not exist, calls init() on the algorithm
EventNotification* get_notification_before(const std::string &name, const EventNotification *algo);
void register_event_notification(ModuleAllocator<EventNotification, EventController>* maa);//registers an allocator and makes an algorithm available for use
ImageUtil& get_img_util(void);//return a reference to the image util
private:
std::vector<Event> events;
ImageUtil &img;
};
#endif
| 2,233
|
C++
|
.h
| 47
| 45.191489
| 163
| 0.70696
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,990
|
export.hpp
|
edman007_chiton/export.hpp
|
#ifndef __EXPORT_HPP__
#define __EXPORT_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include "database.hpp"
#include "file_manager.hpp"
#include "system_controller.fwd.hpp"
#include <thread>
#include <atomic>
#include <mutex>
/*
* This checks for tasks to export and exports them
*/
class Export {
public:
Export(SystemController &sys);
~Export(void);
bool check_for_jobs(void);//checks for any pending export jobs and executes them, returns true if a job is in progress
bool rm_export(int export_id);//deletes export with this ID, cancles it if in progress, thread safe
private:
SystemController &sys;
Database &db;
Config &cfg;
FileManager &g_fm;
AVPacket *pkt;//buffer packet
//details of current job:
std::atomic<long> id;
long long starttime;
long long endtime;
long camera;
std::string path;
long progress;
Config* camera_cfg;
long reserved_bytes;
std::thread runner;
std::atomic<bool> export_in_progress;//set to true when the runner is active
std::atomic<bool> force_exit;//will cause the runner to exis ASAP when true
std::mutex lock;//lock to check on the runner
bool start_job(void);//kicks off a thread to perform the export
void run_job(void);//main loop for exporting
bool update_progress();//sets the current progress
void reserve_space(FileManager &fm, long size);//reserve size bytes of drive space
bool split_export(long seg_id);//split the export so that a new export is created starting with this segment
};
#endif
| 2,449
|
C++
|
.h
| 65
| 34.584615
| 122
| 0.678722
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,991
|
remote.hpp
|
edman007_chiton/remote.hpp
|
#ifndef __REMOTE_HPP__
#define __REMOTE_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include "system_controller.fwd.hpp"
#include "export.hpp"
#include "database.hpp"
#include <atomic>
#include <thread>
#include <list>
#include <map>
#include <vector>
/*
* This class creates a socket to listen for commands from the web interface
* It will spawn off a worker thread that listens for and handles actions requested
* from the web frontend
*/
/*
* Definition of socket protocal:
*
* Commands are all CAPS, and case sensitive
* The client sends commands, seperated by \n, weather or not the server responds depends on the command
* The connection should be closed by calling CLOSE before disconnecting
*
* A typical connection looks like this
*
* -> RELOAD
* <- OK
* -> CLOSE
*
* Command Documentation:
*
* RELOAD
* - Server will respond with "OK" when processed correctly
* - This will reload the backend, as if the HUP signal was sent
*
* RM-EXPORT <INT1>
* - Server will delete the export with the export ID <INT1>
* - Server will cancel the export in progress if this id is currently being exported
*
* CLOSE
* - Server responds by closing the connection
*
* LICENSE
* - Prints the license
*
* TEAPOT
* - Prints I'm a teapot
*
* HELP
* - Server responds with 'SUPPORTED COMMANDS:' followed by a space deliminated list of commands supported
*
* START <INT1>
* - Requests that camera with ID <INT1> is started
* - Invalid or inactive camera IDs do nothing
* - Prints "OK" if added, "BUSY" if already queued for starting
*
* STOP <INT1>
* - Requests that camera with ID <INT1> is started
* - If no camera with this ID is running then does nothing
* - Prints "OK" if added, "BUSY" if already queued for stopping
*
* RESTART <INT1>
* - Requests that camera with ID <INT1> is started
* - Equivilent to running STOP and then START atomically
* - Prints "OK" if added, "BUSY" if already queued for starting
*
* LOG <INT1>
* - Print the log output for given camera, one message per line, use -1 as the camera to access system messages
* - Return value is "<INT1>\t<INT2>\t<INT3>\t<STR>", INT1 is the camera ID, INT2 is the message level, INT3 is seconds since UTC, STR is the message
* - output is terminated by OK by itself on a line
*
* LIST
* - List all running cameras
* - response is <INT1>\t<STATUS>
* INT1 - ID
* STATUS - The current state, STARTING, STOPPING, RESTARTING, RUNNING
* - Terminated by "OK" on it's own line
*
* STATUS <INT1>
* - Show status of camera INT1 (returned as JSON)
* - response is <INT2> on one line, follwed by a \n followed by a JSON string of INT2 len, followed by \nOK\n
*/
class Remote {
public:
Remote(SystemController &sys);
~Remote();
void init(void);//opens the socket
void shutdown(void);//closes the socket
//returns if a reload was requested an clears any pending request
bool get_reload_request(void);
private:
SystemController &sys;
Database &db;
Config &cfg;
std::atomic_bool reload_requested;
int sockfd;
std::string path;
std::thread worker;
std::atomic_bool kill_worker;
int killfd_worker;
int killfd_master;
//for the select() call
int nfds;
fd_set read_fds;
fd_set write_fds;
std::list<int> conn_list;//list of connections we have
std::map<int,std::string> write_buffers;//unwritten responses, indexed by fd
std::map<int, std::string> read_buffers;
//the callback below calls a member function to process the command, with the args: fd, rc (this rc struct), cmd (the full line being processed)
struct RemoteCommand;
std::vector<RemoteCommand> command_vec;
bool create_socket(void);//create the socket and bind to it
bool spawn_worker(void);
void run_worker(void);
int wait_for_activity(void);//calls select() on all open fds, returns the number of FDs that are ready
void accept_new_connection(void);//accepts one new connection
void complete_write(int fd);//writes out any remaining buffer to the fd
void write_data(int fd, std::string str);//writes out string to the fd
void process_input(int fd);
void execute_cmd(int fd, std::string &cmd);//executes the command received
void stop_worker(void);//sends the shutdown signal to the worker
void close_conn(int fd);//close the connection associated with fd and any associated data
//the methods to process each command:
void cmd_reload(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_rm_export(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_close(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_help(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_license(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_teapot(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_start(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_stop(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_restart(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_log(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_list(int fd, RemoteCommand& rc, std::string &cmd);
void cmd_status(int fd, RemoteCommand& rc, std::string &cmd);
};
#endif
| 6,182
|
C++
|
.h
| 158
| 36.21519
| 150
| 0.695059
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,992
|
image_util.hpp
|
edman007_chiton/image_util.hpp
|
#ifndef __IMAGE_UTIL_HPP__
#define __IMAGE_UTIL_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include "chiton_ffmpeg.hpp"
#include "database.hpp"
#include "system_controller.fwd.hpp"
class ImageUtil {
public:
ImageUtil(SystemController &sys, Config &cfg);
~ImageUtil();
//write out the source coordinates as a jpeg
//name is a prefix, full path will be autogenerated based on arguments (date based if start_time is not null)
//if starttime and fileid is non-null, the database ID is written to file id
bool write_frame_jpg(const AVFrame *frame, std::string &name, const struct timeval *start_time = NULL, rect src = {-1, -1, 0, 0}, long *file_id = NULL);
bool write_frame_png(const AVFrame *frame, std::string &name, const struct timeval *start_time = NULL, rect src = {-1, -1, 0, 0}, long *file_id = NULL);
void set_profile(AVCodecID id, int profile);//set the codec profile (used to download images from HW)
private:
SystemController &sys;
Database &db;
Config &cfg;
AVCodecID codec_id;//codec being used by HW
int codec_profile;//codec profile being used by HW
AVPacket *pkt;//packet buffer
//Returns a clone of the frame with the new rect applied
AVFrame* apply_rect(const AVFrame *frame, rect &src);
bool format_supported(const AVFrame *frame, const AVCodec *codec);//return true if the source is in a native format
AVPixelFormat get_pix_mpjeg_fmt(const AVPixelFormat *pix_list);//returns the best pixel format from the list, list is terminated by AV_PIX_FMT_NONE
};
#endif
| 2,460
|
C++
|
.h
| 50
| 46.22
| 156
| 0.6804
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,993
|
cv_target_rect.hpp
|
edman007_chiton/cv_target_rect.hpp
|
#ifndef __CV_TARGET_RECT_HPP__
#define __CV_TARGET_RECT_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#ifdef HAVE_OPENCV
#include <opencv2/core.hpp>
#include "chiton_ffmpeg.hpp"
//helper class to track trargets
class TargetRect {
public:
TargetRect(const cv::RotatedRect &rect);//create a new target from a given rotated rect
TargetRect(const TargetRect &old_target, const cv::RotatedRect &new_rect, const AVFrame *cur_frame);//create a new target that updates the rect of an old target
TargetRect(const TargetRect &rhs);//copy constructor
TargetRect(TargetRect &&rhs) noexcept;//move constructor
~TargetRect();//destructor
const cv::RotatedRect& get_rect(void) const;//return a reference to the underlying rect
bool is_valid(void)const ;//return true is it has not been marked invalid
void mark_invalid(void);//mark this rect as invalid
int get_count(void) const;//get the number of times this has been seen
const AVFrame *get_best_frame(void) const;//return the best frame found
const cv::RotatedRect& get_best_rect(void) const;//return the rect for the best frame
void scale(float scale);//Applies the scaling ratio
private:
cv::RotatedRect rect, best_rect;//the underlying rects
int count;//how many times we have seen this
bool valid;//is this is still valid
AVFrame *frame;//the best frame found so far
void scale_rect(float scale, cv::RotatedRect &rect);//scale the target Rect
};
#endif
#endif
| 2,368
|
C++
|
.h
| 51
| 43.647059
| 164
| 0.692308
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,994
|
camera_status.hpp
|
edman007_chiton/camera_status.hpp
|
#ifndef __CAMERA_STATUS_HPP__
#define __CAMERA_STATUS_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include "util.hpp"
#include <atomic>
/*
* Helper class to track camera running status
*/
class CameraStatus {
public:
CameraStatus(int id);
~CameraStatus();
CameraStatus(const CameraStatus &in);
CameraStatus& operator=(const CameraStatus &in);//copy
CameraStatus& operator+=(const CameraStatus &in);//add
void add_bytes_written(unsigned int bytes);//add bytes to running write total
void add_bytes_read(unsigned int bytes);//add bytes to running read total
void add_dropped_frame(void);//increment dropped frame counter
void set_start_time(time_t start);
int get_id(void);
unsigned int get_bytes_written(void);
unsigned int get_bytes_read(void);
unsigned int get_dropped_frames(void);
time_t get_start_time(void);
private:
std::atomic<int> id;
std::atomic<unsigned int> bytes_written;
std::atomic<unsigned int> bytes_read;
std::atomic<unsigned int> dropped_frames;
std::atomic<time_t> start_time;
};
#endif
| 1,989
|
C++
|
.h
| 53
| 34.54717
| 81
| 0.669259
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,995
|
motion_controller.hpp
|
edman007_chiton/motion_controller.hpp
|
#ifndef __MOTION_CONTROLLER_HPP__
#define __MOTION_CONTROLLER_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022-2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#include "chiton_ffmpeg.hpp"
#include "chiton_config.hpp"
#include "module_controller.hpp"
#include "image_util.hpp"
class MotionController;
#include "event_controller.hpp"
#include "motion_algo.hpp"
#include <list>
#include "stream_unwrap.hpp"
#include "event_notification.hpp"
//this class runs all motion detection algorithms
class MotionController : public ModuleController<MotionAlgo, MotionController> {
public:
MotionController(Database &db, Config &cfg, StreamUnwrap &stream, ImageUtil &img);
~MotionController();
bool process_frame(int index, const AVFrame *frame, bool &skipped);//process the frame, return false on error, skipped is set to true if frame was skipped
bool set_streams(void);//identify the streams (by looking at the StreamUnwrap instance)
bool decode_video(void);//true if video is required (configured to do video motion detection)
bool decode_audio(void);//true if audio is required (configured to do audio motion detection)
//returns the motion algorithm with name, will be executed before algo, returns null if the algorithm does not exist, calls init() on the algorithm
void get_frame_timestamp(const AVFrame *frame, bool video, struct timeval &time);//wrapper for StreamUnwrap timestamp(), assumes from video stream if video is true
EventController& get_event_controller(void);//return a handle to the event controller
ImageUtil& get_img_util(void);//return the imageutil object
private:
StreamUnwrap &stream;
EventController events;
ImageUtil &img;
int video_idx;//index of the video stream
int audio_idx;//index of the audio stream
double skip_ratio;//the configured skip_ratio
bool set_video_stream(const AVStream *stream, const AVCodecContext *codec);//identify the video stream
bool set_audio_stream(const AVStream *stream, const AVCodecContext *codec);//identify the audio stream
bool should_skip(void);//check if we are falling behind and skip if required, return true when we need to skip
};
#endif
| 3,031
|
C++
|
.h
| 59
| 48.627119
| 167
| 0.721417
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,996
|
stream_writer.hpp
|
edman007_chiton/stream_writer.hpp
|
#ifndef __STREAM_WRITER_HPP__
#define __STREAM_WRITER_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2021 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include "stream_unwrap.hpp"
#include <functional>
class PacketInterleavingBuf {
public:
AVPacket* in;//the origional packet, in source timebase
AVPacket* out;//the packet to be written, in destination timebase
bool video_keyframe;
long dts0;//DTS in stream 0 timebase
PacketInterleavingBuf(const AVPacket *pkt);//clone in & out to pkt
~PacketInterleavingBuf();//free the packets
};
class StreamWriter {
public:
StreamWriter(Config &cfg, std::string path);
StreamWriter(Config &cfg);
~StreamWriter();
bool open(void);//open the file for writing, returns true on success
long long close(void);//close the file and return the filesize
bool write(const AVPacket *pkt, const AVStream *in_stream);//write the packet to the file, interleave the packet appropriatly
bool write(const AVFrame *frame, const AVStream *in_stream);//write the frame to the file (using encoding)
//set the path of the file to write to, if the stream was opened, it remains opened (and a new file is created), if it was closed then it is not opened
long long change_path(const std::string &new_path = "");//returns file position of the end of the file
bool add_stream(const AVStream *in_stream);//add in_stream to output (copy)
bool add_encoded_stream(const AVStream *in_stream, const AVCodecContext *dec_ctx, const AVFrame *frame);//add in_stream to output, specify frame to pass a HW context
bool add_encoded_stream(const AVStream *in_stream, const AVCodecContext *dec_ctx);//add in_stream to output
bool copy_streams(StreamUnwrap &unwrap);//copy all streams from unwrap to output
bool is_fragmented(void) const;//return true if this is a file format that supports fragmenting
long long get_init_len(void) const;//return the init length, -1 if not valid
void set_keyframe_callback(std::function<void(const AVPacket *pkt, StreamWriter &out)> cbk);//set a callback when writing video keyframes
std::string get_codec_str(void) const;//returns the codec string for the current output
bool have_video(void) const ;//true if video is included in output
bool have_audio(void) const;//true if audio is included in output
int get_width() const;//returns the video width, or -1 if unknown
int get_height() const;//returns the video height, or -1 if unknown
float get_framerate() const;//returns the video framerate, or 0 if unknown
//return true if we found our encoding parameters, writes out pixel format expected by the encoder, and codec_id and profile as we use
bool get_video_format(const AVFrame *frame, AVPixelFormat &pix_fmt, AVCodecID &codec_id, int &codec_profile) const;
unsigned int get_bytes_written(void);//return the number of bytes written since last call to get_bytes_written()
private:
Config &cfg;
Config *cfg1;
Config *cfg2;
std::string path;
enum {SEGMENT_MPGTS, SEGMENT_FMP4} segment_mode;
unsigned int interleave_queue_depth;
AVFormatContext *output_format_context = NULL;
std::map<int,int> stream_mapping;
std::map<int, AVCodecContext*> encode_ctx;
std::map<int, std::string> codec_str;
//metadata that we track to forward to the HLS frontend (needs to go into the DB)
bool video_stream_found;
bool audio_stream_found;
int video_width;//-1 if unknown
int video_height;//-1 if unknown
float video_framerate;//0 if unknown
//these offsets are used to shift the time when receiving something
std::vector<long> stream_offset;
std::vector<long> last_dts;//used to fix non-increasing DTS
std::map<int,long> track_len_dts;//used to fixup packet DTS (and prevent gaps)
std::function<void(const AVPacket *pkt, StreamWriter &out)> keyframe_cbk;//we call this on all video keyframe packets
//used to track if we were successful in getting a file opened (and skip writing anything if not successful)
//true means the file is opened
bool file_opened;
//buffers used for FMP4 mode to split the file
uint8_t *init_seg;
long long init_len;
AVIOContext *output_file;
AVPacket *enc_pkt;//buffer used when writing files
//buffers used to force proper interleaving
std::list<PacketInterleavingBuf*> interleaving_buf;
std::map<int,long> interleaved_dts;
unsigned int write_counter;//used to provide write stats
void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt, const std::string &tag);
bool open_path(void);//open the path and write the header
void free_context(void);//free the context associated with a file
bool alloc_context(void);
AVStream *init_stream(const AVStream *in_stream);//Initilizes output stream
long long frag_stream(void);//creates a fragment at the current location and returns the position
long long write_buf(bool reopen);//write the buffer to the file, return bytes written on success, negative on error, if reopen is true then a new buffer is also allocated
long long write_init(void);//write the init segment to the buffer
bool write(PacketInterleavingBuf *buf);//write the packet to the file (perform the actual write)
void interleave(PacketInterleavingBuf *buf);//add the packet to the interleaving buffer and write buffers that are ready
//fix the packet at itr to have a reasonable duration, return true if error found and fixed
bool fixup_duration_interleave(std::list<PacketInterleavingBuf*>::iterator itr);
bool write_interleaved(void);//write any buffers that are ready to be written
bool gen_codec_str(const int stream, const AVCodecParameters *codec);//generate the HLS codec ID for the stream
uint8_t *nal_unit_extract_rbsp(const uint8_t *src, const uint32_t src_len, uint32_t *dst_len);//helper for decoding h264 types
bool guess_framerate(const AVStream *stream);//guess the framerate from the stream, true if found framerate
bool guess_framerate(const AVCodecContext* codec_ctx);//guess the framerate from the codec context, true if found framerate
const AVCodec* get_vencoder(int width, int height, AVCodecID &codec_id, int &codec_profile) const;//return the encoder, or null if we can't encode this, write out the codec id/profile
const AVCodec* get_vencoder(int width, int height) const;//return the encoder, or null if we can't encode this
bool validate_codec_tag(AVStream *stream);//check and modifiy the codec tag to ensure it is compatible with the output format
};
#endif
| 7,455
|
C++
|
.h
| 118
| 59.025424
| 187
| 0.729818
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,997
|
system_controller.fwd.hpp
|
edman007_chiton/system_controller.fwd.hpp
|
#ifndef __SYSTEM_CONTROLLER_FWD_HPP__
#define __SYSTEM_CONTROLLER_FWD_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2023 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
//included in headers of every class that SystemController owns
class SystemController;
#endif
| 1,078
|
C++
|
.h
| 26
| 39.692308
| 75
| 0.635932
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,998
|
database_manager.hpp
|
edman007_chiton/database_manager.hpp
|
#ifndef __DATABASE_MANAGER_HPP__
#define __DATABASE_MANAGER_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2021 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "database.hpp"
/*
* Database Manager is called once at startup and prepares the database for use by updating it to
* the latest version if required
*/
class DatabaseManager {
public:
//initilize the database manager against the DB
DatabaseManager(Database &db);
//this queries the tables, determines the version, and initilizes the database as required
//returns true if the database is in the correct configuration (and false if we cannot use the database)
bool check_database(void);
private:
Database &db;
//returns true on success
bool initilize_db(void);//initilized the database to the current version from an empty database
bool set_latest_version(void);//marks the database version as the latest
bool upgrade_database(int major, int minor);//selects the upgrade routine, returns true if successfully upgraded
bool upgrade_from_1_0(void);//upgrade from 1_0 to latest
bool upgrade_from_1_1(void);//upgrade from 1_1 to latest
bool upgrade_from_1_2(void);//upgrade from 1_2 to latest
bool upgrade_from_1_3(void);//upgrade from 1_2 to latest
};
#endif
| 2,108
|
C++
|
.h
| 47
| 42
| 116
| 0.688748
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,542,999
|
module_controller.hpp
|
edman007_chiton/module_controller.hpp
|
#ifndef __MODULE_CONTROLLER_HPP__
#define __MODULE_CONTROLLER_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#include "chiton_ffmpeg.hpp"
#include "chiton_config.hpp"
#include "util.hpp"
#include <vector>
template <class Mod, class Controller> class ModuleController;
#include "module.hpp"
//this class provides a generic way of registering modules
//Mod is a class derived from Module<> and Controller is a class derived from a ModuleController<>
template <class Mod, class Controller> class ModuleController {
public:
//name is the name of the controller, name-mods is queried for the list of modules
ModuleController(Config &cfg, Database &db, const std::string name);
~ModuleController();
//returns the event notification modrithm with name, will be executed before mod, returns null if the modrithm does not exist, calls init() on the modrithm
Mod* get_module_before(const std::string &name, const Mod *mod);
void register_module(ModuleAllocator<Mod, Controller>* maa);//registers an allocator and makes an modrithm available for use
const std::string& get_name(void);//return the name of the module controller;
protected:
Config &cfg;
Database &db;
std::vector<ModuleAllocator<Mod, Controller>*> supported_mods;//list of allocators supported
std::vector<Mod*> mods;//list of configured modules
bool add_mods(void);//put all mods in mods
private:
std::string name;//the name of the modulecontroller
void clear_mods(void);//clear & delete mods
bool parse_mods(const std::string param, std::vector<std::string> &mod_list);//read the config value param, write out all modrithms to mod_list, return true if non-empty
Mod* find_mod(const std::string &name);//return the mod with a given name, null if it does not exist, allocate it if not already done
};
template <class Mod, class Controller> ModuleController<Mod, Controller>::ModuleController(Config &cfg, Database &db, const std::string name) : cfg(cfg), db(db), name(name) {
}
template <class Mod, class Controller> ModuleController<Mod, Controller>::~ModuleController(){
clear_mods();
for (auto &m : supported_mods){
delete m;
}
}
template <class Mod, class Controller> Mod* ModuleController<Mod, Controller>::get_module_before(const std::string &mod_name, const Mod* mod){
for (auto it = mods.begin(); it != mods.end(); it++){
if (*it == mod){
for (auto &m : supported_mods){
if (m->get_name() == mod_name){
Mod* new_mod = m->allocate(cfg, db, *static_cast<Controller*>(this));
mods.insert(it, new_mod);
new_mod->init();
return new_mod;
}
}
return NULL;//not found
}
if ((*it)->get_name() == mod_name){
return *it;
}
}
return NULL;//mod was not found
}
template <class Mod, class Controller> void ModuleController<Mod, Controller>::register_module(ModuleAllocator<Mod, Controller>* ma) {
if (ma){
supported_mods.push_back(ma);
}
}
template <class Mod, class Controller> void ModuleController<Mod, Controller>::clear_mods(void){
for (auto m = mods.rbegin(); m != mods.rend(); ++m){//do it backwards to prevent dependency problems
delete *m;
}
mods.clear();
}
template <class Mod, class Controller> bool ModuleController<Mod, Controller>::parse_mods(const std::string param, std::vector<std::string> &mod_list){
const std::string &str_list = cfg.get_value(param);
std::string::size_type start = 0;
while (start < str_list.length()){
auto end = str_list.find(",", start);
if (end == start){
start++;
continue;
}
mod_list.push_back(str_list.substr(start, end));
if (end == std::string::npos){
break;
}
start = end + 1;
}
return !mod_list.empty();
}
template <class Mod, class Controller> Mod* ModuleController<Mod, Controller>::find_mod(const std::string &mod_name){
for (auto &m : mods){
if (m->get_name() == mod_name){
return m;
}
}
for (auto &m : supported_mods){
if (m->get_name() == mod_name){
Mod* new_mod = m->allocate(cfg, db, *static_cast<Controller*>(this));
mods.push_back(new_mod);
mods.back()->init();
return mods.back();
}
}
return NULL;
}
template <class Mod, class Controller> bool ModuleController<Mod, Controller>::add_mods(void){
std::vector<std::string> mod_list;
if (!parse_mods(name + "-mods", mod_list)){
return true;//nothing to configure
}
if (mod_list[0] == "" || mod_list[0] == "none"){
return true;//explicitly disabled
}
bool ret = false;
for (auto &mod_name : mod_list){
auto m = find_mod(mod_name);
if (m != NULL){
ret |= true;
} else {
LWARN("Cannot find module '" + mod_name + "' in '" + + "', skipping");
}
}
return true;
}
#endif
| 5,988
|
C++
|
.h
| 144
| 35.763889
| 174
| 0.631308
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,000
|
motion_opencv.hpp
|
edman007_chiton/motion_opencv.hpp
|
#ifndef __MOTION_ALGO_OPENCV_HPP__
#define __MOTION_ALGO_OPENCV_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#ifdef HAVE_OPENCV
#include "motion_algo.hpp"
#include "filter.hpp"
#include <opencv2/core.hpp>
#include <opencv2/core/ocl.hpp>
class MotionOpenCV : public MotionAlgo {
public:
MotionOpenCV(Config &cfg, Database &db, MotionController &controller);
~MotionOpenCV();
bool process_frame(const AVFrame *frame, bool video);//process the frame, return false on error
bool set_video_stream(const AVStream *stream, const AVCodecContext *codec);//identify the video stream
static const std::string& get_mod_name(void);//return the name of the algorithm
const cv::UMat& get_UMat(void) const;//return the UMat (CV_8UC1) for this frame
private:
cv::UMat invalid_mat;//returned when buf_mat is invalid
cv::UMat buf_mat;//the Mat we operate on
cv::Mat input_mat;//the sw mat
cv::UMat tmp1, tmp2;//temporary buffers
AVFrame *input;
Filter fmt_filter;
bool map_cl;//true if using opencl mapping instead of direct vaapi mapping
bool map_indirect;//true if mapping indirectly from VA-API to SW OpenCV
bool map_vaapi;//true if mapping using OpenCV's VA-API to OpenCV
//OpenCV device selection
cv::ocl::Context ocv_cl_ctx;
cv::ocl::OpenCLExecutionContext ocv_exe_ctx;
#ifdef HAVE_OPENCL
void map_ocl_frame(AVFrame *input);
#endif
#ifdef HAVE_VAAPI
void indirect_vaapi_map(const AVFrame *input);
#endif
};
#endif
#endif
| 2,390
|
C++
|
.h
| 59
| 37.711864
| 106
| 0.688172
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,001
|
motion_cvbackground.hpp
|
edman007_chiton/motion_cvbackground.hpp
|
#ifndef __MOTION_ALGO_CVBACKGROUND_HPP__
#define __MOTION_ALGO_CVBACKGROUND_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#ifdef HAVE_OPENCV
#include "motion_algo.hpp"
#include "motion_cvresize.hpp"
#include "filter.hpp"
#include <opencv2/core.hpp>
class MotionCVBackground : public MotionAlgo {
public:
MotionCVBackground(Config &cfg, Database &db, MotionController &controller);
~MotionCVBackground();
bool process_frame(const AVFrame *frame, bool video);//process the frame, return false on error
bool set_video_stream(const AVStream *stream, const AVCodecContext *codec);//identify the video stream
static const std::string& get_mod_name(void);//return the name of the algorithm
const cv::UMat get_background(void);//get the averaged background
bool init(void);//called immeditly after the constructor to allow dependicies to be setup
private:
MotionCVResize *ocvr;
cv::UMat avg;//the 16-bit average image
cv::UMat low_res;//low res version derived from the 16-bit
float tau;
};
#endif
#endif
| 1,939
|
C++
|
.h
| 46
| 39.695652
| 106
| 0.687302
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,002
|
motion_cvmask.hpp
|
edman007_chiton/motion_cvmask.hpp
|
#ifndef __MOTION_ALGO_CVMASK_HPP__
#define __MOTION_ALGO_CVMASK_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#ifdef HAVE_OPENCV
#include "motion_algo.hpp"
#include "motion_cvresize.hpp"
#include "motion_cvbackground.hpp"
#include <opencv2/core.hpp>
class MotionCVMask : public MotionAlgo {
public:
MotionCVMask(Config &cfg, Database &db, MotionController &controller);
~MotionCVMask();
bool process_frame(const AVFrame *frame, bool video);//process the frame, return false on error
bool set_video_stream(const AVStream *stream, const AVCodecContext *codec);//identify the video stream
static const std::string& get_mod_name(void);//return the name of the algorithm
bool init(void);//called immeditly after the constructor to allow dependicies to be setup
const cv::UMat get_masked(void);//returns a CV_8UC1 (static bits masked out)
const cv::UMat get_sensitivity(void);//returns the underlaying sensitivity mask
private:
MotionCVResize *ocvr;
MotionCVBackground *background;
cv::UMat masked;//the masked image
std::vector<cv::UMat> sensitivity_db;//storage of all sensitivity UMats
std::vector<cv::UMat>::iterator sensitivity_it;//reference to the active sensitivity
float tau;//sensitivity tau (time constant)
float beta;//sensitivity beta (diff amplification factor)
float thresh;//final thresholding value
};
#endif
#endif
| 2,289
|
C++
|
.h
| 51
| 42.176471
| 106
| 0.698434
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,003
|
event_db.hpp
|
edman007_chiton/event_db.hpp
|
#ifndef __EVENT_DB_HPP__
#define __EVENT_DB_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "event_notification.hpp"
#include "image_util.hpp"
//this writes events to the db/logging
class EventDB : public EventNotification {
public:
EventDB(Config &cfg, Database &db, EventController &controller);
~EventDB();
bool send_event(Event &e);//Send the event through notification method
static const std::string& get_mod_name(void);
private:
};
#endif
| 1,339
|
C++
|
.h
| 35
| 36.142857
| 75
| 0.647963
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,004
|
camera.hpp
|
edman007_chiton/camera.hpp
|
#ifndef __CAMERA_HPP__
#define __CAMERA_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "database.hpp"
#include "chiton_config.hpp"
#include "stream_unwrap.hpp"
#include "stream_writer.hpp"
#include "file_manager.hpp"
#include "camera_status.hpp"
#include "system_controller.fwd.hpp"
#include <atomic>
#include <thread>
class Camera {
/*
* This monitors the Recording process for one camera
*/
public:
Camera(SystemController &sys, int camera);
~Camera();
void start(void);//start the camera thread
void stop(void);//requests the thread stops
void join(void);//join the Camera thread
bool ping(void);//checks that this is running, returns true if the thread has not progressed (processed at least one frame) since last ping
bool in_startup(void);//returns true if we have not completed connecting
std::thread::id get_thread_id(void);
int get_id(void);//return this camera's ID
CameraStatus get_status(void);//return status info
private:
void run(void);//connect and run the camera monitor
void load_cfg(void);
SystemController &sys;
int id; //camera ID
Config cfg;
Database& db;
StreamUnwrap stream;
FileManager fm;
std::atomic_bool alive;//used by ping to check our status
std::atomic_bool watchdog;//used by ping to check our status
std::atomic_bool shutdown;//signals that we should exit
std::atomic_bool startup;//used to identify if we are in an extended wait due to startup
std::thread thread;
AVPacket *pkt;//packet we are processing
AVRational last_cut;//last time a segment was cut
AVRational last_cut_file;//last time a file was cut
long long last_cut_byte;//the bytes of the end of the previous segment (or file)
AVRational seconds_per_file;//max seconds per file
AVRational seconds_per_segment;//max seconds per segment
CameraStatus status;
long int file_id;//database id of current file we are writing to
//check if packet is a keyframe and switch the filename as needed
void cut_video(const AVPacket *pkt, StreamWriter &out);
bool get_vencode(void);//get if video needs to be encoded
bool get_aencode(void);//get if audio needs to be encoded
};
#endif
| 3,106
|
C++
|
.h
| 75
| 37.933333
| 143
| 0.691951
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,005
|
motion_cvdetect.hpp
|
edman007_chiton/motion_cvdetect.hpp
|
#ifndef __MOTION_ALGO_CVDETECT_HPP__
#define __MOTION_ALGO_CVDETECT_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#ifdef HAVE_OPENCV
#include "motion_algo.hpp"
#include "motion_cvmask.hpp"
#include <opencv2/core.hpp>
#include "motion_opencv.hpp"
#include "motion_cvresize.hpp"
#include "cv_target_rect.hpp"
//algorithm to implement the cvdetect motion detection algorithm
class MotionCVDetect : public MotionAlgo {
public:
MotionCVDetect(Config &cfg, Database &db, MotionController &controller);
~MotionCVDetect();
bool process_frame(const AVFrame *frame, bool video);//process the frame, return false on error
bool set_video_stream(const AVStream *stream, const AVCodecContext *codec);//identify the video stream
static const std::string& get_mod_name(void);//return the name of the algorithm
bool init(void);//called immeditly after the constructor to allow dependicies to be setup
const cv::UMat& get_debug_view(void);
private:
MotionCVMask *masked_objects;//mask we are using
std::vector<std::vector<cv::Point>> contours;//the detected contours
std::vector<TargetRect> targets;//the targets we are counting
cv::UMat debug_view, canny;
MotionOpenCV *ocv;
MotionCVResize *ocvr;
void display_objects(void);//debug tool to display the objects
void send_events(void);
//config parameters
float min_dist;//min distance between objects to track seperatly
float min_area;//miniumn area of an object to track
int tracking_time_send;//number of frames tracked to trigger an event
};
#endif
#endif
| 2,466
|
C++
|
.h
| 57
| 40.508772
| 106
| 0.70104
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,006
|
motion_algo.hpp
|
edman007_chiton/motion_algo.hpp
|
#ifndef __MOTION_ALGO_HPP__
#define __MOTION_ALGO_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "config_build.hpp"
#include "chiton_ffmpeg.hpp"
#include "chiton_config.hpp"
class MotionAlgo;
#include "motion_controller.hpp"
//this class runs all motion detection algorithms
class MotionAlgo : public Module<MotionAlgo, MotionController> {
public:
MotionAlgo(Config &cfg, Database &db, MotionController &controller, const std::string &name) : Module<MotionAlgo, MotionController>(cfg, db, controller, name) {};
virtual ~MotionAlgo() {};
virtual bool process_frame(const AVFrame *frame, bool video) = 0;//process the frame, return false on error, video is true if video frame is supplied
virtual bool set_video_stream(const AVStream *stream, const AVCodecContext *codec) {return true;};//identify the video stream
virtual bool set_audio_stream(const AVStream *stream, const AVCodecContext *codec) {return true;};//identify the audio stream
};
#endif
| 1,847
|
C++
|
.h
| 38
| 46.473684
| 166
| 0.6866
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,007
|
util.hpp
|
edman007_chiton/util.hpp
|
#ifndef __UTIL_HPP__
#define __UTIL_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2020-2022 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include <iostream>
#include <mutex>
#include <time.h>
#include <deque>
#include "config_build.hpp"
#include "chiton_ffmpeg.hpp"
#include "chiton_config.hpp"
//when editing check the static assert for color_map in util.cpp
enum LOG_LEVEL {
CH_LOG_FATAL = 0,
CH_LOG_ERROR,//1
CH_LOG_WARN,//2
CH_LOG_INFO,//3
CH_LOG_DEBUG,//4
};
//basic macros
#ifdef DEBUG
#define LDEBUG(str) Util::log_msg(CH_LOG_DEBUG, str)
#else
#define LDEBUG(str)
#endif
#define LINFO(str) Util::log_msg(CH_LOG_INFO, str)
#define LWARN(str) Util::log_msg(CH_LOG_WARN, str)
#define LERROR(str) Util::log_msg(CH_LOG_ERROR, str)
#define LFATAL(str) Util::log_msg(CH_LOG_FATAL, str)
struct VideoDate {
unsigned int year;
unsigned int month;
unsigned int day;
unsigned int hour;
unsigned int min;
unsigned int sec;
unsigned int ms;
};
//used for querying log info
struct LogMsg {
std::string msg;
LOG_LEVEL lvl;
struct timeval time;
LogMsg(const std::string &msg, LOG_LEVEL lvl, struct timeval time) : msg(msg), lvl(lvl), time(time) {};
};
class Util {
public:
/*
* Log a message
*/
static void log_msg(const LOG_LEVEL lvl, const std::string& msg);
static void get_videotime(struct timeval &time);//write the current time out
static void get_time_parts(const struct timeval &time, struct VideoDate &date);//write the time out to date format
//pack and unpack time for database storage, spits out a 64-bit unsigned int
static unsigned long long int pack_time(const struct timeval &time);
static void unpack_time(const unsigned long long int packed_time, struct timeval &time);
static void compute_timestamp(const struct timeval &connect_time, struct timeval &out_time, long pts, AVRational &time_base);
static void set_log_level(unsigned int level);//set the amount of logging that we do..
static void set_history_len(int len);
static bool get_history(int cam, std::vector<LogMsg> &hist);//write thie history for a given camera to hist, return true if messages found
static bool enable_syslog(void);
static bool disable_syslog(void);
static bool enable_color(void);
static bool disable_color(void);
static void set_low_priority(void);//reduce the current thread to low priority
static AVDictionary* get_dict_options(const std::string &fmt);//convert fmt into an AVDict, caller must free
static void reset_color(void);//clears the color on the CLI
static void load_colors(Config &cfg);//load all color settings
static void set_thread_name(int id, Config &cfg);//takes the camera ID and the camera's config
private:
static std::mutex lock;//lock for actually printing messages
static unsigned int log_level;//the output logging level
static bool use_syslog;
static bool use_color;
static int color_map[5];
static_assert(sizeof(color_map)/sizeof(color_map[0]) == (1 + CH_LOG_DEBUG), "Color map must be the same size as enum LOG_LEVEL");
static std::map<int, std::deque<LogMsg>> log_history;//a log of our messages
static unsigned int history_len;
static std::mutex history_lock;
static std::string get_color_txt(enum LOG_LEVEL ll);//return the string to switch the color on the CLI
static void add_history(const std::string &msg, LOG_LEVEL lvl);//add the message to the history log
};
#endif
| 4,331
|
C++
|
.h
| 102
| 39.068627
| 142
| 0.698787
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,008
|
io_wrapper.hpp
|
edman007_chiton/io/io_wrapper.hpp
|
#ifndef __IO_WRAPPER_HPP__
#define __IO_WRAPPER_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2021 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "chiton_config.hpp"
#include "chiton_ffmpeg.hpp"
/*
* Virtual class for Alternate I/O streams
*
* This class just allows the StreamUnwrap class to get an AVIOcontext that is user defined
*
*/
class IOWrapper {
public:
virtual ~IOWrapper() {};
virtual AVIOContext* get_pb(void) { return NULL;};//return the AVIOContext
virtual std::string get_url(void) { return "IOWrapper://";};//return the URL identifying this object
};
#endif
| 1,420
|
C++
|
.h
| 38
| 35.289474
| 104
| 0.648041
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,009
|
cfmp4.hpp
|
edman007_chiton/io/cfmp4.hpp
|
#ifndef __IO_CFMP4_HPP__
#define __IO_CFMP4_HPP__
/**************************************************************************
*
* This file is part of Chiton.
*
* Chiton is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chiton is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Chiton. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright 2021 Ed Martin <edman007@edman007.com>
*
**************************************************************************
*/
#include "io/io_wrapper.hpp"
#include <fstream>
/*
* Supports reading of Chiton-generated fMP4 segments
*/
class CFMP4 : public IOWrapper {
public:
CFMP4(const std::string &path, int initlen, int start_byte, int end_byte);
~CFMP4() override;
AVIOContext* get_pb(void) override;//return the pb handle refering to this
std::string get_url(void) override;//return a URL for this stream
private:
AVIOContext* pb;//the pb we own, automatically freed upon destruction of this object
unsigned char* buf;//the buffer used for reading
//segment metadata
const int initlen;//length of the init segment, prepended to the segment
const int start_byte;//start of the segment
const int end_byte;//end of the segment
std::ifstream ifs;
//API interface call
static int read_packet(void *opaque, uint8_t *buf, int buf_size);
static int64_t seek(void *opaque, int64_t offset, int whence);
//actual calls to handle API
int read(uint8_t *buf, int buf_size);
int64_t seek(int64_t offset, int whence);
};
#endif
| 2,026
|
C++
|
.h
| 50
| 37.54
| 88
| 0.667006
|
edman007/chiton
| 38
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,010
|
util.cpp
|
mullvad_win-split-tunnel/leaktest/util.cpp
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <libcommon/network/adapters.h>
#include "util.h"
#include <libcommon/process/process.h>
#include <libcommon/error.h>
#include <libcommon/memory.h>
#include <libcommon/string.h>
#include <iostream>
#include <vector>
#include <filesystem>
#include <ws2tcpip.h>
namespace
{
std::wstring ImplodeArgs(const std::vector<std::wstring> &args)
{
std::wstring imploded;
for (const auto &arg : args)
{
if (std::wstring::npos != arg.find(L' '))
{
imploded.append(L" \"").append(arg).append(L"\"");
}
else
{
imploded.append(L" ").append(arg);
}
}
return imploded;
}
void PrintWithColor(const std::wstring &str, WORD colorAttributes)
{
auto consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO info = { 0 };
if (FALSE == GetConsoleScreenBufferInfo(consoleHandle, &info)
|| FALSE == SetConsoleTextAttribute(consoleHandle, colorAttributes))
{
std::wcout << str << std::endl;
return;
}
std::wcout << str << std::endl;
SetConsoleTextAttribute(consoleHandle, info.wAttributes);
}
} // anonymous namespace
void PromptActivateVpnSplitTunnel()
{
std::wcout << L"Activate VPN && activate split tunnel for testing application" << std::endl;
std::wcout << L"Then press a key to continue" << std::endl;
_getwch();
}
void PromptActivateVpn()
{
std::wcout << L"Activate VPN" << std::endl;
std::wcout << L"Then press a key to continue" << std::endl;
_getwch();
}
void PromptActivateSplitTunnel()
{
std::wcout << L"Activate split tunnel for testing application" << std::endl;
std::wcout << L"Then press a key to continue" << std::endl;
_getwch();
}
void PromptDisableSplitTunnel()
{
std::wcout << L"Disable split tunnel for testing application" << std::endl;
std::wcout << L"Then press a key to continue" << std::endl;
_getwch();
}
std::filesystem::path ProcessBinaryCreateRandomCopy()
{
constexpr size_t bufferSize = 1024;
std::vector<wchar_t> tempDir(bufferSize), tempFilename(bufferSize);
if (0 == GetTempPathW(bufferSize, &tempDir[0]))
{
THROW_WINDOWS_ERROR(GetLastError(), "GetTempPathW");
}
if (0 == GetTempFileNameW(&tempDir[0], L"tst", 0, &tempFilename[0]))
{
THROW_WINDOWS_ERROR(GetLastError(), "GetTempFileNameW");
}
const std::wstring sourceFile(_wpgmptr);
const auto destFile = std::wstring(&tempFilename[0]);
if (FALSE == CopyFileW(sourceFile.c_str(), destFile.c_str(), FALSE))
{
THROW_WINDOWS_ERROR(GetLastError(), "CopyFileW");
}
return destFile;
}
HANDLE LaunchProcess
(
const std::filesystem::path &path,
const std::vector<std::wstring> &args,
DWORD creationFlags,
std::optional<LPPROC_THREAD_ATTRIBUTE_LIST> attributes
)
{
if (false == path.is_absolute()
|| false == path.has_filename())
{
THROW_ERROR("Invalid path specification for subprocess");
}
const auto implodedArgs = ImplodeArgs(args);
const auto workingDir = path.parent_path();
const auto quotedPath = std::wstring(L"\"").append(path).append(L"\"");
const auto commandLine = implodedArgs.empty()
? quotedPath
: std::wstring(quotedPath).append(L" ").append(implodedArgs);
DWORD additionalCreationFlags = 0;
STARTUPINFOEXW siStorage = { 0 };
STARTUPINFOW *siPointer = nullptr;
if (attributes.has_value())
{
//
// Use extended startup structure.
//
additionalCreationFlags |= EXTENDED_STARTUPINFO_PRESENT;
siStorage.StartupInfo.cb = sizeof(STARTUPINFOEXW);
siStorage.lpAttributeList = attributes.value();
siPointer = reinterpret_cast<STARTUPINFOW*>(&siStorage);
}
else
{
//
// Use plain startup structure.
// We can use the same storage for this.
//
siStorage.StartupInfo.cb = sizeof(STARTUPINFOW);
siPointer = &siStorage.StartupInfo;
}
PROCESS_INFORMATION pi = { 0 };
const auto status = CreateProcessW
(
nullptr,
const_cast<wchar_t *>(commandLine.c_str()),
nullptr,
nullptr,
FALSE,
creationFlags | additionalCreationFlags,
nullptr,
workingDir.c_str(),
siPointer,
&pi
);
if (FALSE == status)
{
THROW_WINDOWS_ERROR(GetLastError(), "Launch subprocess");
}
CloseHandle(pi.hThread);
return pi.hProcess;
}
HANDLE LaunchUnrelatedProcess
(
const std::filesystem::path &path,
const std::vector<std::wstring> &args,
DWORD creationFlags
)
{
//
// Find explorer.exe
//
auto explorerPid = common::process::GetProcessIdFromName
(
L"explorer.exe",
[](const std::wstring &lhs, const std::wstring &rhs)
{
const auto l = common::string::Tokenize(lhs, L"\\/");
const auto r = common::string::Tokenize(rhs, L"\\/");
return 0 == _wcsicmp((*l.rbegin()).c_str(), (*r.rbegin()).c_str());
}
);
auto explorerHandle = OpenProcess(PROCESS_CREATE_PROCESS, FALSE, explorerPid);
if (NULL == explorerHandle)
{
THROW_ERROR("Could not acquire handle to explorer");
}
common::memory::ScopeDestructor sd;
sd += [explorerHandle]
{
CloseHandle(explorerHandle);
};
//
// Prepare data struct that will be used to launch
// subprocess as child of explorer.exe
//
SIZE_T requiredBufferSize = 0;
InitializeProcThreadAttributeList(nullptr, 1, 0, &requiredBufferSize);
std::vector<uint8_t> attributeListBuffer(requiredBufferSize);
auto attributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)&attributeListBuffer[0];
auto instanceSize = requiredBufferSize;
auto status = InitializeProcThreadAttributeList(attributeList, 1, 0, &instanceSize);
if (FALSE == status)
{
THROW_WINDOWS_ERROR(GetLastError(), "Initialize attribute list for subprocess");
}
//
// We can't use the ScopeDestructor to delete `attributeList`
// because the buffer backing it may already be gone.
//
status = UpdateProcThreadAttribute
(
attributeList,
0,
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS,
&explorerHandle,
sizeof(explorerHandle),
nullptr,
nullptr
);
if (FALSE == status)
{
DeleteProcThreadAttributeList(attributeList);
THROW_WINDOWS_ERROR(GetLastError(), "Update parent process attribute for subprocess");
}
//
// Launch unrelated app.
//
HANDLE processHandle = INVALID_HANDLE_VALUE;
try
{
processHandle = LaunchProcess(path, args, creationFlags, attributeList);
}
catch (...)
{
DeleteProcThreadAttributeList(attributeList);
throw;
}
DeleteProcThreadAttributeList(attributeList);
return processHandle;
}
HANDLE Fork(const std::vector<std::wstring> &args)
{
return LaunchProcess(_wpgmptr, args, CREATE_NEW_CONSOLE);
}
void PrintGreen(const std::wstring &str)
{
constexpr WORD WhiteOnGreen = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | BACKGROUND_GREEN;
PrintWithColor(str, WhiteOnGreen);
}
void PrintRed(const std::wstring &str)
{
constexpr WORD WhiteOnRed = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | BACKGROUND_RED;
PrintWithColor(str, WhiteOnRed);
}
void GetAdapterAddresses(const std::wstring &adapterName, IN_ADDR *ipv4, IN6_ADDR *ipv6)
{
const DWORD flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER;
if (ipv4 != NULL)
{
common::network::Adapters adapters(AF_INET, flags);
bool ipv4Done = false;
for (auto adapter = adapters.next(); adapter != NULL; adapter = adapters.next())
{
if (0 != _wcsicmp(adapter->FriendlyName, adapterName.c_str()))
{
continue;
}
if (adapter->Ipv4Enabled == 0
|| adapter->FirstUnicastAddress == nullptr)
{
break;
}
auto sa = (SOCKADDR_IN*)adapter->FirstUnicastAddress->Address.lpSockaddr;
*ipv4 = sa->sin_addr;
ipv4Done = true;
break;
}
if (!ipv4Done)
{
throw std::runtime_error("Could not determine adapter IPv4 address");
}
}
if (ipv6 != NULL)
{
common::network::Adapters adapters6(AF_INET6, flags);
bool ipv6Done = false;
for (auto adapter = adapters6.next(); adapter != NULL; adapter = adapters6.next())
{
if (0 != _wcsicmp(adapter->FriendlyName, adapterName.c_str()))
{
continue;
}
if (adapter->Ipv6Enabled == 0
|| adapter->FirstUnicastAddress == nullptr)
{
break;
}
auto sa = (SOCKADDR_IN6*)adapter->FirstUnicastAddress->Address.lpSockaddr;
*ipv6 = sa->sin6_addr;
ipv6Done = true;
break;
}
if (!ipv6Done)
{
throw std::runtime_error("Could not determine adapter IPv6 address");
}
}
}
std::wstring IpToString(const IN_ADDR &ip)
{
const auto NBO = common::string::AddressOrder::NetworkByteOrder;
return common::string::FormatIpv4<NBO>(ip.s_addr);
}
IN_ADDR ParseIpv4(const std::wstring &ip)
{
IN_ADDR rawIp;
auto status = InetPtonW(AF_INET, ip.c_str(), &rawIp.s_addr);
if (status != 1)
{
THROW_ERROR("Unable to parse IP address");
}
return rawIp;
}
bool operator==(const IN_ADDR &lhs, const IN_ADDR &rhs)
{
return lhs.s_addr == rhs.s_addr;
}
bool ProtoArgumentTcp(const std::wstring &argValue)
{
if (0 == _wcsicmp(argValue.c_str(), L"tcp"))
{
return true;
}
if (0 == _wcsicmp(argValue.c_str(), L"udp"))
{
return false;
}
std::wstringstream ss;
ss << L"Invalid argument: " << argValue;
THROW_ERROR(common::string::ToAnsi(ss.str()).c_str());
}
| 8,975
|
C++
|
.cpp
| 329
| 24.723404
| 102
| 0.724368
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,011
|
sockutil.cpp
|
mullvad_win-split-tunnel/leaktest/sockutil.cpp
|
#include "sockutil.h"
#include "util.h"
#include <libcommon/error.h>
#include <libcommon/string.h>
#include <stdexcept>
#include <sstream>
#include <iomanip>
#include <cassert>
std::string FormatWsaError(int errorCode)
{
std::stringstream ss;
ss << "0x" << std::setw(8) << std::setfill('0') << std::hex << errorCode;
return ss.str();
}
SOCKET CreateBindSocket(const IN_ADDR &ip, uint16_t port, bool tcp)
{
auto s = CreateSocket(tcp);
sockaddr_in endpoint = { 0 };
endpoint.sin_family = AF_INET;
endpoint.sin_port = htons(port);
endpoint.sin_addr = ip;
auto status = bind(s, (sockaddr*)&endpoint, sizeof(endpoint));
if (SOCKET_ERROR == status)
{
const auto errorCode = WSAGetLastError();
closesocket(s);
const auto err = std::string("Failed to bind socket: ")
.append(FormatWsaError(errorCode));
THROW_ERROR(err.c_str());
}
return s;
}
SOCKET CreateBindSocket(const std::wstring &ip, uint16_t port, bool tcp)
{
return CreateBindSocket(ParseIpv4(ip), port, tcp);
}
SOCKET CreateSocket(bool tcp)
{
const auto [type, protocol] = tcp
? std::make_pair<>(SOCK_STREAM, IPPROTO_TCP)
: std::make_pair<>(SOCK_DGRAM, IPPROTO_UDP);
auto s = socket(AF_INET, type, protocol);
if (INVALID_SOCKET == s)
{
THROW_ERROR("Failed to create socket");
}
return s;
}
void ShutdownSocket(SOCKET &s)
{
if (s != INVALID_SOCKET)
{
shutdown(s, SD_BOTH);
closesocket(s);
s = INVALID_SOCKET;
}
}
void ConnectSocket(SOCKET s, const IN_ADDR &ip, uint16_t port)
{
sockaddr_in peer = { 0 };
peer.sin_family = AF_INET;
peer.sin_port = htons(port);
peer.sin_addr = ip;
if (SOCKET_ERROR == connect(s, (sockaddr*)&peer, sizeof(peer)))
{
const auto lastError = WSAGetLastError();
const auto err = std::string("Failed to connect socket: ")
.append(FormatWsaError(lastError));
THROW_WINDOWS_ERROR(lastError, err.c_str());
}
}
void ConnectSocket(SOCKET s, const std::wstring &ip, uint16_t port)
{
ConnectSocket(s, ParseIpv4(ip), port);
}
std::vector<uint8_t> SendRecvSocket(SOCKET s, const std::vector<uint8_t> &sendBuffer)
{
auto status = send(s, (const char *)&sendBuffer[0], (int)sendBuffer.size(), 0);
if (SOCKET_ERROR == status)
{
const auto err = std::string("Failed to send on socket: ")
.append(FormatWsaError(WSAGetLastError()));
THROW_ERROR(err.c_str());
}
if (status != sendBuffer.size())
{
std::stringstream ss;
ss << "Failed to send() on socket. Sent " << status << " of " << sendBuffer.size() << " bytes";
THROW_ERROR(ss.str().c_str());
}
std::vector<uint8_t> receiveBuffer(1024, 0);
status = recv(s, (char *)&receiveBuffer[0], (int)receiveBuffer.size(), 0);
if (SOCKET_ERROR == status)
{
const auto err = std::string("Failed to receive on socket: ")
.append(FormatWsaError(WSAGetLastError()));
THROW_ERROR(err.c_str());
}
receiveBuffer.resize(status);
return receiveBuffer;
}
void SendRecvValidateEcho(SOCKET s, const std::vector<uint8_t> &sendBuffer)
{
const auto receiveBuffer = SendRecvSocket(s, sendBuffer);
if (receiveBuffer.size() != sendBuffer.size()
|| 0 != memcmp(&receiveBuffer[0], &sendBuffer[0], receiveBuffer.size()))
{
THROW_ERROR("Invalid echo response");
}
}
sockaddr_in QueryBind(SOCKET s)
{
sockaddr_in bind = { 0 };
int bindSize = sizeof(bind);
if (SOCKET_ERROR == getsockname(s, (sockaddr*)&bind, &bindSize))
{
const auto err = std::string("Failed to query bind: ")
.append(FormatWsaError(WSAGetLastError()));
THROW_ERROR(err.c_str());
}
if (bindSize != sizeof(bind))
{
THROW_ERROR("Invalid data returned for bind query");
}
return bind;
}
void ValidateBind(SOCKET s, const IN_ADDR &ip)
{
auto actualBind = QueryBind(s);
if (actualBind.sin_addr.s_addr != ip.s_addr)
{
std::wstringstream ss;
ss << L"Unexpected socket bind. Expected address " << IpToString(ip)
<< L", Actual address " << IpToString(actualBind.sin_addr);
THROW_ERROR(common::string::ToAnsi(ss.str()).c_str());
}
}
void SetSocketRecvTimeout(SOCKET s, std::chrono::milliseconds timeout)
{
DWORD rawTimeout = static_cast<DWORD>(timeout.count());
const auto status = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<char*>(&rawTimeout), sizeof(rawTimeout));
if (SOCKET_ERROR == status)
{
const auto errorCode = WSAGetLastError();
const auto err = std::string("Failed to set socket recv timeout: ")
.append(FormatWsaError(errorCode));
THROW_ERROR(err.c_str());
}
}
SOCKET CreateBindOverlappedSocket(const IN_ADDR &ip, uint16_t port, bool tcp)
{
//
// Turns out all sockets on Windows support overlapped operations.
//
return CreateBindSocket(ip, port, tcp);
}
SOCKET CreateBindOverlappedSocket(const std::wstring &ip, uint16_t port, bool tcp)
{
return CreateBindOverlappedSocket(ParseIpv4(ip), port, tcp);
}
WinsockOverlapped *AllocateWinsockOverlapped()
{
auto ctx = new WinsockOverlapped;
ZeroMemory(&ctx->overlapped, sizeof(ctx->overlapped));
ctx->overlapped.hEvent = WSACreateEvent();
ZeroMemory(&ctx->winsockBuffer, sizeof(ctx->winsockBuffer));
ctx->pendingOperation = false;
return ctx;
}
void DeleteWinsockOverlapped(WinsockOverlapped **ctx)
{
if ((*ctx)->pendingOperation)
{
WaitForSingleObject((*ctx)->overlapped.hEvent, INFINITE);
}
WSACloseEvent((*ctx)->overlapped.hEvent);
delete *ctx;
*ctx = nullptr;
}
void AssignOverlappedBuffer(WinsockOverlapped &ctx, std::vector<uint8_t> &&buffer)
{
assert(!ctx.pendingOperation);
ctx.buffer.swap(buffer);
ctx.winsockBuffer.buf = reinterpret_cast<CHAR*>(&ctx.buffer[0]);
ctx.winsockBuffer.len = static_cast<ULONG>(ctx.buffer.size());
}
void SendOverlappedSocket(SOCKET s, WinsockOverlapped &ctx)
{
assert(!ctx.pendingOperation);
WSAResetEvent(ctx.overlapped.hEvent);
const auto status = WSASend(s, &ctx.winsockBuffer, 1, nullptr, 0, &ctx.overlapped, nullptr);
if (0 == status || (SOCKET_ERROR == status && WSA_IO_PENDING == WSAGetLastError()))
{
ctx.pendingOperation = true;
return;
}
THROW_WINDOWS_ERROR(WSAGetLastError(), "WSASend");
}
void RecvOverlappedSocket(SOCKET s, WinsockOverlapped &ctx, size_t bytes)
{
assert(!ctx.pendingOperation);
WSAResetEvent(ctx.overlapped.hEvent);
if (ctx.winsockBuffer.len != bytes)
{
ctx.winsockBuffer.len = static_cast<ULONG>(bytes);
if (ctx.buffer.size() < bytes)
{
ctx.buffer.resize(bytes);
ctx.winsockBuffer.buf = reinterpret_cast<CHAR*>(&ctx.buffer[0]);
}
}
DWORD flags = 0;
const auto status = WSARecv(s, &ctx.winsockBuffer, 1, nullptr, &flags, &ctx.overlapped, nullptr);
if (0 == status || (SOCKET_ERROR == status && WSA_IO_PENDING == WSAGetLastError()))
{
ctx.pendingOperation = true;
return;
}
THROW_WINDOWS_ERROR(WSAGetLastError(), "WSARecv");
}
bool PollOverlappedSend(SOCKET s, WinsockOverlapped &ctx)
{
assert(ctx.pendingOperation);
DWORD bytesTransferred;
DWORD flags;
const auto status = WSAGetOverlappedResult(s, &ctx.overlapped, &bytesTransferred, FALSE, &flags);
if (FALSE == status)
{
if (WSA_IO_INCOMPLETE == WSAGetLastError())
{
return false;
}
THROW_WINDOWS_ERROR(WSAGetLastError(), "Overlapped send");
}
ctx.pendingOperation = false;
if (bytesTransferred != ctx.winsockBuffer.len)
{
THROW_ERROR("Overlapped send completed but did not transfer all bytes");
}
return true;
}
bool PollOverlappedRecv(SOCKET s, WinsockOverlapped &ctx)
{
assert(ctx.pendingOperation);
DWORD bytesTransferred;
DWORD flags;
const auto status = WSAGetOverlappedResult(s, &ctx.overlapped, &bytesTransferred, FALSE, &flags);
if (FALSE == status)
{
if (WSA_IO_INCOMPLETE == WSAGetLastError())
{
return false;
}
THROW_WINDOWS_ERROR(WSAGetLastError(), "Overlapped receive");
}
ctx.pendingOperation = false;
ctx.winsockBuffer.len = bytesTransferred;
return true;
}
| 7,763
|
C++
|
.cpp
| 259
| 27.586873
| 118
| 0.727175
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,012
|
settings.cpp
|
mullvad_win-split-tunnel/leaktest/settings.cpp
|
#include "settings.h"
#include <fstream>
#include <stdexcept>
#include <vector>
//static
Settings Settings::FromFile(const std::filesystem::path &filename)
{
std::ifstream source(filename);
if (!source.is_open())
{
throw std::runtime_error("Failed to open settings file");
}
std::vector<std::wstring> intermediate;
for (std::string kvp; source >> kvp; intermediate.emplace_back(common::string::ToWide(kvp)));
return Settings(std::move(common::string::SplitKeyValuePairs(intermediate)));
}
const std::wstring &Settings::get(const std::wstring &key)
{
auto it = m_values.find(key);
if (it == m_values.end())
{
throw std::runtime_error("Settings key not present in settings file");
}
return it->second;
}
| 726
|
C++
|
.cpp
| 25
| 27.08
| 94
| 0.737374
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,013
|
runtimesettings.cpp
|
mullvad_win-split-tunnel/leaktest/runtimesettings.cpp
|
#include "runtimesettings.h"
#include "util.h"
#include <libcommon/error.h>
#include <ws2tcpip.h>
#include <vector>
namespace
{
std::filesystem::path g_SettingsFilePathOverride;
} // anonymous namespace
RuntimeSettings::RuntimeSettings(Settings settings)
: m_settings(std::move(settings))
{
}
//static
std::filesystem::path RuntimeSettings::GetSettingsFilePath()
{
if (!g_SettingsFilePathOverride.empty())
{
return g_SettingsFilePathOverride;
}
wchar_t *rawPath;
if (0 != _get_wpgmptr(&rawPath))
{
throw std::runtime_error(__FUNCTION__ ": _get_wpgmptr choked");
}
std::filesystem::path path(rawPath);
if (!path.is_absolute())
{
throw std::runtime_error("Could not construct path for settings file");
}
path.replace_filename(L"leaktest.settings");
return path;
}
//static
void RuntimeSettings::OverrideSettingsFilePath(const std::filesystem::path &path)
{
g_SettingsFilePathOverride = path;
}
//static
RuntimeSettings &RuntimeSettings::Instance()
{
//
// This is fine for testing code.
//
// Lazy construction and lazy evaluation means a test that doesn't rely on settings
// can be ran without creating a settings file.
//
static RuntimeSettings *Instance = nullptr;
if (Instance == nullptr)
{
Instance = new RuntimeSettings(Settings::FromFile(GetSettingsFilePath()));
}
return *Instance;
}
IN_ADDR RuntimeSettings::tunnelIp()
{
if (m_tunnelIp.has_value())
{
return m_tunnelIp.value();
}
auto adapterName = m_settings.get(L"TunnelAdapter");
IN_ADDR ipv4;
GetAdapterAddresses(adapterName, &ipv4, nullptr);
m_tunnelIp = ipv4;
return ipv4;
}
IN6_ADDR RuntimeSettings::tunnelIp6()
{
if (m_tunnelIp6.has_value())
{
return m_tunnelIp6.value();
}
auto adapterName = m_settings.get(L"TunnelAdapter");
IN6_ADDR ipv6;
GetAdapterAddresses(adapterName, nullptr, &ipv6);
m_tunnelIp6 = ipv6;
return ipv6;
}
IN_ADDR RuntimeSettings::lanIp()
{
if (m_lanIp.has_value())
{
return m_lanIp.value();
}
auto adapterName = m_settings.get(L"LanAdapter");
IN_ADDR ipv4;
GetAdapterAddresses(adapterName, &ipv4, nullptr);
m_lanIp = ipv4;
return ipv4;
}
IN6_ADDR RuntimeSettings::lanIp6()
{
if (m_lanIp6.has_value())
{
return m_lanIp6.value();
}
auto adapterName = m_settings.get(L"LanAdapter");
IN6_ADDR ipv6;
GetAdapterAddresses(adapterName, nullptr, &ipv6);
m_lanIp6 = ipv6;
return ipv6;
}
IN_ADDR RuntimeSettings::publicNonVpnIp()
{
if (m_publicNonVpnIp.has_value())
{
return m_publicNonVpnIp.value();
}
auto ip = m_settings.get(L"PublicNonVpnIp");
sockaddr_in endpoint = { 0 };
auto status = InetPtonW(AF_INET, ip.c_str(), &endpoint.sin_addr.s_addr);
if (status != 1)
{
THROW_ERROR("Unable to parse IP address");
}
m_publicNonVpnIp = endpoint.sin_addr;
return endpoint.sin_addr;
}
IN_ADDR RuntimeSettings::tcpbinServerIp()
{
if (m_tcpbinServerIp.has_value())
{
return m_tcpbinServerIp.value();
}
auto ip = m_settings.get(L"TcpBinServerIp");
sockaddr_in endpoint = { 0 };
auto status = InetPtonW(AF_INET, ip.c_str(), &endpoint.sin_addr.s_addr);
if (status != 1)
{
THROW_ERROR("Unable to parse IP address");
}
m_tcpbinServerIp = endpoint.sin_addr;
return endpoint.sin_addr;
}
uint16_t RuntimeSettings::tcpbinEchoPort()
{
if (m_tcpbinEchoPort.has_value())
{
return m_tcpbinEchoPort.value();
}
auto port = m_settings.get(L"TcpBinEchoPort");
auto numericalPort = common::string::LexicalCast<uint16_t>(port);
m_tcpbinEchoPort = numericalPort;
return numericalPort;
}
uint16_t RuntimeSettings::tcpbinEchoPortUdp()
{
if (m_tcpbinEchoPortUdp.has_value())
{
return m_tcpbinEchoPortUdp.value();
}
auto port = m_settings.get(L"TcpBinEchoPortUdp");
auto numericalPort = common::string::LexicalCast<uint16_t>(port);
m_tcpbinEchoPortUdp = numericalPort;
return numericalPort;
}
uint16_t RuntimeSettings::tcpbinInfoPort()
{
if (m_tcpbinInfoPort.has_value())
{
return m_tcpbinInfoPort.value();
}
auto port = m_settings.get(L"TcpBinInfoPort");
auto numericalPort = common::string::LexicalCast<uint16_t>(port);
m_tcpbinInfoPort = numericalPort;
return numericalPort;
}
| 4,127
|
C++
|
.cpp
| 167
| 22.51497
| 84
| 0.750964
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,014
|
leaktest.cpp
|
mullvad_win-split-tunnel/leaktest/leaktest.cpp
|
#include <ws2tcpip.h> // include before windows.h
#include "general/gen1.h"
#include "split-tunnel/st1.h"
#include "split-tunnel/st2.h"
#include "split-tunnel/st3.h"
#include "split-tunnel/st4.h"
#include "split-tunnel/st5.h"
#include "split-tunnel/st6.h"
#include "split-tunnel/st7.h"
#include "util.h"
#include "sockutil.h"
#include <libcommon/error.h>
#include <libcommon/string.h>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <functional>
#include <windows.h>
namespace
{
bool g_PauseBeforeExit = false;
int g_ProcessExitCode = 0;
bool g_UseProcessExitCode = false;
} // anonymous namespace
void SetPauseBeforeExit(bool pause)
{
g_PauseBeforeExit = pause;
}
void MaybePauseBeforeExit()
{
if (g_PauseBeforeExit)
{
std::wcout << L"Press a key to continue..." << std::endl;
_getwch();
}
}
void SetProcessExitCode(int exitCode)
{
g_ProcessExitCode = exitCode;
g_UseProcessExitCode = true;
}
bool innerMain(int argc, wchar_t *argv[])
{
if (argc < 2)
{
THROW_ERROR("Test ID not specified");
}
const std::wstring testId = argv[1];
std::vector<std::wstring> arguments;
for (size_t argumentIndex = 2; argumentIndex < argc; ++argumentIndex)
{
arguments.emplace_back(argv[argumentIndex]);
}
//
// Declare all test cases.
//
struct TestCase
{
std::wstring id;
std::function<bool(const std::vector<std::wstring> &)> handler;
};
std::vector<TestCase> tests =
{
{ L"gen1", TestCaseGen1},
{ L"st1", TestCaseSt1 },
{ L"st2", TestCaseSt2 },
{ L"st3", TestCaseSt3 },
{ L"st4", TestCaseSt4 },
{ L"st5", TestCaseSt5 },
{ L"st5-child", TestCaseSt5Child },
{ L"st6", TestCaseSt6 },
{ L"st6-server", TestCaseSt6Server },
{ L"st6-client", TestCaseSt6Client },
{ L"st7", TestCaseSt7 },
{ L"st7-child", TestCaseSt7Child },
};
//
// Find and invoke matching handler.
//
for (const auto &candidate : tests)
{
if (0 != _wcsicmp(testId.c_str(), candidate.id.c_str()))
{
continue;
}
return candidate.handler(arguments);
}
//
// Invalid test id specified on command line.
//
std::stringstream ss;
ss << "Invalid test id: " << common::string::ToAnsi(testId);
THROW_ERROR(ss.str().c_str());
}
int wmain(int argc, wchar_t *argv[])
{
WSADATA winSockData;
if (0 != WSAStartup(MAKEWORD(2, 2), &winSockData))
{
std::cerr << "Failed to initialize winsock: " << FormatWsaError(WSAGetLastError()) << std::endl;
return 1;
}
if (LOBYTE(winSockData.wVersion) != 2 || HIBYTE(winSockData.wVersion) != 2)
{
WSACleanup();
std::cerr << "Could not find/load winsock 2.2 implementation" << std::endl;
return 1;
}
auto successful = false;
try
{
successful = innerMain(argc, argv);
}
catch (const std::exception &err)
{
std::cerr << "EXCEPTION: " << err.what() << std::endl;
}
catch (...)
{
std::cerr << "EXCEPTION: Unknown error" << std::endl;
}
if (successful)
{
PrintGreen(L"--> PASS <--");
}
else
{
PrintRed(L"!!! FAIL !!!");
}
MaybePauseBeforeExit();
if (successful)
{
return (g_UseProcessExitCode ? g_ProcessExitCode : 0);
}
return 1;
}
| 3,096
|
C++
|
.cpp
| 137
| 20.394161
| 98
| 0.688653
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,015
|
st2.cpp
|
mullvad_win-split-tunnel/leaktest/split-tunnel/st2.cpp
|
#include "st2.h"
#include <iostream>
#include <ws2tcpip.h>
#include "../util.h"
#include "../runtimesettings.h"
#include "../sockutil.h"
#include <libcommon/memory.h>
constexpr auto SocketRecvTimeoutValue = std::chrono::milliseconds(2000);
bool TestCaseSt2(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Launching split tunnel test case 2" << std::endl;
std::wcout << L"Evaluate whether existing connections are blocked when an app becomes excluded" << std::endl;
std::wcout << L"===" << std::endl;
ArgumentContext argsContext(arguments);
const auto tcp = ProtoArgumentTcp(argsContext.nextOrDefault(L"tcp"));
argsContext.assertExhausted();
PromptActivateVpn();
std::wcout << "Creating socket and binding to tunnel IP" << std::endl;
auto tunnelSocket = CreateBindSocket(RuntimeSettings::Instance().tunnelIp(), 0, tcp);
common::memory::ScopeDestructor sd;
sd += [&tunnelSocket]
{
ShutdownSocket(tunnelSocket);
};
if (!tcp)
{
SetSocketRecvTimeout(tunnelSocket, SocketRecvTimeoutValue);
}
std::wcout << L"Connecting to tcpbin server" << std::endl;
ConnectSocket
(
tunnelSocket,
RuntimeSettings::Instance().tcpbinServerIp(),
tcp ? RuntimeSettings::Instance().tcpbinEchoPort() : RuntimeSettings::Instance().tcpbinEchoPortUdp()
);
std::wcout << L"Communicating with echo service to establish connectivity" << std::endl;
SendRecvValidateEcho(tunnelSocket, { 'h', 'e', 'y', 'n', 'o', 'w' });
std::wcout << L"Querying bind to verify correct interface is used" << std::endl;
ValidateBind(tunnelSocket, RuntimeSettings::Instance().tunnelIp());
PromptActivateSplitTunnel();
std::wcout << L"Testing comms on LAN interface" << std::endl;
auto lanSocket = CreateBindSocket(RuntimeSettings::Instance().lanIp(), 0, tcp);
sd += [&lanSocket]
{
ShutdownSocket(lanSocket);
};
ConnectSocket
(
lanSocket,
RuntimeSettings::Instance().tcpbinServerIp(),
tcp ? RuntimeSettings::Instance().tcpbinEchoPort() : RuntimeSettings::Instance().tcpbinEchoPortUdp()
);
SendRecvValidateEcho(lanSocket, { 'h', 'e', 'y', 'n', 'o', 'w' });
std::wcout << L"Sending and receiving to validate blocking policies" << std::endl;
try
{
SendRecvValidateEcho(tunnelSocket, { 'b', 'l', 'o', 'c', 'k', 'e', 'd' });
}
catch (const std::exception &err)
{
std::cout << "Sending and receiving failed with message: " << err.what() << std::endl;
std::wcout << L"Assuming firewall filters are blocking comms" << std::endl;
return true;
}
std::wcout << L"Traffic leak!" << std::endl;
return false;
}
| 2,551
|
C++
|
.cpp
| 67
| 35.626866
| 110
| 0.721091
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,016
|
st1.cpp
|
mullvad_win-split-tunnel/leaktest/split-tunnel/st1.cpp
|
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
#include "st1.h"
#include <iostream>
#include <optional>
#include <ws2tcpip.h> // include before windows.h
#include <libcommon/security.h>
#include <libcommon/error.h>
#include <libcommon/string.h>
#include "../util.h"
#include "../runtimesettings.h"
#include "../sockutil.h"
#include "../leaktest.h"
namespace
{
std::vector<uint8_t> GenerateEchoPayload()
{
std::stringstream ss;
ss << GetTickCount64();
std::vector<uint8_t> payload;
//
// stringstream returns a copy, not a reference.
//
const auto source = ss.str();
payload.reserve(source.size());
std::transform(source.begin(), source.end(), std::back_inserter(payload), [](char c)
{
return static_cast<uint8_t>(c);
});
return payload;
}
void EvaluateSplitting(std::optional<IN_ADDR> bindAddr, const IN_ADDR &expectedActualBind, bool tcp)
{
SOCKET s;
if (bindAddr.has_value())
{
std::wcout << L"Creating socket and explicitly binding it" << std::endl;
s = CreateBindSocket(bindAddr.value(), 0, tcp);
}
else
{
std::wcout << L"Creating socket and leaving it unbound" << std::endl;
s = CreateSocket(tcp);
}
common::memory::ScopeDestructor sd;
sd += [&s]
{
ShutdownSocket(s);
};
std::wcout << L"Connecting to tcpbin server" << std::endl;
ConnectSocket
(
s,
RuntimeSettings::Instance().tcpbinServerIp(),
tcp ? RuntimeSettings::Instance().tcpbinEchoPort() : RuntimeSettings::Instance().tcpbinEchoPortUdp()
);
std::wcout << L"Communicating with echo service to establish connectivity" << std::endl;
SendRecvValidateEcho(s, GenerateEchoPayload());
std::wcout << L"Querying bind to verify correct interface is used" << std::endl;
ValidateBind(s, expectedActualBind);
}
bool RunSubtest(std::optional<IN_ADDR> bindAddr, const IN_ADDR &expectedActualBind, bool tcp)
{
try
{
EvaluateSplitting(bindAddr, expectedActualBind, tcp);
return true;
}
catch (const std::exception &err)
{
std::wcout << "EXCEPTION: " << err.what() << std::endl;
return false;
}
catch (...)
{
std::cerr << "EXCEPTION: Unknown error" << std::endl;
return false;
}
}
} // anonymous namespace
bool TestCaseSt1(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Launching split tunnel test case 1" << std::endl;
std::wcout << L"Evaluate whether different kinds of binds are correctly handled" << std::endl;
std::wcout << L"===" << std::endl;
ArgumentContext argsContext(arguments);
const auto tcp = ProtoArgumentTcp(argsContext.nextOrDefault(L"tcp"));
argsContext.assertExhausted();
PromptActivateVpnSplitTunnel();
//
// There are three relevant tests:
//
// (localhost binds are tested separately)
//
// 1: Bind to tunnel and validate that bind is redirected to lan interface && that comms work
// 2: Bind to lan interface and validate that bind is successful && that comms work
// 3: Do not bind before connecting. Validate that bind is directed to lan interface && that comms work
//
std::wcout << L">> Testing explicit bind to tunnel interface" << std::endl;
const auto subtest1 = RunSubtest
(
std::make_optional<>(RuntimeSettings::Instance().tunnelIp()),
RuntimeSettings::Instance().lanIp(),
tcp
);
std::wcout << L">> Testing explicit bind to LAN interface" << std::endl;
const auto subtest2 = RunSubtest
(
std::make_optional<>(RuntimeSettings::Instance().lanIp()),
RuntimeSettings::Instance().lanIp(),
tcp
);
std::wcout << L">> Testing implicit bind" << std::endl;
const auto subtest3 = RunSubtest
(
std::nullopt,
RuntimeSettings::Instance().lanIp(),
tcp
);
return subtest1 && subtest2 && subtest3;
}
| 3,629
|
C++
|
.cpp
| 120
| 27.925
| 104
| 0.722318
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,017
|
st4.cpp
|
mullvad_win-split-tunnel/leaktest/split-tunnel/st4.cpp
|
#include "st4.h"
#include <iostream>
#include <ws2tcpip.h>
#include <windns.h>
#include "../util.h"
#include "../runtimesettings.h"
#include "../sockutil.h"
#include <libcommon/error.h>
#include <libcommon/process/applicationrunner.h>
using Runner = common::process::ApplicationRunner;
namespace
{
std::wstring GetPktmonPath()
{
return L"c:\\windows\\system32\\pktmon.exe";
}
void PktmonCommand(const std::wstring &arguments, const char *errorMessage)
{
auto command = Runner::StartWithoutConsole(GetPktmonPath(), arguments);
DWORD status;
command->join(status, INFINITE);
if (status != 0)
{
THROW_ERROR(errorMessage);
}
}
void PktmonRemoveFilters()
{
PktmonCommand(L"filter remove", "Could not remove pktmon filters");
}
void PktmonAddFilter(const std::wstring &filterSpec)
{
PktmonCommand(std::wstring(L"filter add ").append(filterSpec), "Could not add pktmon filter");
}
void PktmonStart()
{
PktmonCommand(L"start", "Could not activate pktmon");
}
void PktmonStop()
{
PktmonCommand(L"stop", "Could not stop pktmon");
}
std::string PktmonStopCaptureOutput()
{
auto stopCommand = Runner::StartWithoutConsole(GetPktmonPath(), L"stop");
DWORD status;
stopCommand->join(status, INFINITE);
if (status != 0)
{
THROW_ERROR("Could not stop pktmon");
}
std::string output;
if (false == stopCommand->read(output, 1024, INFINITE))
{
THROW_ERROR("Stopped pktmon but could not capture output");
}
return output;
}
void SendDnsRequest()
{
DNS_RECORDW *record = nullptr;
for (auto i = 0; i < 3; ++i)
{
if (i != 0)
{
Sleep(1000);
}
std::wcout << L"Sending DNS query for A-record" << std::endl;
const DWORD flags = DNS_QUERY_BYPASS_CACHE | DNS_QUERY_WIRE_ONLY;
const auto status = DnsQuery_W(L"mullvad.net", DNS_TYPE_A, flags, nullptr, &record, nullptr);
if (0 != status)
{
THROW_WINDOWS_ERROR(status, "Query DNS A-record");
}
const auto ip = IpToString(*reinterpret_cast<in_addr*>(&record->Data.A.IpAddress));
std::wcout << L"Response" << std::endl;
std::wcout << L" name: " << record->pName << std::endl;
std::wcout << L" addr: " << ip << std::endl;
DnsRecordListFree(record, DnsFreeRecordList);
}
}
bool TestCaseSt4Inner(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Launching split tunnel test case 4" << std::endl;
std::wcout << L"Evaluate whether DNS requests can be moved outside tunnel" << std::endl;
std::wcout << L"===" << std::endl;
ArgumentContext argsContext(arguments);
argsContext.ensureExactArgumentCount(0);
PromptActivateVpn();
std::wcout << L"Getting pktmon ready" << std::endl;
try
{
PktmonStop();
}
catch (...)
{
}
//
// Removing filters always succeeds with exit code 0.
// Unless we're lacking an elevated token.
//
try
{
PktmonRemoveFilters();
}
catch (...)
{
THROW_ERROR("Re-launch test from elevated context");
}
std::wstringstream ss;
ss << L"landns -d IPv4 --ip "
<< IpToString(RuntimeSettings::Instance().lanIp())
<< L" --port 53";
PktmonAddFilter(ss.str());
PktmonStart();
PromptActivateSplitTunnel();
SendDnsRequest();
const auto output = PktmonStopCaptureOutput();
const bool capturedNothing =
(&output[0] == strstr(&output[0], "All counters are zero."));
if (capturedNothing)
{
std::wcout << L"No DNS requests were captured on the LAN interface" << std::endl;
return false;
}
//
// There's nothing useful or identifying in the output.
// One improvement would be to configure different DNS servers on the LAN interface
// and the tunnel interface, and use a more specific filter in pktmon.
//
std::wcout << L"DNS requests successfully captured on LAN interface" << std::endl;
return true;
}
} // anonymous namespace
bool TestCaseSt4(const std::vector<std::wstring> &arguments)
{
auto cleanup = []()
{
try
{
PktmonStop();
}
catch (...)
{
}
try
{
PktmonRemoveFilters();
}
catch (...)
{
}
};
try
{
const auto status = TestCaseSt4Inner(arguments);
cleanup();
return status;
}
catch (...)
{
cleanup();
throw;
}
}
| 4,070
|
C++
|
.cpp
| 165
| 22.29697
| 95
| 0.707608
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,018
|
st5.cpp
|
mullvad_win-split-tunnel/leaktest/split-tunnel/st5.cpp
|
#include "st5.h"
#include <iostream>
#include <ws2tcpip.h>
#include "../util.h"
#include "../runtimesettings.h"
#include "../sockutil.h"
#include "../leaktest.h"
#include <libcommon/memory.h>
#include <chrono>
namespace
{
class WaitAssistant
{
public:
WaitAssistant(DWORD maxWaitTimeMs)
: m_maxWaitTime(maxWaitTimeMs)
{
}
//
// Returns max time in ms that can be waited for.
// Or 0 if the max waiting time has already been reached.
//
DWORD getWaitTime() const
{
const auto now = std::chrono::steady_clock::now();
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - startTime);
return (elapsed > m_maxWaitTime ? 0 : static_cast<DWORD>((m_maxWaitTime - elapsed).count()));
}
private:
const std::chrono::milliseconds m_maxWaitTime;
using time_point = std::chrono::time_point<std::chrono::steady_clock>;
const time_point startTime = std::chrono::steady_clock::now();
};
HANDLE
LaunchChild
(
const std::filesystem::path &path,
const std::filesystem::path &settingsFilePath,
const std::wstring &tunnelIp,
const std::wstring &lanIp
)
{
const auto quotedSettingsFile = std::wstring(L"\"").append(settingsFilePath).append(L"\"");
return LaunchProcess
(
path,
std::vector<std::wstring> {L"st5-child", quotedSettingsFile, tunnelIp, lanIp},
CREATE_NO_WINDOW
);
}
enum class ChildExitCode
{
// If child process fails to override exit code before completing.
// This "can't" happen.
GeneralSuccess = 0,
// If child process throws before able to complete.
GeneralFailure = 1,
// Bind was successful and was NOT redirected.
BoundTunnel = 2,
// Bind was successful and was redirected.
BoundLan = 3
};
std::vector<uint8_t> GenerateChildPayload()
{
std::stringstream ss;
ss << "st-5-child:" << GetCurrentProcessId();
std::vector<uint8_t> payload;
//
// stringstream returns a copy, not a reference.
//
const auto source = ss.str();
payload.reserve(source.size());
std::transform(source.begin(), source.end(), std::back_inserter(payload), [](char c)
{
return static_cast<uint8_t>(c);
});
return payload;
}
} // anonymous namespace
bool TestCaseSt5(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Launching split tunnel test case 5" << std::endl;
std::wcout << L"Evaluate whether child processes are automatically and atomically handled" << std::endl;
std::wcout << L"===" << std::endl;
ArgumentContext argsContext(arguments);
argsContext.ensureExactArgumentCount(0);
PromptActivateVpnSplitTunnel();
const size_t NUM_PROCESSES = 20;
std::wcout << L"Starting " << NUM_PROCESSES << L" processes to test child process association" << std::endl;
std::wcout << L"Each child will attempt to bind to the tunnel interface" << std::endl;
struct ScoreCard
{
uint64_t miscFailure;
uint64_t tunnelBind;
uint64_t lanBind;
}
scoreCard = {0,0,0};
const auto settingsFilePath = RuntimeSettings::GetSettingsFilePath();
const auto tunnelIp = IpToString(RuntimeSettings::Instance().tunnelIp());
const auto lanIp = IpToString(RuntimeSettings::Instance().lanIp());
//
// Create unique binaries, one for each child.
// This way the VPN can't use the path to determine association.
//
std::vector<std::filesystem::path> childPaths;
common::memory::ScopeDestructor sd;
sd += [&childPaths]
{
for(const auto &path : childPaths)
{
DeleteFileW(path.c_str());
}
};
childPaths.reserve(NUM_PROCESSES);
for (auto i = 0; i < NUM_PROCESSES; ++i)
{
childPaths.emplace_back(ProcessBinaryCreateRandomCopy());
}
//
// Launch all processes in quick succession, without waiting for each one to complete its work.
// This should hopefully create some CPU load and work for the scheduler.
//
std::vector<HANDLE> childProcesses;
sd += [&childProcesses]()
{
for (auto process : childProcesses)
{
CloseHandle(process);
}
};
childProcesses.reserve(NUM_PROCESSES);
for (auto i = 0; i < NUM_PROCESSES; ++i)
{
try
{
childProcesses.emplace_back(LaunchChild(childPaths[i], settingsFilePath, tunnelIp, lanIp));
}
catch (...)
{
std::wcout << L"Failed to launch child process" << std::endl;
++scoreCard.miscFailure;
}
}
const size_t MAX_WAIT_TIME_MS = 1000 * 10;
WaitAssistant waitAssistant(MAX_WAIT_TIME_MS);
for (auto process : childProcesses)
{
auto status = WaitForSingleObject(process, waitAssistant.getWaitTime());
if (WAIT_OBJECT_0 != status)
{
std::wcout << L"Child process did not complete in time" << std::endl;
++scoreCard.miscFailure;
continue;
}
DWORD exitCode;
if (FALSE == GetExitCodeProcess(process, &exitCode))
{
std::wcout << L"Failed to read child process exit code" << std::endl;
++scoreCard.miscFailure;
continue;
}
switch ((ChildExitCode)exitCode)
{
case ChildExitCode::BoundLan:
{
++scoreCard.lanBind;
break;
}
case ChildExitCode::BoundTunnel:
{
++scoreCard.tunnelBind;
break;
}
default:
{
std::wcout << L"Unexpected child exit code" << std::endl;
++scoreCard.miscFailure;
}
}
}
std::wcout << L"-----" << std::endl;
std::wcout << L"Failed to start or report status: " << scoreCard.miscFailure << std::endl;
std::wcout << L"Had their bind redirected: " << scoreCard.lanBind << std::endl;
std::wcout << L"Bypassed the split tunnel functionality: " << scoreCard.tunnelBind << std::endl;
std::wcout << L"-----" << std::endl;
return NUM_PROCESSES == scoreCard.lanBind;
}
bool TestCaseSt5Child(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Split tunnel test case 5 - Child" << std::endl;
std::wcout << L"I have PID: " << GetCurrentProcessId() << std::endl;
ArgumentContext argsContext(arguments);
argsContext.ensureExactArgumentCount(3);
const auto settingsFilePath = std::filesystem::path(argsContext.next());
const auto tunnelIp = ParseIpv4(argsContext.next());
const auto lanIp = ParseIpv4(argsContext.next());
RuntimeSettings::OverrideSettingsFilePath(settingsFilePath);
std::wcout << "Creating socket and leaving it unbound" << std::endl;
auto lanSocket = CreateSocket();
common::memory::ScopeDestructor sd;
sd += [&lanSocket]
{
ShutdownSocket(lanSocket);
};
std::wcout << L"Connecting to tcpbin server" << std::endl;
//
// Connecting will select the tunnel interface because of best metric,
// but exclusion logic should redirect the bind.
//
ConnectSocket
(
lanSocket,
RuntimeSettings::Instance().tcpbinServerIp(),
RuntimeSettings::Instance().tcpbinEchoPort()
);
std::wcout << L"Communicating with echo service to establish connectivity" << std::endl;
const auto payload = GenerateChildPayload();
SendRecvValidateEcho(lanSocket, payload);
std::wcout << L"Querying bind to determine which interface is used" << std::endl;
const auto actualBind = QueryBind(lanSocket);
if (actualBind.sin_addr == tunnelIp)
{
std::wcout << L"Bound to tunnel interface" << std::endl;
SetProcessExitCode(static_cast<int>(ChildExitCode::BoundTunnel));
return true;
}
else if (actualBind.sin_addr == lanIp)
{
std::wcout << L"Bound to LAN interface" << std::endl;
SetProcessExitCode(static_cast<int>(ChildExitCode::BoundLan));
return true;
}
std::wcout << L"Failed to match bind to known interface" << std::endl;
return false;
}
| 7,296
|
C++
|
.cpp
| 235
| 28.421277
| 109
| 0.723288
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,019
|
st6.cpp
|
mullvad_win-split-tunnel/leaktest/split-tunnel/st6.cpp
|
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
#include "st6.h"
#include <iostream>
#include <ws2tcpip.h> // include before windows.h
#include <libcommon/security.h>
#include <libcommon/error.h>
#include <libcommon/string.h>
#include "../util.h"
#include "../sockutil.h"
#include "../leaktest.h"
bool TestCaseSt6(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Launching split tunnel test case 6" << std::endl;
std::wcout << L"Evaluate whether binds to localhost are correctly NOT being redirected" << std::endl;
std::wcout << L"===" << std::endl;
ArgumentContext argsContext(arguments);
argsContext.ensureExactArgumentCount(0);
PromptActivateVpnSplitTunnel();
const auto serverAddr = std::wstring(L"127.0.0.1");
const auto serverPort = std::wstring(L"5050");
HANDLE serverProcess = NULL;
HANDLE clientProcess = NULL;
common::memory::ScopeDestructor sd;
sd += [&serverProcess, &clientProcess]()
{
if (serverProcess != NULL)
{
CloseHandle(serverProcess);
}
if (clientProcess != NULL)
{
CloseHandle(clientProcess);
}
};
std::wcout << L"Launching server process" << std::endl;
serverProcess = Fork(std::vector<std::wstring> {L"st6-server", serverAddr, serverPort});
std::wcout << L"Waiting for VPN software to catch up" << std::endl;
Sleep(1000 * 5);
std::wcout << L"Launching unrelated client process" << std::endl;
const auto childPath = ProcessBinaryCreateRandomCopy();
sd += [&childPath]
{
DeleteFileW(childPath.c_str());
};
clientProcess = LaunchUnrelatedProcess
(
childPath,
std::vector<std::wstring> {L"st6-client", serverAddr, serverPort},
CREATE_NEW_CONSOLE
);
//
// Wait for both processes to complete
//
HANDLE waitHandles[] =
{
serverProcess,
clientProcess
};
const auto numWaitHandles = _countof(waitHandles);
const auto waitStatus = WaitForMultipleObjects(numWaitHandles, waitHandles, TRUE, 1000 * 60);
if (waitStatus < WAIT_OBJECT_0
|| waitStatus > (WAIT_OBJECT_0 + numWaitHandles - 1))
{
THROW_ERROR("Failed waiting for tester processes");
}
//
// Check return codes
//
DWORD serverProcessExitCode;
DWORD clientProcessExitCode;
if (FALSE == GetExitCodeProcess(serverProcess, &serverProcessExitCode)
|| FALSE == GetExitCodeProcess(clientProcess, &clientProcessExitCode))
{
THROW_ERROR("Failed to acquire exit codes from tester processes");
}
return serverProcessExitCode == 0
&& clientProcessExitCode == 0;
}
bool TestCaseSt6Server(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Split tunnel test case 6 - Server" << std::endl;
std::wcout << L"I have PID: " << GetCurrentProcessId() << std::endl;
SetPauseBeforeExit(true);
ArgumentContext argsContext(arguments);
argsContext.ensureExactArgumentCount(2);
const auto serverAddr = argsContext.next();
const auto serverPort = argsContext.next();
std::wcout << L"Using server addr: " << serverAddr << L", port: " << serverPort << std::endl;
std::wcout << L"Creating and binding server socket" << std::endl;
//
// Get server ready.
//
auto serverSocket = CreateBindSocket(serverAddr, common::string::LexicalCast<uint16_t>(serverPort));
common::memory::ScopeDestructor sd;
sd += [&serverSocket]
{
ShutdownSocket(serverSocket);
};
std::wcout << L"Calling listen() on socket" << std::endl;
if (SOCKET_ERROR == listen(serverSocket, SOMAXCONN))
{
const auto err = std::string("Failed to listen on server socket: ")
.append(FormatWsaError(WSAGetLastError()));
THROW_ERROR(err.c_str());
}
//
// Accept peer connection.
//
std::wcout << L"Calling accept() on server socket" << std::endl;
sockaddr_in peer = { 0 };
int peerSize = sizeof(peer);
auto echoSocket = accept(serverSocket, (sockaddr*)&peer, &peerSize);
if (INVALID_SOCKET == echoSocket)
{
const auto err = std::string("Failed to accept incoming connection: ")
.append(FormatWsaError(WSAGetLastError()));
THROW_ERROR(err.c_str());
}
sd += [&echoSocket]
{
ShutdownSocket(echoSocket);
};
if (peerSize != sizeof(peer))
{
THROW_ERROR("Invalid peer info returned");
}
//
// Query server bind.
//
std::wcout << L"Retrieving bind details for server socket" << std::endl;
auto local = QueryBind(serverSocket);
std::wcout << L"Server endpoint: " << IpToString(local.sin_addr) << L":" << ntohs(local.sin_port) << std::endl;
std::wcout << L"Peer: " << IpToString(peer.sin_addr) << L":" << ntohs(peer.sin_port) << std::endl;
if (local.sin_addr != ParseIpv4(serverAddr))
{
THROW_ERROR("Unexpected server bind");
}
//
// Enter echo loop.
//
std::wcout << L"Engaging in echo messaging" << std::endl;
std::vector<uint8_t> buffer(1024);
size_t index = 0;
bool receivedSomething = false;
for (;;)
{
if (index >= 1000)
{
index = 0;
}
const auto bytesReceived = recv(echoSocket, (char*)&buffer[index], 1, 0);
if (bytesReceived != 1)
{
break;
}
receivedSomething = true;
if (0x0a != buffer[index])
{
++index;
continue;
}
buffer[++index] = 0;
std::cout << (char*)&buffer[0];
const auto bytesSent = send(echoSocket, (char*)&buffer[0], (int)index, 0);
if (bytesSent != index)
{
THROW_ERROR("Failed to send echo response");
}
index = 0;
if (nullptr != strstr((char*)&buffer[0], "exit"))
{
// Client requested to exit.
break;
}
}
return receivedSomething;
}
bool TestCaseSt6Client(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Split tunnel test case 6 - Client" << std::endl;
std::wcout << L"I have PID: " << GetCurrentProcessId() << std::endl;
SetPauseBeforeExit(true);
ArgumentContext argsContext(arguments);
argsContext.ensureExactArgumentCount(2);
const auto serverAddr = argsContext.next();
const auto serverPort = argsContext.next();
std::wcout << L"Using server addr: " << serverAddr << L", port: " << serverPort << std::endl;
std::wcout << L"Creating client socket" << std::endl;
auto echoSocket = CreateSocket();
common::memory::ScopeDestructor sd;
sd += [&echoSocket]
{
ShutdownSocket(echoSocket);
};
//
// Connect.
//
// This will momentarily bind the socket to "0.0.0.0".
// The initial bind event is passed through WFP bind redirect callouts.
//
// The bind will be corrected shortly thereafter to reflect
// which interface was actually bound to.
//
// The corrected bind is not reported to WFP callouts.
//
std::wcout << L"Connecting socket" << std::endl;
ConnectSocket(echoSocket, serverAddr, common::string::LexicalCast<uint16_t>(serverPort));
//
// Query bind after connecting.
//
// This is a little backwards, the comparison only works because we know the server
// is running on localhost.
//
std::wcout << L"Retrieving bind details for socket" << std::endl;
auto bindInfo = QueryBind(echoSocket);
std::wcout << L"Bind details: " << IpToString(bindInfo.sin_addr) << L":" << ntohs(bindInfo.sin_port) << std::endl;
if (bindInfo.sin_addr != ParseIpv4(serverAddr))
{
THROW_ERROR("Unexpected socket bind");
}
//
// Ensure socket can send/receive.
//
std::wcout << L"Verifying connection" << std::endl;
std::vector<uint8_t> out = { 'm', 'e', 'e', 'p', '\x0a' };
auto in = SendRecvSocket(echoSocket, out);
if (in.size() != out.size()
|| 0 != memcmp(&in[0], &out[0], in.size()))
{
THROW_ERROR("Invalid echo response");
}
std::wcout << L"Echo response OK" << std::endl;
//
// Query bind after comms.
//
std::wcout << L"Retrieving bind details for socket" << std::endl;
bindInfo = QueryBind(echoSocket);
std::wcout << L"Bind details: " << IpToString(bindInfo.sin_addr) << L":" << ntohs(bindInfo.sin_port) << std::endl;
if (bindInfo.sin_addr != ParseIpv4(serverAddr))
{
THROW_ERROR("Unexpected socket bind");
}
return true;
}
| 7,755
|
C++
|
.cpp
| 244
| 29.147541
| 115
| 0.701605
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,020
|
st7.cpp
|
mullvad_win-split-tunnel/leaktest/split-tunnel/st7.cpp
|
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
#include "st7.h"
#include <iostream>
#include <ws2tcpip.h>
#include <libcommon/security.h>
#include <libcommon/error.h>
#include <libcommon/string.h>
#include "../runtimesettings.h"
#include "../util.h"
#include "../sockutil.h"
#include "../leaktest.h"
// Signalled by child to indicate readiness.
const wchar_t *ReadyEventName = L"ST7-CHILD-READY-EVENT";
// Signalled by parent to command child into action.
const wchar_t *CommenceEventName = L"ST7-CHILD-COMMENCE-EVENT";
enum class ChildStatus
{
// If child process fails to override exit code before completing.
// This "can't" happen.
GeneralSuccess = 0,
// If child process throws before able to complete.
GeneralFailure = 1,
// Explicit bind to tunnel was successful.
BindUnaffected = 2,
// Explicit bind to tunnel was redirected to LAN interface.
BindRedirected = 3
};
bool TestCaseSt7(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Launching split tunnel test case 7" << std::endl;
std::wcout << L"Evaluate whether existing child processes become excluded with their parent" << std::endl;
std::wcout << L"===" << std::endl;
ArgumentContext argsContext(arguments);
argsContext.ensureExactArgumentCount(0);
PromptActivateVpn();
//
// The child process needs to wait for an event to become signalled.
// So it makes the connection attempt at the right moment.
//
std::wcout << L"Creating synchronization events" << std::endl;
HANDLE readyEvent = CreateEventW(nullptr, TRUE, FALSE, ReadyEventName);
if (NULL == readyEvent || GetLastError() == ERROR_ALREADY_EXISTS)
{
THROW_ERROR("Could not create event object");
}
common::memory::ScopeDestructor sd;
sd += [readyEvent]
{
CloseHandle(readyEvent);
};
HANDLE commenceEvent = CreateEventW(nullptr, TRUE, FALSE, CommenceEventName);
if (NULL == commenceEvent || GetLastError() == ERROR_ALREADY_EXISTS)
{
THROW_ERROR("Could not create event object");
}
sd += [commenceEvent]
{
CloseHandle(commenceEvent);
};
std::wcout << L"Creating child process" << std::endl;
const auto childPath = ProcessBinaryCreateRandomCopy();
sd += [&childPath]
{
DeleteFileW(childPath.c_str());
};
auto childProcess = LaunchProcess
(
childPath,
{ L"st7-child", RuntimeSettings::GetSettingsFilePath() },
CREATE_NEW_CONSOLE
);
sd += [childProcess]
{
// This will fail if the child process was successful.
TerminateProcess(childProcess, 0x1337);
CloseHandle(childProcess);
};
std::wcout << L"Waiting for child process to become ready" << std::endl;
WaitForSingleObject(readyEvent, INFINITE);
PromptActivateSplitTunnel();
std::wcout << L"Commanding child process to make a connection" << std::endl;
SetEvent(commenceEvent);
std::wcout << L"Waiting for child process to finish" << std::endl;
WaitForSingleObject(childProcess, INFINITE);
DWORD exitCode;
auto status = GetExitCodeProcess(childProcess, &exitCode);
if (FALSE == status)
{
THROW_ERROR("Could not determine child process exit code");
}
switch ((ChildStatus)exitCode)
{
case ChildStatus::BindUnaffected:
{
std::wcout << L"Socket binds in child process are NOT redirected" << std::endl;
return false;
}
case ChildStatus::BindRedirected:
{
std::wcout << L"Socket binds in child process are being redirected" << std::endl;
return true;
}
};
std::wcout << L"Unexpected child process exit code" << std::endl;
return false;
}
bool TestCaseSt7Child(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Launching split tunnel test case 7 - CHILD" << std::endl;
std::wcout << L"===" << std::endl;
SetPauseBeforeExit(true);
ArgumentContext argsContext(arguments);
auto settingsFilePath = argsContext.next();
RuntimeSettings::OverrideSettingsFilePath(settingsFilePath);
argsContext.assertExhausted();
std::wcout << L"Opening event objects" << std::endl;
constexpr DWORD AccessRights = STANDARD_RIGHTS_READ | SYNCHRONIZE | EVENT_MODIFY_STATE;
auto readyEvent = OpenEventW(AccessRights, FALSE, ReadyEventName);
if (NULL == readyEvent)
{
THROW_ERROR("Could not open event object");
}
common::memory::ScopeDestructor sd;
sd += [readyEvent]
{
CloseHandle(readyEvent);
};
auto commenceEvent = OpenEventW(AccessRights, FALSE, CommenceEventName);
if (NULL == commenceEvent)
{
THROW_ERROR("Could not open event object");
}
sd += [commenceEvent]
{
CloseHandle(commenceEvent);
};
std::wcout << L"Signalling to parent that child is ready" << std::endl;
SetEvent(readyEvent);
std::wcout << L"Waiting for parent" << std::endl;
WaitForSingleObject(commenceEvent, INFINITE);
std::wcout << L"Creating socket and binding to tunnel interface" << std::endl;
auto socket = CreateBindSocket(RuntimeSettings::Instance().tunnelIp());
sd += [&socket]
{
ShutdownSocket(socket);
};
std::wcout << L"Connecting to tcpbin echo service" << std::endl;
ConnectSocket
(
socket,
RuntimeSettings::Instance().tcpbinServerIp(),
RuntimeSettings::Instance().tcpbinEchoPort()
);
std::wcout << L"Communicating with echo service to establish connectivity" << std::endl;
SendRecvValidateEcho(socket, { 'h', 'e', 'y', 'n', 'o', 'w' });
std::wcout << L"Querying bind to determine which interface is used" << std::endl;
const auto actualBind = QueryBind(socket);
if (actualBind.sin_addr == RuntimeSettings::Instance().tunnelIp())
{
std::wcout << L"Bound to tunnel interface" << std::endl;
SetProcessExitCode(static_cast<int>(ChildStatus::BindUnaffected));
return true;
}
else if (actualBind.sin_addr == RuntimeSettings::Instance().lanIp())
{
std::wcout << L"Bound to LAN interface" << std::endl;
SetProcessExitCode(static_cast<int>(ChildStatus::BindRedirected));
return true;
}
std::wcout << L"Failed to match bind to known interface" << std::endl;
return false;
}
| 5,866
|
C++
|
.cpp
| 172
| 31.569767
| 107
| 0.739409
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,021
|
st3.cpp
|
mullvad_win-split-tunnel/leaktest/split-tunnel/st3.cpp
|
#include "st3.h"
#include <iostream>
#include <ws2tcpip.h>
#include "../util.h"
#include "../runtimesettings.h"
#include "../sockutil.h"
#include <libcommon/memory.h>
constexpr auto SocketRecvTimeoutValue = std::chrono::milliseconds(2000);
bool TestCaseSt3(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Launching split tunnel test case 3" << std::endl;
std::wcout << L"Evaluate whether excluded connections are blocked when an app stops being excluded" << std::endl;
std::wcout << L"===" << std::endl;
ArgumentContext argsContext(arguments);
const auto tcp = ProtoArgumentTcp(argsContext.nextOrDefault(L"tcp"));
argsContext.assertExhausted();
PromptActivateVpnSplitTunnel();
std::wcout << "Creating socket and leaving it unbound" << std::endl;
auto lanSocket = CreateSocket(tcp);
common::memory::ScopeDestructor sd;
sd += [&lanSocket]
{
ShutdownSocket(lanSocket);
};
if (!tcp)
{
SetSocketRecvTimeout(lanSocket, SocketRecvTimeoutValue);
}
std::wcout << L"Connecting to tcpbin server" << std::endl;
//
// Connecting will select the tunnel interface because of best metric,
// but exclusion logic should redirect the bind.
//
ConnectSocket
(
lanSocket,
RuntimeSettings::Instance().tcpbinServerIp(),
tcp ? RuntimeSettings::Instance().tcpbinEchoPort() : RuntimeSettings::Instance().tcpbinEchoPortUdp()
);
std::wcout << L"Communicating with echo service to establish connectivity" << std::endl;
SendRecvValidateEcho(lanSocket, { 'h', 'e', 'y', 'n', 'o', 'w' });
std::wcout << L"Querying bind to verify correct interface is used" << std::endl;
ValidateBind(lanSocket, RuntimeSettings::Instance().lanIp());
PromptDisableSplitTunnel();
std::wcout << L"Sending and receiving to validate blocking policies" << std::endl;
try
{
SendRecvValidateEcho(lanSocket, { 'b', 'l', 'o', 'c', 'k', 'e', 'd' });
}
catch (const std::exception &err)
{
std::cout << "Sending and receiving failed with message: " << err.what() << std::endl;
std::wcout << L"Assuming firewall filters are blocking comms" << std::endl;
return true;
}
std::wcout << L"Traffic leak!" << std::endl;
return false;
}
| 2,161
|
C++
|
.cpp
| 58
| 34.87931
| 114
| 0.723425
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,022
|
gen1.cpp
|
mullvad_win-split-tunnel/leaktest/general/gen1.cpp
|
#include "gen1.h"
#include "../util.h"
#include "../sockutil.h"
#include "../runtimesettings.h"
#include <libcommon/memory.h>
#include <libcommon/error.h>
#include <iostream>
namespace
{
std::vector<uint8_t> GenerateEchoBuffer()
{
return { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
}
void LoopSendReceive(SOCKET lanSocket, size_t delay)
{
WinsockOverlapped *sendContext;
WinsockOverlapped *recvContext;
common::memory::ScopeDestructor sd;
sd += [&lanSocket, &sendContext, &recvContext]
{
//
// This has to happen first so pending operations are cancelled.
//
ShutdownSocket(lanSocket);
DeleteWinsockOverlapped(&sendContext);
DeleteWinsockOverlapped(&recvContext);
};
sendContext = AllocateWinsockOverlapped();
recvContext = AllocateWinsockOverlapped();
for (;;)
{
if (!sendContext->pendingOperation)
{
AssignOverlappedBuffer(*sendContext, GenerateEchoBuffer());
SendOverlappedSocket(lanSocket, *sendContext);
}
if (!recvContext->pendingOperation)
{
RecvOverlappedSocket(lanSocket, *recvContext, 1024);
}
Sleep(static_cast<DWORD>(delay));
//
// Check if overlapped ops have completed.
//
const bool sendCompleted = PollOverlappedSend(lanSocket, *sendContext);
const bool recvCompleted = PollOverlappedRecv(lanSocket, *recvContext);
if (sendCompleted)
{
if (recvCompleted)
{
std::wcout << L'+';
}
else
{
std::wcout << L's';
}
}
else if (recvCompleted)
{
std::wcout << L'r';
}
}
}
SOCKET CreateConnectSocket(bool tcp, bool verbose)
{
if (verbose)
{
std::wcout << L"Creating socket and binding to LAN interface" << std::endl;
}
auto lanSocket = CreateBindOverlappedSocket(RuntimeSettings::Instance().lanIp(), 0, tcp);
try
{
if (verbose)
{
std::wcout << L"Connecting to tcpbin echo service" << std::endl;
}
ConnectSocket
(
lanSocket,
RuntimeSettings::Instance().tcpbinServerIp(),
tcp ? RuntimeSettings::Instance().tcpbinEchoPort() : RuntimeSettings::Instance().tcpbinEchoPortUdp()
);
}
catch (...)
{
ShutdownSocket(lanSocket);
throw;
}
return lanSocket;
}
template<typename T>
T take(T &lhs, T rhs)
{
T temp = lhs;
lhs = rhs;
return temp;
}
} // anonymous namespace
//
// Disable `warning C4702: unreachable code`
// The function mostly doesn't return.
//
#pragma warning(push)
#pragma warning(disable:4702)
bool TestCaseGen1(const std::vector<std::wstring> &arguments)
{
std::wcout << L"Launching general test case 1" << std::endl;
std::wcout << L"Evaluate whether VPN client state changes have momentary leaks" << std::endl;
std::wcout << L"===" << std::endl;
ArgumentContext argsContext(arguments);
const auto tcp = ProtoArgumentTcp(argsContext.nextOrDefault(L"tcp"));
const auto delay = common::string::LexicalCast<size_t>(argsContext.nextOrDefault(L"50"));
argsContext.assertExhausted();
auto lanSocket = CreateConnectSocket(tcp, true);
PromptActivateVpn();
std::wcout << L"You should interact with the VPN app to cause state changes" << std::endl;
std::wcout << L"'s' is successfully sent data" << std::endl;
std::wcout << L"'r' is successfully received data" << std::endl;
std::wcout << L"'+' is a successful send+receive" << std::endl;
std::wcout << L"'.' is a broken socket that's being reconnected" << std::endl;
bool brokenSocket = false;
for (;;)
{
try
{
if (brokenSocket)
{
Sleep(static_cast<DWORD>(delay));
lanSocket = CreateConnectSocket(tcp, false);
brokenSocket = false;
}
//
// NOTE: Ownership of `lanSocket` is passed to LoopSendReceive().
// The socket will already be closed if the function ever returns.
//
LoopSendReceive(take<>(lanSocket, SOCKET(INVALID_SOCKET)), delay);
}
catch (const common::error::WindowsException &err)
{
if (brokenSocket)
{
std::wcout << L'.';
continue;
}
if (err.errorCode() == WSAECONNRESET
|| err.errorCode() == WSAECONNABORTED)
{
std::wcout << L'.';
brokenSocket = true;
continue;
}
throw;
}
}
return false;
}
#pragma warning(pop)
| 4,081
|
C++
|
.cpp
| 157
| 23.10828
| 103
| 0.708473
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,023
|
proc.cpp
|
mullvad_win-split-tunnel/testing/proc.cpp
|
#include <vector>
#include <iterator>
#include <cstdint>
#include <windows.h>
#include <tlhelp32.h>
#include <libcommon/error.h>
#include <libcommon/memory.h>
#include <map>
#include "../src/public.h"
#define PSAPI_VERSION 2
#include <psapi.h>
#include "proc.h"
using common::memory::UniqueHandle;
struct ProcessInfo
{
DWORD ProcessId;
DWORD ParentProcessId;
FILETIME CreationTime;
std::wstring DevicePath;
};
FILETIME GetProcessCreationTime(HANDLE processHandle)
{
FILETIME creationTime, dummy;
const auto status = GetProcessTimes(processHandle, &creationTime, &dummy, &dummy, &dummy);
if (FALSE == status)
{
THROW_WINDOWS_ERROR(GetLastError(), "GetProcessTimes");
}
return creationTime;
}
std::wstring GetProcessDevicePath(HANDLE processHandle)
{
size_t bufferSize = 512;
std::vector<wchar_t> buffer;
for (;;)
{
buffer.resize(bufferSize);
const auto charsWritten = K32GetProcessImageFileNameW(processHandle,
&buffer[0], static_cast<DWORD>(buffer.size()));
if (0 == charsWritten)
{
if (ERROR_INSUFFICIENT_BUFFER == GetLastError())
{
bufferSize *= 2;
continue;
}
THROW_WINDOWS_ERROR(GetLastError(), "K32GetProcessImageFileNameW");
}
//
// K32GetProcessImageFileNameW writes a null terminator
// but doesn't account for it in the return value.
//
return std::wstring(&buffer[0], &buffer[0] + charsWritten);
}
}
//
// CompileProcessInfo()
//
// Returns a set including all processes in the system.
//
// The return value uses the vector container type since it's perceived
// the set will not be searched.
//
std::vector<ProcessInfo> CompileProcessInfo()
{
auto snapshot = UniqueHandle(new HANDLE(
(HANDLE)CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)));
if (INVALID_HANDLE_VALUE == *snapshot)
{
THROW_WINDOWS_ERROR(GetLastError(), "Snapshot processes");
}
PROCESSENTRY32W processEntry { .dwSize = sizeof(PROCESSENTRY32W) };
if (FALSE == Process32First(*snapshot, &processEntry))
{
THROW_WINDOWS_ERROR(GetLastError(), "Initiate process enumeration");
}
std::map<DWORD, ProcessInfo> processes;
//
// Discover all processes.
//
do
{
auto handle = UniqueHandle(new HANDLE(OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processEntry.th32ProcessID)));
if (NULL == *handle)
{
//THROW_WINDOWS_ERROR(GetLastError(), "Open process");
continue;
}
ProcessInfo pi;
pi.ProcessId = processEntry.th32ProcessID;
pi.ParentProcessId = processEntry.th32ParentProcessID;
try
{
pi.CreationTime = GetProcessCreationTime(*handle);
}
catch (...)
{
pi.CreationTime = { 0 };
}
try
{
pi.DevicePath = GetProcessDevicePath(*handle);
}
catch (...)
{
//
// Including a process without a path might seem useless.
// But it enables ancestor discovery.
//
pi.DevicePath = L"";
}
processes.insert(std::make_pair(pi.ProcessId, pi));
}
while (FALSE != Process32NextW(*snapshot, &processEntry));
//
// Find instances of PID recycling.
//
// This can be done by checking the creation time of the parent
// process and discovering that the age of the claimed parent process
// is lower than that of the child process.
//
for (auto& [pid, process] : processes)
{
auto parentIter = processes.find(process.ParentProcessId);
if (parentIter != processes.end())
{
ULARGE_INTEGER parentTime { .LowPart = parentIter->second.CreationTime.dwLowDateTime,
.HighPart = parentIter->second.CreationTime.dwHighDateTime };
ULARGE_INTEGER processTime { .LowPart = process.CreationTime.dwLowDateTime,
.HighPart = process.CreationTime.dwHighDateTime };
if (0 != parentTime.QuadPart
&& parentTime.QuadPart < processTime.QuadPart)
{
continue;
}
}
process.ParentProcessId = 0;
}
//
// Store process records into vector.
//
std::vector<ProcessInfo> output;
output.reserve(processes.size());
std::transform(processes.begin(), processes.end(), std::back_inserter(output),
[](const std::map<DWORD, ProcessInfo>::value_type &entry)
{
return entry.second;
});
return output;
}
//
// MakeHandle()
//
// For some reason a PID is of type HANDLE in the kernel.
// Casting to HANDLE, which is a pointer type, requires some sourcery.
//
HANDLE MakeHandle(DWORD h)
{
return reinterpret_cast<HANDLE>(static_cast<size_t>(h));
}
std::vector<uint8_t> PackageProcessInfo(const std::vector<ProcessInfo> &processes)
{
if (processes.empty())
{
THROW_ERROR("Invalid set of processes (empty set)");
}
//
// Determine required byte length for string buffer.
//
size_t stringBufferLength = 0;
for (const auto &process : processes)
{
stringBufferLength += (process.DevicePath.size() * sizeof(wchar_t));
}
size_t bufferLength = sizeof(ST_PROCESS_DISCOVERY_HEADER)
+ (sizeof(ST_PROCESS_DISCOVERY_ENTRY) * processes.size())
+ stringBufferLength;
std::vector<uint8_t> buffer(bufferLength);
//
// Create pointers to various buffer areas.
//
auto header = reinterpret_cast<ST_PROCESS_DISCOVERY_HEADER*>(&buffer[0]);
auto entry = reinterpret_cast<ST_PROCESS_DISCOVERY_ENTRY*>(header + 1);
auto stringBuffer = reinterpret_cast<uint8_t *>(entry + processes.size());
//
// Serialize into buffer.
//
SIZE_T stringOffset = 0;
for (const auto &process : processes)
{
entry->ProcessId = MakeHandle(process.ProcessId);
entry->ParentProcessId = MakeHandle(process.ParentProcessId);
if (process.DevicePath.empty())
{
entry->ImageNameOffset = 0;
entry->ImageNameLength = 0;
}
else
{
const auto imageNameLength = process.DevicePath.size() * sizeof(wchar_t);
entry->ImageNameOffset = stringOffset;
entry->ImageNameLength = static_cast<USHORT>(imageNameLength);
RtlCopyMemory(stringBuffer + stringOffset, &process.DevicePath[0], imageNameLength);
stringOffset += imageNameLength;
}
++entry;
}
//
// Finalize header.
//
header->NumEntries = processes.size();
header->TotalLength = bufferLength;
return buffer;
}
std::vector<uint8_t> BuildRegisterProcessesPayload()
{
return PackageProcessInfo(CompileProcessInfo());
}
| 6,079
|
C++
|
.cpp
| 219
| 25.09589
| 91
| 0.736116
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,024
|
stconsole.cpp
|
mullvad_win-split-tunnel/testing/stconsole.cpp
|
#include <libcommon/network/adapters.h>
#include <libcommon/string.h>
#include <libcommon/error.h>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <windows.h>
#include <conio.h>
#include <ip2string.h>
#include <winternl.h>
#include <ws2ipdef.h>
#include <process.h>
#include "proc.h"
#include "../src/public.h"
#pragma comment(lib, "iphlpapi.lib")
static const wchar_t DriverSymbolicName[] = L"\\\\.\\MULLVADSPLITTUNNEL";
HANDLE g_DriverHandle = INVALID_HANDLE_VALUE;
std::vector<std::wstring> g_imagenames;
bool g_DisplayEvents = false;
bool SendIoControl(DWORD code, void *inBuffer, DWORD inBufferSize,
void *outBuffer, DWORD outBufferSize, DWORD *bytesReturned)
{
OVERLAPPED o = { 0 };
//
// Event should not be created on-the-fly.
//
// Create an event for each thread that needs to send a request
// and keep the event around.
//
o.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
auto status = DeviceIoControl(g_DriverHandle, code,
inBuffer, inBufferSize, outBuffer, outBufferSize, bytesReturned, &o);
if (FALSE != status)
{
CloseHandle(o.hEvent);
return true;
}
if (ERROR_IO_PENDING != GetLastError())
{
//THROW_ERROR("Could not post request to driver");
CloseHandle(o.hEvent);
return false;
}
DWORD tempBytesReturned = 0;
status = GetOverlappedResult(g_DriverHandle, &o, &tempBytesReturned, TRUE);
CloseHandle(o.hEvent);
if (FALSE == status)
{
//THROW_ERROR("Failed to wait on driver to complete request");
return false;
}
*bytesReturned = tempBytesReturned;
return true;
}
ST_DRIVER_STATE GetDriverState()
{
if (INVALID_HANDLE_VALUE == g_DriverHandle)
{
THROW_ERROR("Not connected to driver");
}
DWORD bytesReturned;
SIZE_T buffer;
auto status = SendIoControl((DWORD)IOCTL_ST_GET_STATE, nullptr, 0, &buffer, sizeof(buffer), &bytesReturned);
if (!status)
{
THROW_ERROR("Failed to request state info from driver");
}
return static_cast<ST_DRIVER_STATE>(buffer);
}
std::wstring MapDriverState(ST_DRIVER_STATE state)
{
switch (state)
{
case ST_DRIVER_STATE_STARTED: return L"ST_DRIVER_STATE_STARTED";
case ST_DRIVER_STATE_INITIALIZED: return L"ST_DRIVER_STATE_INITIALIZED";
case ST_DRIVER_STATE_READY: return L"ST_DRIVER_STATE_READY";
case ST_DRIVER_STATE_ENGAGED: return L"ST_DRIVER_STATE_ENGAGED";
case ST_DRIVER_STATE_ZOMBIE: return L"ST_DRIVER_STATE_ZOMBIE";
default:
{
THROW_ERROR("Unknown driver state");
}
}
}
void ProcessConnect()
{
g_DriverHandle = CreateFileW(DriverSymbolicName, GENERIC_READ | GENERIC_WRITE,
0, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
if (INVALID_HANDLE_VALUE == g_DriverHandle)
{
THROW_WINDOWS_ERROR(GetLastError(), "Connect to driver");
}
std::wcout << L"Driver state: " << MapDriverState(GetDriverState()) << std::endl;
std::wcout << L"Successfully connected to driver" << std::endl;
}
void ProcessInitialize()
{
DWORD bytesReturned;
auto status = SendIoControl((DWORD)IOCTL_ST_INITIALIZE, nullptr, 0, nullptr, 0, &bytesReturned);
if (!status)
{
THROW_ERROR("Initialization command failed");
}
std::wcout << L"Driver state: " << MapDriverState(GetDriverState()) << std::endl;
std::wcout << L"Successfully initialized driver" << std::endl;
}
std::vector<uint8_t> MakeConfiguration(const std::vector<std::wstring> &imageNames)
{
size_t totalStringLength = 0;
for (const auto &imageName : imageNames)
{
totalStringLength += imageName.size() * sizeof(wchar_t);
}
size_t totalBufferSize = sizeof(ST_CONFIGURATION_HEADER)
+ (sizeof(ST_CONFIGURATION_ENTRY) * imageNames.size())
+ totalStringLength;
std::vector<uint8_t> buffer(totalBufferSize);
auto header = (ST_CONFIGURATION_HEADER*)&buffer[0];
auto entry = (ST_CONFIGURATION_ENTRY*)(header + 1);
auto stringDest = &buffer[0] + sizeof(ST_CONFIGURATION_HEADER)
+ (sizeof(ST_CONFIGURATION_ENTRY) * imageNames.size());
SIZE_T stringOffset = 0;
for (const auto &imageName : imageNames)
{
auto stringLength = imageName.size() * sizeof(wchar_t);
entry->ImageNameLength = (USHORT)stringLength;
entry->ImageNameOffset = stringOffset;
memcpy(stringDest, imageName.c_str(), stringLength);
++entry;
stringDest += stringLength;
stringOffset += stringLength;
}
header->NumEntries = imageNames.size();
header->TotalLength = totalBufferSize;
return buffer;
}
void ProcessSetConfig(const std::vector<std::wstring> &imageNames)
{
if (INVALID_HANDLE_VALUE == g_DriverHandle)
{
THROW_ERROR("Not connected to driver");
}
std::wcout << L"Sending the following config to driver:" << std::endl;
for (const auto &imagename : imageNames)
{
std::wcout << L" " << imagename << std::endl;
}
auto blob = MakeConfiguration(imageNames);
DWORD bytesReturned;
auto status = SendIoControl((DWORD)IOCTL_ST_SET_CONFIGURATION,
&blob[0], (DWORD)blob.size(), nullptr, 0, &bytesReturned);
if (!status)
{
THROW_ERROR("Set configuration");
}
std::wcout << L"Driver state: " << MapDriverState(GetDriverState()) << std::endl;
std::wcout << L"Successfully set configuration" << std::endl;
}
void ProcessAddConfig(const std::wstring &imageName)
{
auto tempNames = g_imagenames;
tempNames.push_back(imageName);
ProcessSetConfig(tempNames);
// Persist data now that the above call did not throw.
g_imagenames = tempNames;
}
void ProcessClearConfig();
void ProcessRemoveConfig(const std::wstring &imageName)
{
auto iterMatch = std::find_if(g_imagenames.begin(), g_imagenames.end(), [&imageName](const std::wstring &candidate)
{
return 0 == _wcsicmp(candidate.c_str(), imageName.c_str());
});
if (iterMatch == g_imagenames.end())
{
THROW_ERROR("Specified imagename was not previously registered");
}
auto indexMatch = std::distance(g_imagenames.begin(), iterMatch);
auto tempNames = g_imagenames;
tempNames.erase(tempNames.begin() + indexMatch);
if (tempNames.empty())
{
ProcessClearConfig();
return;
}
ProcessSetConfig(tempNames);
// Persist data now that the above call did not throw.
g_imagenames = tempNames;
}
void ProcessGetConfig()
{
if (INVALID_HANDLE_VALUE == g_DriverHandle)
{
THROW_ERROR("Not connected to driver");
}
DWORD bytesReturned;
SIZE_T requiredBufferSize;
auto status = SendIoControl((DWORD)IOCTL_ST_GET_CONFIGURATION,
nullptr, 0, &requiredBufferSize, sizeof(requiredBufferSize), &bytesReturned);
if (!status || 0 == bytesReturned)
{
THROW_ERROR("Get configuration");
}
std::vector<uint8_t> buffer(requiredBufferSize, 0);
status = SendIoControl((DWORD)IOCTL_ST_GET_CONFIGURATION,
nullptr, 0, &buffer[0], (DWORD)buffer.size(), &bytesReturned);
if (!status || bytesReturned != buffer.size())
{
THROW_ERROR("Get configuration");
}
auto header = (ST_CONFIGURATION_HEADER*)&buffer[0];
auto entry = (ST_CONFIGURATION_ENTRY*)(header + 1);
auto stringBuffer = (uint8_t *)(entry + header->NumEntries);
std::vector<std::wstring> imageNames;
for (auto i = 0; i < header->NumEntries; ++i, ++entry)
{
imageNames.emplace_back
(
(wchar_t*)(stringBuffer + entry->ImageNameOffset),
(wchar_t*)(stringBuffer + entry->ImageNameOffset + entry->ImageNameLength)
);
}
std::wcout << L"Successfully got configuration" << std::endl;
std::wcout << L"Image names in config:" << std::endl;
for (const auto &imageName : imageNames)
{
std::wcout << L" " << imageName << std::endl;
}
}
void ProcessClearConfig()
{
if (INVALID_HANDLE_VALUE == g_DriverHandle)
{
THROW_ERROR("Not connected to driver");
}
DWORD bytesReturned;
auto status = SendIoControl((DWORD)IOCTL_ST_CLEAR_CONFIGURATION,
nullptr, 0, nullptr, 0, &bytesReturned);
if (!status)
{
THROW_ERROR("Clear configuration");
}
g_imagenames.clear();
std::wcout << L"Driver state: " << MapDriverState(GetDriverState()) << std::endl;
std::wcout << L"Successfully cleared configuration" << std::endl;
}
void ProcessRegisterProcesses()
{
if (INVALID_HANDLE_VALUE == g_DriverHandle)
{
THROW_ERROR("Not connected to driver");
}
auto blob = BuildRegisterProcessesPayload();
DWORD bytesReturned;
auto status = SendIoControl((DWORD)IOCTL_ST_REGISTER_PROCESSES,
&blob[0], (DWORD)blob.size(), nullptr, 0, &bytesReturned);
if (!status)
{
THROW_ERROR("Register processes");
}
std::wcout << L"Driver state: " << MapDriverState(GetDriverState()) << std::endl;
std::wcout << L"Successfully registered processes" << std::endl;
}
void GetAdapterAddresses(const std::wstring &adapterName, IN_ADDR &ipv4, IN6_ADDR &ipv6)
{
const DWORD flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER;
common::network::Adapters adapters(AF_INET, flags);
bool ipv4Done = false;
for (auto adapter = adapters.next(); adapter != NULL; adapter = adapters.next())
{
if (0 != _wcsicmp(adapter->FriendlyName, adapterName.c_str()))
{
continue;
}
if (adapter->Ipv4Enabled == 0
|| adapter->FirstUnicastAddress == nullptr)
{
break;
}
auto sa = (SOCKADDR_IN*)adapter->FirstUnicastAddress->Address.lpSockaddr;
ipv4 = sa->sin_addr;
ipv4Done = true;
break;
}
if (!ipv4Done)
{
throw std::runtime_error("Could not determine adapter IPv4 address");
}
common::network::Adapters adapters6(AF_INET6, flags);
bool ipv6Done = false;
for (auto adapter = adapters6.next(); adapter != NULL; adapter = adapters6.next())
{
if (0 != _wcsicmp(adapter->FriendlyName, adapterName.c_str()))
{
continue;
}
if (adapter->Ipv6Enabled == 0
|| adapter->FirstUnicastAddress == nullptr)
{
break;
}
auto sa = (SOCKADDR_IN6*)adapter->FirstUnicastAddress->Address.lpSockaddr;
ipv6 = sa->sin6_addr;
ipv6Done = true;
break;
}
if (!ipv6Done)
{
throw std::runtime_error("Could not determine adapter IPv6 address");
}
}
std::vector<uint8_t> BuildRegisterIpsPayload()
{
std::vector<uint8_t> payload(sizeof(ST_IP_ADDRESSES));
auto ip = reinterpret_cast<ST_IP_ADDRESSES*>(&payload[0]);
GetAdapterAddresses(L"Ethernet", ip->InternetIpv4, ip->InternetIpv6);
GetAdapterAddresses(L"Mullvad", ip->TunnelIpv4, ip->TunnelIpv6);
wchar_t stringBuffer[100];
std::wcout << L"Internet addresses" << std::endl;
RtlIpv4AddressToStringW(&(ip->InternetIpv4), stringBuffer);
std::wcout << L" Ipv4: " << stringBuffer << std::endl;
RtlIpv6AddressToStringW(&(ip->InternetIpv6), stringBuffer);
std::wcout << L" Ipv6: " << stringBuffer << std::endl;
std::wcout << L"Tunnel addresses" << std::endl;
RtlIpv4AddressToStringW(&(ip->TunnelIpv4), stringBuffer);
std::wcout << L" Ipv4: " << stringBuffer << std::endl;
RtlIpv6AddressToStringW(&(ip->TunnelIpv6), stringBuffer);
std::wcout << L" Ipv6: " << stringBuffer << std::endl;
//ip->InternetIpv4.S_un.S_addr = 0x0f02000a;
//ip->InternetIpv6.u.Byte[0] = 0;
//ip->TunnelIpv4.S_un.S_addr = 0x0c00080a;
//ip->TunnelIpv6.u.Byte[0] = 0;
return payload;
}
void ProcessRegisterIps()
{
if (INVALID_HANDLE_VALUE == g_DriverHandle)
{
THROW_ERROR("Not connected to driver");
}
auto blob = BuildRegisterIpsPayload();
DWORD bytesReturned;
auto status = SendIoControl((DWORD)IOCTL_ST_REGISTER_IP_ADDRESSES,
&blob[0], (DWORD)blob.size(), nullptr, 0, &bytesReturned);
if (!status)
{
THROW_ERROR("Register IP addresses");
}
std::wcout << L"Driver state: " << MapDriverState(GetDriverState()) << std::endl;
std::wcout << L"Successfully registered IP addresses" << std::endl;
}
void ProcessGetIps()
{
ST_IP_ADDRESSES ips = { 0 };
DWORD bytesReturned;
auto status = SendIoControl((DWORD)IOCTL_ST_GET_IP_ADDRESSES,
nullptr, 0, &ips, (DWORD)sizeof(ips), &bytesReturned);
if (!status || bytesReturned != sizeof(ips))
{
THROW_ERROR("Register IP addresses");
}
std::wcout << L"Internet IPv4: " << common::string::FormatIpv4(ips.InternetIpv4.S_un.S_addr) << std::endl;
std::wcout << L"Internet IPv6: " << common::string::FormatIpv6(ips.InternetIpv6.u.Byte) << std::endl;
std::wcout << L"Tunnel IPv4: " << common::string::FormatIpv4(ips.TunnelIpv4.S_un.S_addr) << std::endl;
std::wcout << L"Tunnel IPv6: " << common::string::FormatIpv6(ips.TunnelIpv6.u.Byte) << std::endl;
}
//
// This is duplicated from proc.cpp
//
HANDLE XxxMakeHandle(DWORD h)
{
return reinterpret_cast<HANDLE>(static_cast<size_t>(h));
}
DWORD MakeDword(HANDLE h)
{
return static_cast<DWORD>(reinterpret_cast<size_t>(h));
}
void ProcessQueryProcess(const std::wstring &processId)
{
ST_QUERY_PROCESS q = { 0 };
q.ProcessId = XxxMakeHandle(_wtoi(processId.c_str()));
std::vector<uint8_t> buffer(1024);
DWORD bytesReturned;
auto status = SendIoControl((DWORD)IOCTL_ST_QUERY_PROCESS,
&q, sizeof(q), &buffer[0], (DWORD)buffer.size(), &bytesReturned);
if (!status)
{
THROW_ERROR("Query process");
}
//
// Dump retrieved information.
//
buffer.push_back(0);
buffer.push_back(0);
auto r = (ST_QUERY_PROCESS_RESPONSE *)&buffer[0];
std::wcout << L"Process id: " << MakeDword(r->ProcessId) << std::endl;
std::wcout << L"Parent process id: " << MakeDword(r->ParentProcessId) << std::endl;
std::wcout << L"Split: " << r->Split << std::endl;
std::wcout << L"Imagename: " << r->ImageName << std::endl;
}
void ProcessDisplayEvents()
{
g_DisplayEvents = !g_DisplayEvents;
std::wcout << L"Displaying events: " << std::boolalpha << g_DisplayEvents << std::endl;
}
void DisplaySplittingEvent(const ST_SPLITTING_EVENT *evt, size_t /*eventSize*/)
{
std::wcout << L"Process id: " << MakeDword(evt->ProcessId) << std::endl;
std::wcout << L"Flags:" << std::endl;
if ((evt->Reason & ST_SPLITTING_REASON_BY_INHERITANCE) != 0)
{
std::wcout << L" ST_SPLITTING_REASON_BY_INHERITANCE" << std::endl;
}
if ((evt->Reason & ST_SPLITTING_REASON_BY_CONFIG) != 0)
{
std::wcout << L" ST_SPLITTING_REASON_BY_CONFIG" << std::endl;
}
if ((evt->Reason & ST_SPLITTING_REASON_PROCESS_ARRIVING) != 0)
{
std::wcout << L" ST_SPLITTING_REASON_PROCESS_ARRIVING" << std::endl;
}
if ((evt->Reason & ST_SPLITTING_REASON_PROCESS_DEPARTING) != 0)
{
std::wcout << L" ST_SPLITTING_REASON_PROCESS_DEPARTING" << std::endl;
}
std::wstring imageName(&evt->ImageName[0], &evt->ImageName[0] + (evt->ImageNameLength / sizeof(wchar_t)));
std::wcout << L"Imagename: " << imageName << std::endl;
}
void DisplaySplittingErrorEvent(const ST_SPLITTING_ERROR_EVENT *evt, size_t /*eventSize*/)
{
std::wcout << L"Process id: " << MakeDword(evt->ProcessId) << std::endl;
std::wstring imageName(&evt->ImageName[0], &evt->ImageName[0] + (evt->ImageNameLength / sizeof(wchar_t)));
std::wcout << L"Imagename: " << imageName << std::endl;
}
void DisplayErrorMessageEvent(const ST_ERROR_MESSAGE_EVENT *evt, size_t /*eventSize*/)
{
std::wstringstream ss;
ss << L"Status: 0x" << std::setw(8) << std::setfill(L'0') << std::hex << evt->Status;
std::wcout << ss.str() << std::endl;
std::wstring message(&evt->ErrorMessage[0], &evt->ErrorMessage[0] + (evt->ErrorMessageLength / sizeof(wchar_t)));
std::wcout << L"Error message: " << message << std::endl;
}
void ParseDisplayEvent(const uint8_t *evt, size_t eventSize)
{
if (!g_DisplayEvents)
{
return;
}
std::wcout << L"Event received, " << eventSize << " bytes" << std::endl;
auto header = (ST_EVENT_HEADER *)evt;
std::wcout << L"Payload size, " << header->EventSize << " bytes" << std::endl;
switch (header->EventId)
{
case ST_EVENT_ID_START_SPLITTING_PROCESS:
{
std::wcout << L"Type: ST_EVENT_START_SPLITTING_PROCESS" << std::endl;
DisplaySplittingEvent((ST_SPLITTING_EVENT*)&header->EventData[0], header->EventSize);
break;
}
case ST_EVENT_ID_STOP_SPLITTING_PROCESS:
{
std::wcout << L"Type: ST_EVENT_STOP_SPLITTING_PROCESS" << std::endl;
DisplaySplittingEvent((ST_SPLITTING_EVENT*)&header->EventData[0], header->EventSize);
break;
}
case ST_EVENT_ID_ERROR_START_SPLITTING_PROCESS:
{
std::wcout << L"Type: ST_EVENT_ERROR_START_SPLITTING_PROCESS" << std::endl;
DisplaySplittingErrorEvent((ST_SPLITTING_ERROR_EVENT*)&header->EventData[0], header->EventSize);
break;
}
case ST_EVENT_ID_ERROR_STOP_SPLITTING_PROCESS:
{
std::wcout << L"Type: ST_EVENT_ERROR_STOP_SPLITTING_PROCESS" << std::endl;
DisplaySplittingErrorEvent((ST_SPLITTING_ERROR_EVENT*)&header->EventData[0], header->EventSize);
break;
}
case ST_EVENT_ID_ERROR_MESSAGE:
{
std::wcout << L"Type: ST_EVENT_ID_ERROR_MESSAGE" << std::endl;
DisplayErrorMessageEvent((ST_ERROR_MESSAGE_EVENT*)&header->EventData[0], header->EventSize);
break;
}
default:
{
std::wcout << L"Unsupported event" << std::endl;
}
}
}
unsigned __stdcall EventThread(void * /*rawContext*/)
{
//
// Wait for connect
//
for (;;)
{
if (g_DriverHandle == INVALID_HANDLE_VALUE)
{
Sleep(1000);
continue;
}
break;
}
//
// Continously issue event requests
//
std::vector<uint8_t> buffer(2048);
for (;;)
{
DWORD bytesReturned;
auto status = SendIoControl((DWORD)IOCTL_ST_DEQUEUE_EVENT, nullptr, 0,
&buffer[0], static_cast<DWORD>(buffer.size()), &bytesReturned);
if (!status)
{
//std::wcout << L"Failed to dequeue event from driver" << std::endl;
Sleep(1000);
continue;
}
ParseDisplayEvent(&buffer[0], bytesReturned);
}
}
void ResetDriver()
{
DWORD bytesReturned;
auto status = SendIoControl((DWORD)IOCTL_ST_RESET,
nullptr, 0, nullptr, 0, &bytesReturned);
if (!status)
{
THROW_ERROR("Request to reset driver has failed");
}
std::wcout << L"Driver state: " << MapDriverState(GetDriverState()) << std::endl;
}
bool CreateEventThread()
{
auto t = _beginthreadex(nullptr, 0, EventThread, nullptr, 0, nullptr);
auto threadHandle = reinterpret_cast<HANDLE>(t);
if (0 == threadHandle)
{
return false;
}
CloseHandle(threadHandle);
return true;
}
int main()
{
std::wcout << L"Testing console for split tunnel driver" << std::endl;
if (!CreateEventThread())
{
std::wcout << L"Failed to create event thread" << std::endl;
return 1;
}
for (;;)
{
std::wcout << L"cmd> ";
std::wstring request;
std::getline(std::wcin, request);
auto tokens = common::string::Tokenize(request, L" ");
if (tokens.empty())
{
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"quit"))
{
break;
}
try
{
if (0 == _wcsicmp(tokens[0].c_str(), L"connect"))
{
ProcessConnect();
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"initialize"))
{
ProcessInitialize();
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"get-state"))
{
std::wcout << L"Driver state: " << MapDriverState(GetDriverState()) << std::endl;
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"add-config"))
{
//
// tokens[1] will be a partial path if the path contains spaces.
// reuse the source for "tokens" instead.
//
ProcessAddConfig(request.substr(sizeof("add-config")));
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"remove-config"))
{
ProcessRemoveConfig(request.substr(sizeof("remove-config")));
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"get-config"))
{
ProcessGetConfig();
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"clear-config"))
{
ProcessClearConfig();
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"register-processes"))
{
ProcessRegisterProcesses();
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"register-ips"))
{
ProcessRegisterIps();
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"get-ips"))
{
ProcessGetIps();
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"dry-run-ips"))
{
BuildRegisterIpsPayload();
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"query-process"))
{
ProcessQueryProcess(tokens[1]);
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"quick"))
{
if (g_DriverHandle != INVALID_HANDLE_VALUE)
{
std::wcout << L"Already initialized" << std::endl;
continue;
}
ProcessConnect();
ProcessInitialize();
ProcessRegisterProcesses();
ProcessRegisterIps();
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"display-events"))
{
ProcessDisplayEvents();
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"split-firefox"))
{
static bool split = false;
const auto targetSplit = !split;
std::wcout << L"Splitting firefox: " << std::boolalpha << targetSplit << std::endl;
const std::wstring path = L"\\Device\\HarddiskVolume2\\Program Files (x86)\\Mozilla Firefox\\firefox.exe";
if (targetSplit)
{
ProcessAddConfig(path);
}
else
{
ProcessRemoveConfig(path);
}
// Safe to update now since above calls did not throw.
split = targetSplit;
continue;
}
if (0 == _wcsicmp(tokens[0].c_str(), L"reset"))
{
ResetDriver();
continue;
}
}
catch (const std::exception &ex)
{
std::cout << "Error: " << ex.what() << std::endl;
continue;
}
std::wcout << L"invalid command" << std::endl;
}
if (g_DriverHandle != INVALID_HANDLE_VALUE)
{
CloseHandle(g_DriverHandle);
}
return 0;
}
| 21,107
|
C++
|
.cpp
| 688
| 27.78343
| 116
| 0.696406
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,025
|
driverentry.cpp
|
mullvad_win-split-tunnel/src/driverentry.cpp
|
#include "win64guard.h"
#include <ntddk.h>
#include <wdf.h>
#include <wdmsec.h>
#include <mstcpip.h>
#include "devicecontext.h"
#include "util.h"
#include "ioctl.h"
#include "firewall/firewall.h"
#include "defs/ioctl.h"
#include "eventing/eventing.h"
#include "trace.h"
#include "driverentry.tmh"
extern "C"
DRIVER_INITIALIZE DriverEntry;
extern "C" // Because alloc_text requires this.
NTSTATUS
StCreateDevice
(
IN WDFDRIVER WdfDriver
);
EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL StEvtIoDeviceControl;
EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL StEvtIoDeviceControlParallel;
EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL StEvtIoDeviceControlSerial;
EVT_WDF_DRIVER_UNLOAD StEvtDriverUnload;
#pragma alloc_text (INIT, DriverEntry)
#pragma alloc_text (INIT, StCreateDevice)
#define ST_DEVICE_SECURITY_DESCRIPTOR SDDL_DEVOBJ_SYS_ALL_ADM_ALL
#define ST_DEVICE_NAME_STRING L"\\Device\\MULLVADSPLITTUNNEL"
#define ST_SYMBOLIC_NAME_STRING L"\\Global??\\MULLVADSPLITTUNNEL"
namespace
{
//
// RaiseDispatchForwardRequest()
//
// Raise to DISPATCH level and forward to IO queue.
//
// As it turns out, WdfRequestForwardToIoQueue() will borrow the calling thread to service the
// queue whenever it determines this is more efficient.
//
// This becomes a problem if we're in our topmost IOCTL handler and are trying to forward the
// request so we can return and unblock the client.
//
// If the destination queue is configured to service requests at PASSIVE, we can raise to DISPATCH
// to prevent our thread from being borrowed :-)
//
NTSTATUS
RaiseDispatchForwardRequest
(
WDFREQUEST Request,
WDFQUEUE Queue
)
{
const auto oldIrql = KeRaiseIrqlToDpcLevel();
const auto status = WdfRequestForwardToIoQueue(Request, Queue);
KeLowerIrql(oldIrql);
return status;
}
//
// IoControlRequiresParallelProcessing()
//
// Evaluate whether `IoControlCode` uses inverted call.
//
bool
IoControlRequiresParallelProcessing
(
ULONG IoControlCode
)
{
return IoControlCode == IOCTL_ST_DEQUEUE_EVENT;
}
} // anonymous namespace
//
// DriverEntry
//
// Creates a single device with associated symbolic link.
// Does minimal initialization.
//
extern "C"
NTSTATUS
DriverEntry
(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
{
WPP_INIT_TRACING(DriverObject, RegistryPath);
DbgPrint("Loading Mullvad split tunnel driver\n");
ExInitializeDriverRuntime(DrvRtPoolNxOptIn);
//
// Create WDF driver object.
//
WDF_DRIVER_CONFIG config;
WDF_DRIVER_CONFIG_INIT(&config, WDF_NO_EVENT_CALLBACK);
config.DriverInitFlags |= WdfDriverInitNonPnpDriver;
config.EvtDriverUnload = StEvtDriverUnload;
config.DriverPoolTag = ST_POOL_TAG;
WDFDRIVER wdfDriver;
auto status = WdfDriverCreate
(
DriverObject,
RegistryPath,
WDF_NO_OBJECT_ATTRIBUTES,
&config,
&wdfDriver
);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfDriverCreate() failed 0x%X\n", status);
//
// StEvtDriverUnload() won't be called so we have to
// clean up WPP here instead.
//
WPP_CLEANUP(DriverObject);
return status;
}
//
// Create WDF device object.
//
status = StCreateDevice(wdfDriver);
if (!NT_SUCCESS(status))
{
DbgPrint("StCreateDevice() failed 0x%X\n", status);
return status;
}
//
// All set.
//
DbgPrint("Successfully loaded Mullvad split tunnel driver\n");
return STATUS_SUCCESS;
}
extern "C"
NTSTATUS
StCreateDevice
(
IN WDFDRIVER WdfDriver
)
{
DECLARE_CONST_UNICODE_STRING(deviceName, ST_DEVICE_NAME_STRING);
DECLARE_CONST_UNICODE_STRING(symbolicLinkName, ST_SYMBOLIC_NAME_STRING);
auto deviceInit = WdfControlDeviceInitAllocate
(
WdfDriver,
&ST_DEVICE_SECURITY_DESCRIPTOR
);
if (deviceInit == NULL)
{
DbgPrint("WdfControlDeviceInitAllocate() failed\n");
return STATUS_INSUFFICIENT_RESOURCES;
}
WdfDeviceInitSetExclusive(deviceInit, TRUE);
auto status = WdfDeviceInitAssignName(deviceInit, &deviceName);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfDeviceInitAssignName() failed 0x%X\n", status);
goto Cleanup;
}
//
// No need to call WdfDeviceInitSetIoType() that configures the I/O type for
// read and write requests.
//
// We're using IOCTL for everything, which have the I/O type encoded.
//
// ---
//
// No need to call WdfControlDeviceInitSetShutdownNotification() because
// we don't care about the system being shut down.
//
// ---
//
// No need to call WdfDeviceInitSetFileObjectConfig() because we're not
// interested in receiving events when device handles are created/destroyed.
//
// --
//
// No need to call WdfDeviceInitSetIoInCallerContextCallback() because
// we're not using METHOD_NEITHER for any buffers.
//
WDF_OBJECT_ATTRIBUTES attributes;
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE
(
&attributes,
ST_DEVICE_CONTEXT
);
WDFDEVICE wdfDevice;
status = WdfDeviceCreate
(
&deviceInit,
&attributes,
&wdfDevice
);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfDeviceCreate() failed 0x%X\n", status);
goto Cleanup;
}
status = WdfDeviceCreateSymbolicLink
(
wdfDevice,
&symbolicLinkName
);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfDeviceCreateSymbolicLink() failed 0x%X\n", status);
goto Cleanup;
}
//
// Create a default request queue.
// Only register to handle IOCTL requests.
// Use WdfIoQueueDispatchParallel to enable inverted call.
//
WDF_IO_QUEUE_CONFIG queueConfig;
WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE
(
&queueConfig,
WdfIoQueueDispatchParallel
);
queueConfig.EvtIoDeviceControl = StEvtIoDeviceControl;
queueConfig.PowerManaged = WdfFalse;
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ExecutionLevel = WdfExecutionLevelPassive;
status = WdfIoQueueCreate
(
wdfDevice,
&queueConfig,
&attributes,
WDF_NO_HANDLE
);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfIoQueueCreate() for default queue failed 0x%X\n", status);
goto Cleanup;
}
//
// Create a secondary queue which is also using parallel dispatching.
// This enables us to forward incoming requests and return before processing completes.
//
WDF_IO_QUEUE_CONFIG_INIT
(
&queueConfig,
WdfIoQueueDispatchParallel
);
queueConfig.EvtIoDeviceControl = StEvtIoDeviceControlParallel;
queueConfig.PowerManaged = WdfFalse;
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ExecutionLevel = WdfExecutionLevelPassive;
WDFQUEUE parallelQueue;
status = WdfIoQueueCreate
(
wdfDevice,
&queueConfig,
&attributes,
¶llelQueue
);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfIoQueueCreate() for parallel queue failed 0x%X\n", status);
goto Cleanup;
}
//
// Create a third queue that uses serialized dispatching.
// Commands that need to be serialized can then be forwarded to this queue.
//
WDF_IO_QUEUE_CONFIG_INIT
(
&queueConfig,
WdfIoQueueDispatchSequential
);
queueConfig.EvtIoDeviceControl = StEvtIoDeviceControlSerial;
queueConfig.PowerManaged = WdfFalse;
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ExecutionLevel = WdfExecutionLevelPassive;
WDFQUEUE serialQueue;
status = WdfIoQueueCreate
(
wdfDevice,
&queueConfig,
&attributes,
&serialQueue
);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfIoQueueCreate() for serialized queue failed 0x%X\n", status);
goto Cleanup;
}
//
// Initialize context.
//
auto context = DeviceGetSplitTunnelContext(wdfDevice);
RtlZeroMemory(context, sizeof(*context));
status = WdfWaitLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &context->DriverState.Lock);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfWaitLockCreate() failed 0x%X\n", status);
goto Cleanup;
}
context->DriverState.State = ST_DRIVER_STATE_STARTED;
context->ParallelRequestQueue = parallelQueue;
context->SerializedRequestQueue = serialQueue;
WdfControlFinishInitializing(wdfDevice);
status = STATUS_SUCCESS;
Cleanup:
if (deviceInit != NULL)
{
WdfDeviceInitFree(deviceInit);
}
return status;
}
VOID
StEvtIoDeviceControl
(
WDFQUEUE Queue,
WDFREQUEST Request,
size_t OutputBufferLength,
size_t InputBufferLength,
ULONG IoControlCode
)
{
UNREFERENCED_PARAMETER(OutputBufferLength);
UNREFERENCED_PARAMETER(InputBufferLength);
auto device = WdfIoQueueGetDevice(Queue);
auto context = DeviceGetSplitTunnelContext(device);
//
// Querying the current driver state is always a valid operation, regardless of state.
// This is safe to service inline because it doesn't acquire any locks.
//
if (IoControlCode == IOCTL_ST_GET_STATE)
{
ioctl::GetStateComplete(device, Request);
return;
}
//
// Select which queue the request is forwarded to.
//
auto targetQueue = IoControlRequiresParallelProcessing(IoControlCode)
? context->ParallelRequestQueue
: context->SerializedRequestQueue;
const auto status = RaiseDispatchForwardRequest(Request, targetQueue);
if (NT_SUCCESS(status))
{
return;
}
DbgPrint("Failed to forward request to secondary IOCTL queue\n");
WdfRequestComplete(Request, status);
}
bool
StEvtIoDeviceControlParallelInner
(
WDFREQUEST Request,
ULONG IoControlCode,
ST_DEVICE_CONTEXT *Context
)
{
switch (IoControlCode)
{
case IOCTL_ST_DEQUEUE_EVENT:
{
//
// TODO: This approach is slightly broken.
//
// CollectOne() may enqueue the request in anticipation of an event arriving.
// That means the request completion may come at a later time when the asserted
// driver state has changed.
//
// But this probably doesn't matter.
//
if (Context->DriverState.State >= ST_DRIVER_STATE_INITIALIZED
&& Context->DriverState.State <= ST_DRIVER_STATE_ENGAGED)
{
eventing::CollectOne(Context->Eventing, Request);
return true;
}
break;
}
};
return false;
}
VOID
StEvtIoDeviceControlParallel
(
WDFQUEUE Queue,
WDFREQUEST Request,
size_t OutputBufferLength,
size_t InputBufferLength,
ULONG IoControlCode
)
{
UNREFERENCED_PARAMETER(OutputBufferLength);
UNREFERENCED_PARAMETER(InputBufferLength);
auto device = WdfIoQueueGetDevice(Queue);
auto context = DeviceGetSplitTunnelContext(device);
//
// Keep state lock acquired for the duration of processing.
// This prevents serialized IOCTL handlers from transitioning the state.
//
WdfWaitLockAcquire(context->DriverState.Lock, NULL);
bool servicedRequest = StEvtIoDeviceControlParallelInner(Request, IoControlCode, context);
WdfWaitLockRelease(context->DriverState.Lock);
if (servicedRequest)
{
return;
}
DbgPrint("Invalid IOCTL or not valid for current driver state\n");
WdfRequestComplete(Request, STATUS_INVALID_DEVICE_REQUEST);
}
VOID
StEvtIoDeviceControlSerial
(
WDFQUEUE Queue,
WDFREQUEST Request,
size_t OutputBufferLength,
size_t InputBufferLength,
ULONG IoControlCode
)
{
UNREFERENCED_PARAMETER(Queue);
UNREFERENCED_PARAMETER(OutputBufferLength);
UNREFERENCED_PARAMETER(InputBufferLength);
auto device = WdfIoQueueGetDevice(Queue);
if (IoControlCode == IOCTL_ST_RESET)
{
//
// Potential state transition here.
//
ioctl::ResetComplete(device, Request);
return;
}
auto context = DeviceGetSplitTunnelContext(device);
switch (context->DriverState.State)
{
case ST_DRIVER_STATE_STARTED:
{
//
// Valid controls:
//
// IOCTL_ST_INITIALIZE
//
if (IoControlCode == IOCTL_ST_INITIALIZE)
{
//
// Definitive state transition here.
// No locking needed this early.
//
WdfRequestComplete(Request, ioctl::Initialize(device));
return;
}
break;
}
case ST_DRIVER_STATE_INITIALIZED:
{
//
// Valid controls:
//
// IOCTL_ST_REGISTER_PROCESSES
//
if (IoControlCode == IOCTL_ST_REGISTER_PROCESSES)
{
//
// Definitive state transition here.
// No locking needed this early.
//
WdfRequestComplete(Request, ioctl::RegisterProcesses(device, Request));
return;
}
break;
}
case ST_DRIVER_STATE_READY:
case ST_DRIVER_STATE_ENGAGED:
{
//
// Valid controls:
//
// IOCTL_ST_REGISTER_IP_ADDRESSES
// IOCTL_ST_GET_IP_ADDRESSES
// IOCTL_ST_SET_CONFIGURATION
// IOCTL_ST_GET_CONFIGURATION
// IOCTL_ST_CLEAR_CONFIGURATION
// IOCTL_ST_QUERY_PROCESS
//
if (IoControlCode == IOCTL_ST_REGISTER_IP_ADDRESSES)
{
//
// Potential state transition here.
//
auto status = ioctl::RegisterIpAddresses(device, Request);
WdfRequestComplete(Request, status);
return;
}
if (IoControlCode == IOCTL_ST_GET_IP_ADDRESSES)
{
ioctl::GetIpAddressesComplete(device, Request);
return;
}
if (IoControlCode == IOCTL_ST_SET_CONFIGURATION)
{
registeredimage::CONTEXT *imageset;
auto status = ioctl::SetConfigurationPrepare(Request, &imageset);
if (!NT_SUCCESS(status))
{
WdfRequestComplete(Request, status);
return;
}
//
// Potential state transition here.
//
status = ioctl::SetConfiguration(device, imageset);
WdfRequestComplete(Request, status);
return;
}
if (IoControlCode == IOCTL_ST_GET_CONFIGURATION)
{
ioctl::GetConfigurationComplete(device, Request);
return;
}
if (IoControlCode == IOCTL_ST_CLEAR_CONFIGURATION)
{
//
// Potential state transition here.
//
auto status = ioctl::ClearConfiguration(device);
WdfRequestComplete(Request, status);
return;
}
if (IoControlCode == IOCTL_ST_QUERY_PROCESS)
{
ioctl::QueryProcessComplete(device, Request);
return;
}
break;
}
case ST_DRIVER_STATE_ZOMBIE:
{
DbgPrint("Zombie state: Rejecting all requests\n");
WdfRequestComplete(Request, STATUS_CANCELLED);
return;
}
}
DbgPrint("Invalid IOCTL or not valid for current driver state\n");
WdfRequestComplete(Request, STATUS_INVALID_DEVICE_REQUEST);
}
VOID
StEvtDriverUnload
(
IN WDFDRIVER WdfDriver
)
{
UNREFERENCED_PARAMETER(WdfDriver);
DbgPrint("Unloading Mullvad split tunnel driver\n");
WPP_CLEANUP(WdfDriverWdmGetDriverObject(WdfDriver));
}
| 16,184
|
C++
|
.cpp
| 550
| 22.407273
| 98
| 0.645193
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,026
|
util.cpp
|
mullvad_win-split-tunnel/src/util.cpp
|
#include <ntifs.h>
#include "util.h"
namespace util
{
void
ReparentList
(
LIST_ENTRY *Dest,
LIST_ENTRY *Src
)
{
//
// If it's an empty list there is nothing to reparent.
//
if (Src->Flink == Src)
{
InitializeListHead(Dest);
return;
}
//
// Replace root node.
//
*Dest = *Src;
//
// Update links on first and last entry.
//
Dest->Flink->Blink = Dest;
Dest->Blink->Flink = Dest;
//
// Reinitialize original root node.
//
InitializeListHead(Src);
}
typedef NTSTATUS (*QUERY_INFO_PROCESS) (
__in HANDLE ProcessHandle,
__in PROCESSINFOCLASS ProcessInformationClass,
__out_bcount(ProcessInformationLength) PVOID ProcessInformation,
__in ULONG ProcessInformationLength,
__out_opt PULONG ReturnLength
);
extern "C"
NTSTATUS
GetDevicePathImageName
(
PEPROCESS Process,
UNICODE_STRING **ImageName
)
{
*ImageName = NULL;
HANDLE processHandle;
auto status = ObOpenObjectByPointer
(
Process,
OBJ_KERNEL_HANDLE,
NULL,
GENERIC_READ,
NULL,
KernelMode,
&processHandle
);
if (!NT_SUCCESS(status))
{
return status;
}
static QUERY_INFO_PROCESS QueryFunction = NULL;
if (QueryFunction == NULL)
{
DECLARE_CONST_UNICODE_STRING(queryName, L"ZwQueryInformationProcess");
QueryFunction = (QUERY_INFO_PROCESS)
MmGetSystemRoutineAddress((UNICODE_STRING*)&queryName);
if (NULL == QueryFunction)
{
// TODO: Use more appropriate error code
status = STATUS_NOT_CAPABLE;
goto Failure;
}
}
//
// Determine required size of name buffer.
//
ULONG bufferLength;
status = QueryFunction
(
processHandle,
ProcessImageFileName,
NULL,
0,
&bufferLength
);
if (status != STATUS_INFO_LENGTH_MISMATCH)
{
goto Failure;
}
//
// Allocate name buffer.
//
*ImageName = (UNICODE_STRING*)ExAllocatePoolUninitialized(PagedPool, bufferLength, ST_POOL_TAG);
if (NULL == *ImageName)
{
status = STATUS_INSUFFICIENT_RESOURCES;
goto Failure;
}
//
// Retrieve filename.
//
status = QueryFunction
(
processHandle,
ProcessImageFileName,
*ImageName,
bufferLength,
&bufferLength
);
if (NT_SUCCESS(status))
{
goto Cleanup;
}
Failure:
if (*ImageName != NULL)
{
ExFreePoolWithTag(*ImageName, ST_POOL_TAG);
}
Cleanup:
ZwClose(processHandle);
return status;
}
bool
ValidateBufferRange
(
const void *Buffer,
const void *BufferEnd,
SIZE_T RangeOffset,
SIZE_T RangeLength
)
{
if (RangeLength == 0)
{
return true;
}
auto range = (const UCHAR*)Buffer + RangeOffset;
auto rangeEnd = range + RangeLength;
if (range < (const UCHAR*)Buffer
|| range >= (const UCHAR*)BufferEnd
|| rangeEnd < range
|| rangeEnd > BufferEnd)
{
return false;
}
return true;
}
bool
IsEmptyRange
(
const void *Buffer,
SIZE_T Length
)
{
//
// TODO
//
// Assuming x64, round down `Length` and read QWORDs from the buffer.
// Then read the last few bytes in this silly byte-by-byte manner.
//
for (auto b = (const UCHAR*)Buffer; Length != 0; ++b, --Length)
{
if (*b != 0)
{
return false;
}
}
return true;
}
NTSTATUS
AllocateCopyDowncaseString
(
LOWER_UNICODE_STRING *Dest,
const UNICODE_STRING * const Src,
ST_PAGEABLE Pageable
)
{
//
// Unfortunately, there is no way to determine the required buffer size.
//
// It would be possible to allocate e.g. `In.Length * 1.5` bytes, and waste memory.
//
// We opt for the slightly less time efficient method of allocating an exact size
// twice and copying the string.
//
UNICODE_STRING lower;
auto status = RtlDowncaseUnicodeString(&lower, Src, TRUE);
if (!NT_SUCCESS(status))
{
return status;
}
const auto poolType = (Pageable == ST_PAGEABLE::YES) ? PagedPool : NonPagedPool;
auto finalBuffer = (PWCH)ExAllocatePoolUninitialized(poolType, lower.Length, ST_POOL_TAG);
if (finalBuffer == NULL)
{
RtlFreeUnicodeString(&lower);
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlCopyMemory(finalBuffer, lower.Buffer, lower.Length);
Dest->Length = lower.Length;
Dest->MaximumLength = lower.Length;
Dest->Buffer = finalBuffer;
RtlFreeUnicodeString(&lower);
return STATUS_SUCCESS;
}
void
FreeStringBuffer
(
UNICODE_STRING *String
)
{
ExFreePoolWithTag(String->Buffer, ST_POOL_TAG);
String->Length = 0;
String->MaximumLength = 0;
String->Buffer = NULL;
}
void
FreeStringBuffer
(
LOWER_UNICODE_STRING *String
)
{
return FreeStringBuffer((UNICODE_STRING*)String);
}
NTSTATUS
DuplicateString
(
UNICODE_STRING *Dest,
const UNICODE_STRING *Src,
ST_PAGEABLE Pageable
)
{
const auto poolType = (Pageable == ST_PAGEABLE::YES) ? PagedPool : NonPagedPool;
auto buffer = (PWCH)ExAllocatePoolUninitialized(poolType, Src->Length, ST_POOL_TAG);
if (NULL == buffer)
{
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlCopyMemory(buffer, Src->Buffer, Src->Length);
Dest->Length = Src->Length;
Dest->MaximumLength = Src->Length;
Dest->Buffer = buffer;
return STATUS_SUCCESS;
}
NTSTATUS
DuplicateString
(
LOWER_UNICODE_STRING *Dest,
const LOWER_UNICODE_STRING *Src,
ST_PAGEABLE Pageable
)
{
return DuplicateString((UNICODE_STRING*)Dest, (const UNICODE_STRING*)Src, Pageable);
}
void
StopIfDebugBuild
(
)
{
#ifdef DEBUG
DbgBreakPoint();
#endif
}
bool
SplittingEnabled
(
ST_PROCESS_SPLIT_STATUS Status
)
{
return (Status == ST_PROCESS_SPLIT_STATUS_ON_BY_CONFIG
|| Status == ST_PROCESS_SPLIT_STATUS_ON_BY_INHERITANCE);
}
bool
Equal
(
const LOWER_UNICODE_STRING *lhs,
const LOWER_UNICODE_STRING *rhs
)
{
if (lhs->Length != rhs->Length)
{
return false;
}
const auto equalBytes = RtlCompareMemory
(
lhs->Buffer,
rhs->Buffer,
lhs->Length
);
return equalBytes == lhs->Length;
}
void
Swap
(
LOWER_UNICODE_STRING *lhs,
LOWER_UNICODE_STRING *rhs
)
{
const LOWER_UNICODE_STRING temp = *lhs;
*lhs = *rhs;
*rhs = temp;
}
} // namespace util
| 5,811
|
C++
|
.cpp
| 306
| 16.732026
| 97
| 0.736009
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,027
|
ioctl.cpp
|
mullvad_win-split-tunnel/src/ioctl.cpp
|
#include "ioctl.h"
#include "devicecontext.h"
#include "util.h"
#include "ipaddr.h"
#include "firewall/firewall.h"
#include "defs/config.h"
#include "defs/process.h"
#include "defs/queryprocess.h"
#include "validation.h"
#include "eventing/eventing.h"
#include "eventing/builder.h"
#include "trace.h"
#include "ioctl.tmh"
namespace ioctl
{
namespace
{
//
// Minimum buffer sizes for requests.
//
enum class MIN_REQUEST_SIZE
{
SET_CONFIGURATION = sizeof(ST_CONFIGURATION_HEADER),
GET_CONFIGURATION = sizeof(SIZE_T),
REGISTER_PROCESSES = sizeof(ST_PROCESS_DISCOVERY_HEADER),
REGISTER_IP_ADDRESSES = sizeof(ST_IP_ADDRESSES),
GET_IP_ADDRESSES = sizeof(ST_IP_ADDRESSES),
GET_STATE = sizeof(SIZE_T),
QUERY_PROCESS = sizeof(ST_QUERY_PROCESS),
QUERY_PROCESS_RESPONSE = sizeof(ST_QUERY_PROCESS_RESPONSE),
};
bool VpnActive(const ST_IP_ADDRESSES *IpAddresses)
{
return ip::ValidTunnelIpv4Address(IpAddresses) || ip::ValidTunnelIpv6Address(IpAddresses);
}
NTSTATUS
InitializeProcessRegistryMgmt
(
PROCESS_REGISTRY_MGMT *Mgmt
)
{
auto status = WdfSpinLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &Mgmt->Lock);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfSpinLockCreate() failed 0x%X\n", status);
goto Abort;
}
status = procregistry::Initialize(&Mgmt->Instance, ST_PAGEABLE::NO);
if (!NT_SUCCESS(status))
{
DbgPrint("procregistry::Initialize() failed 0x%X\n", status);
goto Abort_Delete_Lock;
}
return STATUS_SUCCESS;
Abort_Delete_Lock:
WdfObjectDelete(Mgmt->Lock);
Abort:
Mgmt->Lock = NULL;
Mgmt->Instance = NULL;
return status;
}
void
DestroyProcessRegistryMgmt
(
PROCESS_REGISTRY_MGMT *Mgmt
)
{
if (Mgmt->Instance != NULL)
{
procregistry::TearDown(&Mgmt->Instance);
Mgmt->Instance = NULL;
}
if (Mgmt->Lock != NULL)
{
WdfObjectDelete(Mgmt->Lock);
Mgmt->Lock = NULL;
}
}
//
// UpdateTargetSplitSetting()
//
// Updates the target split setting on a process registry entry.
//
// Target state is set to split if either of:
//
// - Imagename is included in config.
// - Currently split by inheritance and parent has departed.
//
bool
NTAPI
UpdateTargetSplitSetting
(
procregistry::PROCESS_REGISTRY_ENTRY *Entry,
void *Context
)
{
auto context = (ST_DEVICE_CONTEXT*)Context;
Entry->TargetSettings.Split = ST_PROCESS_SPLIT_STATUS_OFF;
if (registeredimage::HasEntryExact(context->RegisteredImage.Instance, &Entry->ImageName))
{
Entry->TargetSettings.Split = ST_PROCESS_SPLIT_STATUS_ON_BY_CONFIG;
}
else if (Entry->ParentProcessId == 0
&& Entry->Settings.Split == ST_PROCESS_SPLIT_STATUS_ON_BY_INHERITANCE)
{
Entry->TargetSettings.Split = ST_PROCESS_SPLIT_STATUS_ON_BY_INHERITANCE;
}
return true;
}
//
// ApplyFinalizeTargetSettings()
//
// NOTE: Applies the target split setting but does not update current settings
// on the process registry entry under consideration.
//
// Manages transitions in settings changes:
//
// Not split -> split
// Split -> not split
//
// Something worth noting is that a process being split may have firewall state, but a process
// that's not being split will never have firewall state.
//
// This is contrary to a previous design that used additional filters to block non-tunnel traffic.
//
bool
NTAPI
ApplyFinalizeTargetSettings
(
ST_DEVICE_CONTEXT *Context,
procregistry::PROCESS_REGISTRY_ENTRY *Entry
)
{
if (!util::SplittingEnabled(Entry->Settings.Split))
{
NT_ASSERT(!Entry->Settings.HasFirewallState);
if (!util::SplittingEnabled(Entry->TargetSettings.Split))
{
Entry->TargetSettings.HasFirewallState = false;
return true;
}
//
// Not split -> split
//
auto status = firewall::RegisterAppBecomingSplitTx(Context->Firewall, &Entry->ImageName);
if (!NT_SUCCESS(status))
{
return false;
}
return Entry->TargetSettings.HasFirewallState = true;
}
if (util::SplittingEnabled(Entry->TargetSettings.Split))
{
Entry->TargetSettings.HasFirewallState = Entry->Settings.HasFirewallState;
return true;
}
//
// Split -> not split
//
if (Entry->Settings.HasFirewallState)
{
auto status = firewall::RegisterAppBecomingUnsplitTx(Context->Firewall, &Entry->ImageName);
if (!NT_SUCCESS(status))
{
return false;
}
}
Entry->TargetSettings.HasFirewallState = false;
return true;
}
//
// PropagateApplyTargetSettings()
//
// Traverse ancestry to see if parent/grandparent/etc is being split.
// Then apply target split setting.
//
bool
NTAPI
PropagateApplyTargetSettings
(
procregistry::PROCESS_REGISTRY_ENTRY *Entry,
void *Context
)
{
auto context = (ST_DEVICE_CONTEXT *)Context;
if (!util::SplittingEnabled(Entry->TargetSettings.Split))
{
auto currentEntry = Entry;
//
// In the current state of changing settings,
// we have to follow the ancestry all the way to the root.
//
for (;;)
{
const auto parent = procregistry::GetParentEntry(context->ProcessRegistry.Instance, currentEntry);
if (NULL == parent)
{
break;
}
if (util::SplittingEnabled(parent->TargetSettings.Split))
{
Entry->TargetSettings.Split = ST_PROCESS_SPLIT_STATUS_ON_BY_INHERITANCE;
break;
}
currentEntry = parent;
}
}
return ApplyFinalizeTargetSettings(context, Entry);
}
struct CONFIGURATION_COMPUTE_LENGTH_CONTEXT
{
SIZE_T NumEntries;
SIZE_T TotalStringLength;
};
bool
NTAPI
GetConfigurationComputeLength
(
const LOWER_UNICODE_STRING *Entry,
void *Context
)
{
auto ctx = (CONFIGURATION_COMPUTE_LENGTH_CONTEXT*)Context;
++(ctx->NumEntries);
ctx->TotalStringLength += Entry->Length;
return true;
}
struct CONFIGURATION_SERIALIZE_CONTEXT
{
// Next entry that should be written.
ST_CONFIGURATION_ENTRY *Entry;
// Pointer where next string should be written.
UCHAR *StringDest;
// Offset where next string should be written.
SIZE_T StringOffset;
};
bool
NTAPI
GetConfigurationSerialize
(
const LOWER_UNICODE_STRING *Entry,
void *Context
)
{
auto ctx = (CONFIGURATION_SERIALIZE_CONTEXT*)Context;
//
// Copy data.
//
ctx->Entry->ImageNameOffset = ctx->StringOffset;
ctx->Entry->ImageNameLength = Entry->Length;
RtlCopyMemory(ctx->StringDest, Entry->Buffer, Entry->Length);
//
// Update context for next iteration.
//
++(ctx->Entry);
ctx->StringDest += Entry->Length;
ctx->StringOffset += Entry->Length;
return true;
}
//
// CallbackQueryProcess
//
// This callback is provided to the firewall for use with callouts.
//
// We don't need to worry about the current driver state, because if callouts
// are active this means the current state is "engaged".
//
firewall::PROCESS_SPLIT_VERDICT
CallbackQueryProcess
(
HANDLE ProcessId,
void *RawContext
)
{
auto context = (ST_DEVICE_CONTEXT*)RawContext;
WdfSpinLockAcquire(context->ProcessRegistry.Lock);
auto process = procregistry::FindEntry(context->ProcessRegistry.Instance, ProcessId);
firewall::PROCESS_SPLIT_VERDICT verdict = firewall::PROCESS_SPLIT_VERDICT::UNKNOWN;
if (process != NULL)
{
verdict = (util::SplittingEnabled(process->Settings.Split)
? firewall::PROCESS_SPLIT_VERDICT::DO_SPLIT
: firewall::PROCESS_SPLIT_VERDICT::DONT_SPLIT);
}
WdfSpinLockRelease(context->ProcessRegistry.Lock);
return verdict;
}
bool
NTAPI
DbgPrintConfiguration
(
const LOWER_UNICODE_STRING *Entry,
void *Context
)
{
UNREFERENCED_PARAMETER(Context);
DbgPrint("%wZ\n", (const UNICODE_STRING*)Entry);
return true;
}
//
// RealizeAnnounceSettingsChange()
//
// Update previous, current settings.
//
// Analyze change and emit corresponding event.
//
bool
NTAPI
RealizeAnnounceSettingsChange
(
procregistry::PROCESS_REGISTRY_ENTRY *Entry,
void *Context
)
{
auto context = (ST_DEVICE_CONTEXT *)Context;
Entry->PreviousSettings = Entry->Settings;
Entry->Settings = Entry->TargetSettings;
if (util::SplittingEnabled(Entry->Settings.Split))
{
if (!util::SplittingEnabled(Entry->PreviousSettings.Split))
{
auto evt = eventing::BuildStartSplittingEvent(Entry->ProcessId,
ST_SPLITTING_REASON_BY_CONFIG, &Entry->ImageName);
eventing::Emit(context->Eventing, &evt);
}
}
else
{
if (util::SplittingEnabled(Entry->PreviousSettings.Split))
{
auto evt = eventing::BuildStopSplittingEvent(Entry->ProcessId,
ST_SPLITTING_REASON_BY_CONFIG, &Entry->ImageName);
eventing::Emit(context->Eventing, &evt);
}
}
return true;
}
//
// ClearRealizeAnnounceSettingsChange()
//
// Clear splitting. Then realize and announce.
//
bool
NTAPI
ClearRealizeAnnounceSettingsChange
(
procregistry::PROCESS_REGISTRY_ENTRY *Entry,
void *Context
)
{
Entry->TargetSettings.Split = ST_PROCESS_SPLIT_STATUS_OFF;
Entry->TargetSettings.HasFirewallState = false;
return RealizeAnnounceSettingsChange(Entry, Context);
}
NTSTATUS
SyncProcessRegistry
(
ST_DEVICE_CONTEXT *Context,
bool ForceAleReauthorization = false
)
{
//
// The process management subsystem is locked out becase we're holding the state lock.
// This ensures there will be no structural changes to the process registry.
//
// There will be readers at DISPATCH (callouts).
// But we are free to make atomic updates to individual entries.
//
// Locking of the configuration is not required since we're in the serialized
// IOCTL handler path.
//
procregistry::ForEach(Context->ProcessRegistry.Instance, UpdateTargetSplitSetting, Context);
auto status = firewall::TransactionBegin(Context->Firewall);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not create firewall transaction: 0x%X\n", status);
return status;
}
auto successful = procregistry::ForEach(Context->ProcessRegistry.Instance, PropagateApplyTargetSettings, Context);
if (!successful)
{
DbgPrint("Could not add/remove firewall filters\n");
status = STATUS_UNSUCCESSFUL;
goto Abort;
}
status = firewall::TransactionCommit(Context->Firewall, ForceAleReauthorization);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not commit firewall transaction\n");
goto Abort;
}
//
// No fallible operations beyond here.
//
// Send splitting events and finish off.
//
procregistry::ForEach(Context->ProcessRegistry.Instance, RealizeAnnounceSettingsChange, Context);
return STATUS_SUCCESS;
Abort:
auto s2 = firewall::TransactionAbort(Context->Firewall);
if (!NT_SUCCESS(s2))
{
DbgPrint("Could not abort firewall transaction: 0x%X\n", s2);
}
return status;
}
NTSTATUS
EnterEngagedState
(
ST_DEVICE_CONTEXT *Context,
const ST_IP_ADDRESSES *IpAddresses
)
{
auto status = firewall::EnableSplitting(Context->Firewall, IpAddresses);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not enable splitting in firewall: 0x%X\n", status);
return status;
}
status = SyncProcessRegistry(Context);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not synchronize process registry with configuration: 0x%X\n", status);
auto s2 = firewall::DisableSplitting(Context->Firewall);
if (!NT_SUCCESS(s2))
{
DbgPrint("DisableSplitting() failed: 0x%X\n", s2);
}
return status;
}
Context->DriverState.State = ST_DRIVER_STATE_ENGAGED;
DbgPrint("Successful state transition READY -> ENGAGED\n");
return STATUS_SUCCESS;
}
NTSTATUS
LeaveEngagedState
(
ST_DEVICE_CONTEXT *Context
)
{
auto status = firewall::DisableSplitting(Context->Firewall);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not disable splitting in firewall: 0x%X\n", status);
return status;
}
//
// This doesn't touch the firewall.
// It's already been reset as a result of the disable-call above.
//
procregistry::ForEach(Context->ProcessRegistry.Instance, ClearRealizeAnnounceSettingsChange, Context);
Context->DriverState.State = ST_DRIVER_STATE_READY;
DbgPrint("Successful state transition ENGAGED -> READY\n");
return STATUS_SUCCESS;
}
NTSTATUS
RegisterIpAddressesAtReady
(
ST_DEVICE_CONTEXT *Context,
const ST_IP_ADDRESSES *newIpAddresses
)
{
//
// If there's no config registered we just store the addresses and succeed.
//
// No need to access the configuration exclusively:
//
// - We're in the serialized IOCTL handler path.
// - Config is only read from, not written to.
//
if (registeredimage::IsEmpty(Context->RegisteredImage.Instance))
{
Context->IpAddresses = *newIpAddresses;
return STATUS_SUCCESS;
}
//
// There's a configuration registered.
//
// However, if the VPN isn't active we can't enter the engaged state.
//
if (!VpnActive(newIpAddresses))
{
Context->IpAddresses = *newIpAddresses;
return STATUS_SUCCESS;
}
//
// Enter into engaged state.
//
auto status = EnterEngagedState(Context, newIpAddresses);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not enter engaged state: 0x%X\n", status);
return status;
}
Context->IpAddresses = *newIpAddresses;
return STATUS_SUCCESS;
}
NTSTATUS
RegisterIpAddressesAtEngaged
(
ST_DEVICE_CONTEXT *Context,
const ST_IP_ADDRESSES *newIpAddresses
)
{
if (!VpnActive(newIpAddresses))
{
auto status = LeaveEngagedState(Context);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not leave engaged state: 0x%X\n", status);
return status;
}
Context->IpAddresses = *newIpAddresses;
return STATUS_SUCCESS;
}
//
// No state change required.
// Notify firewall so it can rewrite any filters with IP-conditions.
//
auto status = firewall::RegisterUpdatedIpAddresses(Context->Firewall, newIpAddresses);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not update firewall with new IPs: 0x%X\n", status);
return status;
}
Context->IpAddresses = *newIpAddresses;
return STATUS_SUCCESS;
}
NTSTATUS
RegisterConfigurationAtReady
(
ST_DEVICE_CONTEXT *Context,
registeredimage::CONTEXT *Imageset
)
{
//
// If VPN is not active just store new configuration and succeed.
//
if (!VpnActive(&Context->IpAddresses))
{
auto oldConfiguration = Context->RegisteredImage.Instance;
Context->RegisteredImage.Instance = Imageset;
registeredimage::TearDown(&oldConfiguration);
return STATUS_SUCCESS;
}
//
// VPN is active so enter engaged state.
//
auto oldConfiguration = Context->RegisteredImage.Instance;
Context->RegisteredImage.Instance = Imageset;
auto status = EnterEngagedState(Context, &Context->IpAddresses);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not enter engaged state: 0x%X\n", status);
Context->RegisteredImage.Instance = oldConfiguration;
registeredimage::TearDown(&Imageset);
return status;
}
registeredimage::TearDown(&oldConfiguration);
return STATUS_SUCCESS;
}
NTSTATUS
RegisterConfigurationAtEngaged
(
ST_DEVICE_CONTEXT *Context,
registeredimage::CONTEXT *Imageset
)
{
auto oldConfiguration = Context->RegisteredImage.Instance;
Context->RegisteredImage.Instance = Imageset;
//
// Update process registry to reflect new configuration.
//
auto status = SyncProcessRegistry(Context, true);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not synchronize process registry with configuration: 0x%X\n", status);
Context->RegisteredImage.Instance = oldConfiguration;
registeredimage::TearDown(&Imageset);
return status;
}
registeredimage::TearDown(&oldConfiguration);
return STATUS_SUCCESS;
}
void
NTAPI
CallbackAcquireStateLock
(
void *Context
)
{
auto context = (ST_DEVICE_CONTEXT*)Context;
WdfWaitLockAcquire(context->DriverState.Lock, NULL);
}
void
NTAPI
CallbackReleaseStateLock
(
void *Context
)
{
auto context = (ST_DEVICE_CONTEXT*)Context;
WdfWaitLockRelease(context->DriverState.Lock);
}
bool
NTAPI
CallbackEngagedStateActive
(
void *Context
)
{
auto context = (ST_DEVICE_CONTEXT*)Context;
return context->DriverState.State == ST_DRIVER_STATE_ENGAGED;
}
NTSTATUS
ResetInner
(
ST_DEVICE_CONTEXT *Context
)
{
//
// Leave engaged state to minimize the impact if any of this fails.
//
if (Context->DriverState.State == ST_DRIVER_STATE_ENGAGED)
{
WdfWaitLockAcquire(Context->DriverState.Lock, NULL);
auto status = LeaveEngagedState(Context);
WdfWaitLockRelease(Context->DriverState.Lock);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not leave engaged state\n");
}
}
//
// Tear down everything in reverse order of initializing it.
//
procmgmt::TearDown(&Context->ProcessMgmt);
auto status = firewall::TearDown(&Context->Firewall);
if (!NT_SUCCESS(status))
{
//
// Filters or callouts could not be unregistered.
//
// There is no way to recover from this. The driver will not be able to unload.
//
// All moving parts in the system that depend on the state lock are stopped.
// So safe to update state without using the lock.
//
Context->DriverState.State = ST_DRIVER_STATE_ZOMBIE;
return status;
}
RtlZeroMemory(&Context->IpAddresses, sizeof(Context->IpAddresses));
procregistry::TearDown(&Context->ProcessRegistry.Instance);
registeredimage::TearDown((registeredimage::CONTEXT**)&Context->RegisteredImage.Instance);
procbroker::TearDown(&Context->ProcessEventBroker);
eventing::TearDown(&Context->Eventing);
Context->DriverState.State = ST_DRIVER_STATE_STARTED;
return STATUS_SUCCESS;
}
} // anonymous namespace
NTSTATUS
Initialize
(
WDFDEVICE Device
)
{
auto context = DeviceGetSplitTunnelContext(Device);
//
// The context struct is cleared.
// Only state is set at this point.
//
auto status = eventing::Initialize(&context->Eventing, Device);
if (!NT_SUCCESS(status))
{
return status;
}
status = procbroker::Initialize(&context->ProcessEventBroker);
if (!NT_SUCCESS(status))
{
goto Abort_teardown_eventing;
}
status = registeredimage::Initialize
(
(registeredimage::CONTEXT**)&context->RegisteredImage.Instance,
ST_PAGEABLE::NO
);
if (!NT_SUCCESS(status))
{
goto Abort_teardown_procbroker;
}
status = InitializeProcessRegistryMgmt(&context->ProcessRegistry);
if (!NT_SUCCESS(status))
{
goto Abort_teardown_registeredimage;
}
firewall::CALLBACKS callbacks;
callbacks.QueryProcess = CallbackQueryProcess;
callbacks.Context = context;
status = firewall::Initialize
(
&context->Firewall,
WdfDeviceWdmGetDeviceObject(Device),
&callbacks,
context->ProcessEventBroker,
context->Eventing
);
if (!NT_SUCCESS(status))
{
goto Abort_teardown_process_registry;
}
status = procmgmt::Initialize
(
&context->ProcessMgmt,
context->ProcessEventBroker,
&context->ProcessRegistry,
&context->RegisteredImage,
context->Eventing,
context->Firewall,
CallbackAcquireStateLock,
CallbackReleaseStateLock,
CallbackEngagedStateActive,
context
);
if (!NT_SUCCESS(status))
{
goto Abort_teardown_firewall;
}
context->DriverState.State = ST_DRIVER_STATE_INITIALIZED;
DbgPrint("Successfully processed IOCTL_ST_INITIALIZE\n");
return STATUS_SUCCESS;
Abort_teardown_firewall:
firewall::TearDown(&context->Firewall);
Abort_teardown_process_registry:
DestroyProcessRegistryMgmt(&context->ProcessRegistry);
Abort_teardown_registeredimage:
registeredimage::TearDown((registeredimage::CONTEXT**)&context->RegisteredImage.Instance);
Abort_teardown_procbroker:
procbroker::TearDown(&context->ProcessEventBroker);
Abort_teardown_eventing:
eventing::TearDown(&context->Eventing);
return status;
}
//
// SetConfigurationPrepare()
//
// Validate and repackage configuration data into new registered image instance.
//
// This runs at PASSIVE, in order to be able to downcase the strings.
//
NTSTATUS
SetConfigurationPrepare
(
WDFREQUEST Request,
registeredimage::CONTEXT **Imageset
)
{
*Imageset = NULL;
PVOID buffer;
size_t bufferLength;
auto status = WdfRequestRetrieveInputBuffer(Request,
(size_t)MIN_REQUEST_SIZE::SET_CONFIGURATION, &buffer, &bufferLength);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not access configuration buffer provided to IOCTL: 0x%X\n", status);
return status;
}
if (!ValidateUserBufferConfiguration(buffer, bufferLength))
{
DbgPrint("Invalid configuration data in buffer provided to IOCTL\n");
return STATUS_INVALID_PARAMETER;
}
auto header = (ST_CONFIGURATION_HEADER*)buffer;
auto entry = (ST_CONFIGURATION_ENTRY*)(header + 1);
auto stringBuffer = (UCHAR*)(entry + header->NumEntries);
if (header->NumEntries == 0)
{
DbgPrint("Cannot assign empty configuration\n");
return STATUS_INVALID_PARAMETER;
}
//
// Create new instance for storing image names.
//
registeredimage::CONTEXT *imageset;
status = registeredimage::Initialize(&imageset, ST_PAGEABLE::NO);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not create new registered image instance: 0x%X\n", status);
return status;
}
//
// Insert each entry one by one.
//
for (auto i = 0; i < header->NumEntries; ++i, ++entry)
{
UNICODE_STRING s;
s.Length = entry->ImageNameLength;
s.MaximumLength = entry->ImageNameLength;
s.Buffer = (WCHAR*)(stringBuffer + entry->ImageNameOffset);
status = registeredimage::AddEntry(imageset, &s);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not insert new entry into registered image instance: 0x%X\n", status);
registeredimage::TearDown(&imageset);
return status;
}
}
*Imageset = imageset;
return STATUS_SUCCESS;
}
//
// SetConfiguration()
//
// Store updated configuration.
//
// Possibly enter/leave engaged state depending on a number of factors.
//
NTSTATUS
SetConfiguration
(
WDFDEVICE Device,
registeredimage::CONTEXT *Imageset
)
{
auto context = DeviceGetSplitTunnelContext(Device);
NTSTATUS status = STATUS_UNSUCCESSFUL;
WdfWaitLockAcquire(context->DriverState.Lock, NULL);
switch (context->DriverState.State)
{
case ST_DRIVER_STATE_READY:
{
status = RegisterConfigurationAtReady(context, Imageset);
break;
}
case ST_DRIVER_STATE_ENGAGED:
{
status = RegisterConfigurationAtEngaged(context, Imageset);
break;
}
}
WdfWaitLockRelease(context->DriverState.Lock);
if (NT_SUCCESS(status))
{
DbgPrint("Successfully processed IOCTL_ST_SET_CONFIGURATION\n");
//
// No locking required since we're in a serialized IOCTL handler path.
//
registeredimage::ForEach
(
context->RegisteredImage.Instance,
DbgPrintConfiguration,
NULL
);
}
return status;
}
//
// GetConfigurationComplete()
//
// Return current configuration to driver client.
//
// Locking is not required for the following reasons:
//
// - We're in the serialized IOCTL handler path.
// - Config is only read from, not written to.
//
void
GetConfigurationComplete
(
WDFDEVICE Device,
WDFREQUEST Request
)
{
PVOID buffer;
size_t bufferLength;
auto status = WdfRequestRetrieveOutputBuffer(Request,
(size_t)MIN_REQUEST_SIZE::GET_CONFIGURATION, &buffer, &bufferLength);
if (!NT_SUCCESS(status))
{
WdfRequestComplete(Request, status);
return;
}
//
// Buffer is present and meets the minimum size requirements.
// This means we can "complete with information".
//
ULONG_PTR info = 0;
//
// Compute required buffer length.
//
auto context = DeviceGetSplitTunnelContext(Device);
CONFIGURATION_COMPUTE_LENGTH_CONTEXT computeContext;
computeContext.NumEntries = 0;
computeContext.TotalStringLength = 0;
registeredimage::ForEach(context->RegisteredImage.Instance,
GetConfigurationComputeLength, &computeContext);
SIZE_T requiredLength = sizeof(ST_CONFIGURATION_HEADER)
+ (sizeof(ST_CONFIGURATION_ENTRY) * computeContext.NumEntries)
+ computeContext.TotalStringLength;
//
// It's not possible to fail the request AND provide output data.
//
// Therefore, the only two types of valid input buffers are:
//
// # A buffer large enough to contain the settings.
// # A buffer of exactly sizeof(SIZE_T) bytes, to learn the required length.
//
if (bufferLength < requiredLength)
{
if (bufferLength == sizeof(SIZE_T))
{
status = STATUS_SUCCESS;
*(SIZE_T*)buffer = requiredLength;
info = sizeof(SIZE_T);
}
else
{
status = STATUS_BUFFER_TOO_SMALL;
info = 0;
}
goto Complete;
}
//
// Output buffer is OK.
// Serialize config into buffer.
//
auto header = (ST_CONFIGURATION_HEADER*)buffer;
auto entry = (ST_CONFIGURATION_ENTRY*)(header + 1);
auto stringBuffer = (UCHAR*)(entry + computeContext.NumEntries);
CONFIGURATION_SERIALIZE_CONTEXT serializeContext;
serializeContext.Entry = entry;
serializeContext.StringOffset = 0;
serializeContext.StringDest = stringBuffer;
registeredimage::ForEach(context->RegisteredImage.Instance,
GetConfigurationSerialize, &serializeContext);
//
// Finalize header.
//
header->NumEntries = computeContext.NumEntries;
header->TotalLength = requiredLength;
info = requiredLength;
status = STATUS_SUCCESS;
Complete:
WdfRequestCompleteWithInformation(Request, status, info);
}
//
// ClearConfiguration()
//
// Mark all processes as non-split and clear configuration.
//
NTSTATUS
ClearConfiguration
(
WDFDEVICE Device
)
{
auto context = DeviceGetSplitTunnelContext(Device);
WdfWaitLockAcquire(context->DriverState.Lock, NULL);
if (context->DriverState.State == ST_DRIVER_STATE_ENGAGED)
{
//
// Leave engaged state.
// (This updates the process registry and sends splitting events.)
//
auto status = LeaveEngagedState(context);
if (!NT_SUCCESS(status))
{
WdfWaitLockRelease(context->DriverState.Lock);
DbgPrint("Could not leave engaged state: 0x%X\n", status);
return status;
}
}
registeredimage::Reset(context->RegisteredImage.Instance);
WdfWaitLockRelease(context->DriverState.Lock);
DbgPrint("Successfully processed IOCTL_ST_CLEAR_CONFIGURATION\n");
return STATUS_SUCCESS;
}
NTSTATUS
RegisterProcesses
(
WDFDEVICE Device,
WDFREQUEST Request
)
{
PVOID buffer;
size_t bufferLength;
auto status = WdfRequestRetrieveInputBuffer(Request,
(size_t)MIN_REQUEST_SIZE::REGISTER_PROCESSES, &buffer, &bufferLength);
if (!NT_SUCCESS(status))
{
return status;
}
if (!ValidateUserBufferProcesses(buffer, bufferLength))
{
DbgPrint("Invalid data provided to IOCTL_ST_REGISTER_PROCESSES\n");
return STATUS_INVALID_PARAMETER;
}
auto header = (ST_PROCESS_DISCOVERY_HEADER*)buffer;
auto entry = (ST_PROCESS_DISCOVERY_ENTRY*)(header + 1);
auto stringBuffer = (UCHAR*)(entry + header->NumEntries);
auto context = DeviceGetSplitTunnelContext(Device);
NT_ASSERT(procregistry::IsEmpty(context->ProcessRegistry.Instance));
//
// Insert records one by one.
//
// We can't check the configuration to get accurate information on whether the process being
// inserted should have its traffic split.
//
// Because there is no configuration yet.
//
for (auto i = 0; i < header->NumEntries; ++i, ++entry)
{
UNICODE_STRING imagename;
imagename.Length = entry->ImageNameLength;
imagename.MaximumLength = entry->ImageNameLength;
if (entry->ImageNameLength == 0)
{
imagename.Buffer = NULL;
}
else
{
imagename.Buffer = (WCHAR*)(stringBuffer + entry->ImageNameOffset);
}
procregistry::PROCESS_REGISTRY_ENTRY registryEntry = { 0 };
status = procregistry::InitializeEntry
(
context->ProcessRegistry.Instance,
entry->ParentProcessId,
entry->ProcessId,
ST_PROCESS_SPLIT_STATUS_OFF,
&imagename,
®istryEntry
);
if (!NT_SUCCESS(status))
{
procregistry::Reset(context->ProcessRegistry.Instance);
return status;
}
status = procregistry::AddEntry
(
context->ProcessRegistry.Instance,
®istryEntry
);
if (!NT_SUCCESS(status))
{
procregistry::ReleaseEntry(®istryEntry);
procregistry::Reset(context->ProcessRegistry.Instance);
return status;
}
}
context->DriverState.State = ST_DRIVER_STATE_READY;
procmgmt::Activate(context->ProcessMgmt);
DbgPrint("Successfully processed IOCTL_ST_REGISTER_PROCESSES\n");
return STATUS_SUCCESS;
}
//
// RegisterIpAddresses()
//
// Store updated set of IP addresses.
//
// Possibly enter/leave engaged state depending on a number of factors.
//
NTSTATUS
RegisterIpAddresses
(
WDFDEVICE Device,
WDFREQUEST Request
)
{
PVOID buffer;
size_t bufferLength;
auto status = WdfRequestRetrieveInputBuffer(Request,
(size_t)MIN_REQUEST_SIZE::REGISTER_IP_ADDRESSES, &buffer, &bufferLength);
if (!NT_SUCCESS(status))
{
return status;
}
if (bufferLength != sizeof(ST_IP_ADDRESSES))
{
DbgPrint("Invalid data provided to IOCTL_ST_REGISTER_IP_ADDRESSES\n");
return STATUS_INVALID_PARAMETER;
}
auto newIpAddresses = (ST_IP_ADDRESSES*)buffer;
//
// New addresses seem OK, branch on current state.
//
status = STATUS_UNSUCCESSFUL;
auto context = DeviceGetSplitTunnelContext(Device);
WdfWaitLockAcquire(context->DriverState.Lock, NULL);
switch (context->DriverState.State)
{
case ST_DRIVER_STATE_READY:
{
status = RegisterIpAddressesAtReady(context, newIpAddresses);
break;
}
case ST_DRIVER_STATE_ENGAGED:
{
status = RegisterIpAddressesAtEngaged(context, newIpAddresses);
break;
}
}
WdfWaitLockRelease(context->DriverState.Lock);
if (NT_SUCCESS(status))
{
DbgPrint("Successfully processed IOCTL_ST_REGISTER_IP_ADDRESSES\n");
}
return status;
}
//
// GetIpAddressesComplete()
//
// Return currently registered IP addresses to driver client.
//
// Locking is not required for the following reasons:
//
// - We're in the serialized IOCTL handler path.
// - IP addresses struct is only read from, not written to.
//
void
GetIpAddressesComplete
(
WDFDEVICE Device,
WDFREQUEST Request
)
{
NT_ASSERT((size_t)MIN_REQUEST_SIZE::GET_IP_ADDRESSES >= sizeof(ST_IP_ADDRESSES));
PVOID buffer;
auto status = WdfRequestRetrieveOutputBuffer
(
Request,
(size_t)MIN_REQUEST_SIZE::GET_IP_ADDRESSES,
&buffer,
NULL
);
if (!NT_SUCCESS(status))
{
WdfRequestComplete(Request, status);
return;
}
//
// Copy IP addresses struct to output buffer.
//
auto context = DeviceGetSplitTunnelContext(Device);
RtlCopyMemory(buffer, &context->IpAddresses, sizeof(context->IpAddresses));
//
// Finish up.
//
WdfRequestCompleteWithInformation(Request, STATUS_SUCCESS, sizeof(context->IpAddresses));
}
void
GetStateComplete
(
WDFDEVICE Device,
WDFREQUEST Request
)
{
PVOID buffer;
auto status = WdfRequestRetrieveOutputBuffer
(
Request,
(size_t)MIN_REQUEST_SIZE::GET_STATE,
&buffer,
NULL
);
if (!NT_SUCCESS(status))
{
DbgPrint("Unable to retrieve client buffer or invalid buffer size\n");
WdfRequestComplete(Request, status);
return;
}
auto context = DeviceGetSplitTunnelContext(Device);
// Sample current state.
*(SIZE_T*)buffer = context->DriverState.State;
WdfRequestCompleteWithInformation(Request, STATUS_SUCCESS, sizeof(SIZE_T));
}
//
// QueryProcessComplete()
//
// Returns information about specific process to driver client.
//
void
QueryProcessComplete
(
WDFDEVICE Device,
WDFREQUEST Request
)
{
PVOID buffer;
size_t bufferLength;
auto status = WdfRequestRetrieveInputBuffer
(
Request,
(size_t)MIN_REQUEST_SIZE::QUERY_PROCESS,
&buffer,
&bufferLength
);
if (!NT_SUCCESS(status))
{
DbgPrint("Unable to retrieve input buffer or buffer too small\n");
WdfRequestComplete(Request, status);
return;
}
if (bufferLength != (size_t)MIN_REQUEST_SIZE::QUERY_PROCESS)
{
DbgPrint("Invalid buffer size\n");
WdfRequestComplete(Request, STATUS_INVALID_BUFFER_SIZE);
return;
}
auto processId = ((ST_QUERY_PROCESS*)buffer)->ProcessId;
//
// Get the output buffer.
//
// We can't validate the buffer length just yet, because we don't know the
// length of the process image name.
//
status = WdfRequestRetrieveOutputBuffer
(
Request,
(size_t)MIN_REQUEST_SIZE::QUERY_PROCESS_RESPONSE,
&buffer,
&bufferLength
);
if (!NT_SUCCESS(status))
{
DbgPrint("Unable to retrieve output buffer or buffer too small\n");
WdfRequestComplete(Request, status);
return;
}
//
// Look up process.
//
auto context = DeviceGetSplitTunnelContext(Device);
WdfSpinLockAcquire(context->ProcessRegistry.Lock);
auto record = procregistry::FindEntry(context->ProcessRegistry.Instance, processId);
if (record == NULL)
{
WdfSpinLockRelease(context->ProcessRegistry.Lock);
DbgPrint("Process query for unknown process\n");
WdfRequestComplete(Request, STATUS_INVALID_HANDLE);
return;
}
//
// Definitively validate output buffer.
//
auto requiredLength = sizeof(ST_QUERY_PROCESS_RESPONSE)
- RTL_FIELD_SIZE(ST_QUERY_PROCESS_RESPONSE, ImageName)
+ record->ImageName.Length;
if (bufferLength < requiredLength)
{
WdfSpinLockRelease(context->ProcessRegistry.Lock);
DbgPrint("Output buffer is too small\n");
WdfRequestComplete(Request, STATUS_BUFFER_TOO_SMALL);
return;
}
//
// Copy data and release lock.
//
auto response = (ST_QUERY_PROCESS_RESPONSE *)buffer;
response->ProcessId = record->ProcessId;
response->ParentProcessId = record->ParentProcessId;
response->Split = (util::SplittingEnabled(record->Settings.Split) ? TRUE : FALSE);
response->ImageNameLength = record->ImageName.Length;
RtlCopyMemory(&response->ImageName, record->ImageName.Buffer, record->ImageName.Length);
WdfSpinLockRelease(context->ProcessRegistry.Lock);
//
// Complete request.
//
WdfRequestCompleteWithInformation(Request, STATUS_SUCCESS, requiredLength);
}
void
ResetComplete
(
WDFDEVICE Device,
WDFREQUEST Request
)
{
auto context = DeviceGetSplitTunnelContext(Device);
//
// We're in the serialized IOCTL handler path so handlers that might update the state are
// locked out from executing.
//
// That's the first reason to not acquire the state lock.
//
// The second reason is that process management logic uses the state lock so we can't be
// holding the lock while trying to tear down the process management subsystem.
//
NTSTATUS status = STATUS_SUCCESS;
switch (context->DriverState.State)
{
case ST_DRIVER_STATE_STARTED:
case ST_DRIVER_STATE_ZOMBIE:
{
break;
}
default:
{
status = ResetInner(context);
}
}
if (NT_SUCCESS(status))
{
DbgPrint("Successfully processed IOCTL_ST_RESET\n");
}
else
{
DbgPrint("Failed to reset driver state\n");
}
WdfRequestComplete(Request, status);
}
} // namespace ioctl
| 37,782
|
C++
|
.cpp
| 1,310
| 23.416794
| 118
| 0.679268
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,028
|
ipaddr.cpp
|
mullvad_win-split-tunnel/src/ipaddr.cpp
|
#include <wdm.h>
#include "ipaddr.h"
#include "util.h"
namespace ip
{
bool
ValidTunnelIpv4Address
(
const ST_IP_ADDRESSES *IpAddresses
)
{
return !util::IsEmptyRange(&IpAddresses->TunnelIpv4, sizeof(IpAddresses->TunnelIpv4));
}
bool
ValidInternetIpv4Address
(
const ST_IP_ADDRESSES *IpAddresses
)
{
return !util::IsEmptyRange(&IpAddresses->InternetIpv4, sizeof(IpAddresses->InternetIpv4));
}
bool
ValidTunnelIpv6Address
(
const ST_IP_ADDRESSES *IpAddresses
)
{
return !util::IsEmptyRange(&IpAddresses->TunnelIpv6, sizeof(IpAddresses->TunnelIpv6));
}
bool
ValidInternetIpv6Address
(
const ST_IP_ADDRESSES *IpAddresses
)
{
return !util::IsEmptyRange(&IpAddresses->InternetIpv6, sizeof(IpAddresses->InternetIpv6));
}
} // namespace ip
| 746
|
C++
|
.cpp
| 38
| 18.263158
| 91
| 0.81339
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,029
|
validation.cpp
|
mullvad_win-split-tunnel/src/validation.cpp
|
#include "validation.h"
#include "defs/config.h"
#include "defs/process.h"
#include "util.h"
#include <ntintsafe.h>
bool
ValidateUserBufferConfiguration
(
void *Buffer,
size_t BufferLength
)
{
auto bufferEnd = (UCHAR*)Buffer + BufferLength;
if (BufferLength < sizeof(ST_CONFIGURATION_HEADER)
|| bufferEnd < (UCHAR*)Buffer)
{
return false;
}
auto header = (ST_CONFIGURATION_HEADER*)Buffer;
if (header->TotalLength != BufferLength)
{
return false;
}
//
// Verify that the entries reside within the buffer
//
SIZE_T entriesSize = 0;
if (STATUS_SUCCESS != RtlSIZETMult(sizeof(ST_CONFIGURATION_ENTRY), header->NumEntries, &entriesSize))
{
return false;
}
void *stringBuffer = nullptr;
const auto status = RtlULongPtrAdd(
(ULONG_PTR)((UCHAR*)Buffer + sizeof(ST_CONFIGURATION_HEADER)),
entriesSize,
(ULONG_PTR*)&stringBuffer
);
if (STATUS_SUCCESS != status || stringBuffer >= bufferEnd)
{
return false;
}
//
// Verify that all strings reside within the string buffer.
//
auto entry = (ST_CONFIGURATION_ENTRY*)(header + 1);
for (auto i = 0; i < header->NumEntries; ++i, ++entry)
{
const auto valid = util::ValidateBufferRange(stringBuffer, bufferEnd,
entry->ImageNameOffset, entry->ImageNameLength);
if (!valid)
{
return false;
}
}
return true;
}
bool
ValidateUserBufferProcesses
(
void *Buffer,
size_t BufferLength
)
{
auto bufferEnd = (UCHAR*)Buffer + BufferLength;
if (BufferLength < sizeof(ST_PROCESS_DISCOVERY_HEADER)
|| bufferEnd < (UCHAR*)Buffer)
{
return false;
}
auto header = (ST_PROCESS_DISCOVERY_HEADER*)Buffer;
if (header->TotalLength != BufferLength)
{
return false;
}
//
// Verify that the entries reside within the buffer
//
SIZE_T entriesSize = 0;
if (STATUS_SUCCESS != RtlSIZETMult(sizeof(ST_PROCESS_DISCOVERY_ENTRY), header->NumEntries, &entriesSize))
{
return false;
}
void *stringBuffer = nullptr;
const auto status = RtlULongPtrAdd(
(ULONG_PTR)((UCHAR*)Buffer + sizeof(ST_PROCESS_DISCOVERY_HEADER)),
entriesSize,
(ULONG_PTR*)&stringBuffer
);
if (STATUS_SUCCESS != status || stringBuffer >= bufferEnd)
{
return false;
}
//
// Verify that all strings reside within the string buffer.
//
auto entry = (ST_PROCESS_DISCOVERY_ENTRY*)(header + 1);
for (auto i = 0; i < header->NumEntries; ++i, ++entry)
{
const auto valid = util::ValidateBufferRange(stringBuffer, bufferEnd,
entry->ImageNameOffset, entry->ImageNameLength);
if (!valid)
{
return false;
}
}
return true;
}
| 2,894
|
C++
|
.cpp
| 107
| 21.224299
| 109
| 0.630033
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,030
|
procmon.cpp
|
mullvad_win-split-tunnel/src/procmon/procmon.cpp
|
#include <ntddk.h>
#include "procmon.h"
#include "context.h"
#include "../util.h"
#include "../defs/types.h"
#include "../trace.h"
#include "procmon.tmh"
namespace procmon
{
namespace
{
//
// PsSetCreateProcessNotifyRoutineEx() is broken so you can't pass context.
//
// This isn't ideal, especially considering creating more than once instance of this "class" will
// send all events to the most recently registered sink.
//
// But... There should never be more than one instance.
// And this lets us keep a familiar interface towards clients, so just roll with it.
//
CONTEXT *g_Context = NULL;
void
SystemProcessEvent
(
PEPROCESS Process,
HANDLE ProcessId,
PPS_CREATE_NOTIFY_INFO CreateInfo
)
{
//
// We want to offload the system thread this is being sent on.
// Build a self-contained event record and queue it to a dedicated thread.
//
PROCESS_EVENT *record = NULL;
if (CreateInfo != NULL)
{
//
// Process is arriving.
//
// First, get the filename so we can determine the size of the final
// buffer that needs to be allocated.
//
UNICODE_STRING *imageName;
auto status = util::GetDevicePathImageName(Process, &imageName);
if (!NT_SUCCESS(status))
{
DbgPrint("Dropping process event\n");
DbgPrint(" Could not determine image filename, status: 0x%X\n", status);
DbgPrint(" PID of arriving process %p\n", ProcessId);
return;
}
auto offsetDetails = util::RoundToMultiple(sizeof(PROCESS_EVENT), TYPE_ALIGNMENT(PROCESS_EVENT_DETAILS));
auto offsetStringBuffer = util::RoundToMultiple(offsetDetails + sizeof(PROCESS_EVENT_DETAILS), TYPE_ALIGNMENT(WCHAR));
auto allocationSize = offsetStringBuffer + imageName->Length;
record = (PROCESS_EVENT *)ExAllocatePoolUninitialized(PagedPool, allocationSize, ST_POOL_TAG);
if (record == NULL)
{
DbgPrint("Dropping process event\n");
DbgPrint(" Failed to allocate memory\n");
DbgPrint(" Imagename of arriving process %wZ\n", imageName);
DbgPrint(" PID of arriving process %p\n", ProcessId);
ExFreePoolWithTag(imageName, ST_POOL_TAG);
return;
}
auto details = (PROCESS_EVENT_DETAILS*)(((CHAR*)record) + offsetDetails);
auto stringBuffer = (WCHAR*)(((CHAR*)record) + offsetStringBuffer);
InitializeListHead(&record->ListEntry);
record->ProcessId = ProcessId;
record->Details = details;
details->ParentProcessId = CreateInfo->ParentProcessId;
details->ImageName.Length = imageName->Length;
details->ImageName.MaximumLength = imageName->Length;
details->ImageName.Buffer = stringBuffer;
RtlCopyMemory(stringBuffer, imageName->Buffer, imageName->Length);
ExFreePoolWithTag(imageName, ST_POOL_TAG);
}
else
{
//
// Process is departing.
//
record = (PROCESS_EVENT *)ExAllocatePoolUninitialized(PagedPool, sizeof(PROCESS_EVENT), ST_POOL_TAG);
if (record == NULL)
{
DbgPrint("Dropping process event\n");
DbgPrint(" Failed to allocate memory\n");
DbgPrint(" PID of departing process %p\n", ProcessId);
return;
}
InitializeListHead(&record->ListEntry);
record->ProcessId = ProcessId;
record->Details = NULL;
}
//
// Queue to worker thread.
//
WdfWaitLockAcquire(g_Context->QueueLock, NULL);
InsertTailList(&g_Context->EventQueue, &record->ListEntry);
if (g_Context->DispatchingEnabled)
{
KeSetEvent(&g_Context->WakeUpWorker, 0, FALSE);
}
WdfWaitLockRelease(g_Context->QueueLock);
}
void
DispatchWorker
(
PVOID StartContext
)
{
auto context = (CONTEXT *)StartContext;
for (;;)
{
KeWaitForSingleObject(&context->WakeUpWorker, Executive, KernelMode, FALSE, NULL);
WdfWaitLockAcquire(context->QueueLock, NULL);
if (0 != KeReadStateEvent(&context->ExitWorker))
{
WdfWaitLockRelease(context->QueueLock);
PsTerminateSystemThread(STATUS_SUCCESS);
return;
}
//
// Reparent the queue in order to release the lock sooner.
//
LIST_ENTRY queue;
util::ReparentList(&queue, &context->EventQueue);
KeClearEvent(&context->WakeUpWorker);
WdfWaitLockRelease(context->QueueLock);
//
// There are one or more records queued.
// Process all available records.
//
LIST_ENTRY *record;
while ((record = RemoveHeadList(&queue)) != &queue)
{
context->ProcessEventSink((PROCESS_EVENT*)record, context->SinkContext);
ExFreePoolWithTag(record, ST_POOL_TAG);
}
}
}
} // anonymous namespace
NTSTATUS
Initialize
(
CONTEXT **Context,
PROCESS_EVENT_SINK ProcessEventSink,
void *SinkContext
)
{
*Context = NULL;
bool notifyRoutineRegistered = false;
auto context = (CONTEXT*)ExAllocatePoolUninitialized(NonPagedPool, sizeof(CONTEXT), ST_POOL_TAG);
if (NULL == context)
{
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory(context, sizeof(*context));
context->ProcessEventSink = ProcessEventSink;
context->SinkContext = SinkContext;
InitializeListHead(&context->EventQueue);
KeInitializeEvent(&context->ExitWorker, NotificationEvent, FALSE);
KeInitializeEvent(&context->WakeUpWorker, NotificationEvent, FALSE);
auto status = WdfWaitLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &context->QueueLock);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfWaitLockCreate() failed 0x%X\n", status);
context->QueueLock = NULL;
goto Abort;
}
g_Context = context;
//
// It's alright to register for notifications before starting the worker thread.
//
// Events that come in before the thread is created are queued.
// So no event will be lost.
//
// Also, the thread doesn't own the queued events so nothing is leaked even
// if the thread fails to process events in a timely manner, or at all.
//
// Also, clean-up is simpler if thread creation is the last fallible operation.
//
status = PsSetCreateProcessNotifyRoutineEx(SystemProcessEvent, FALSE);
if (!NT_SUCCESS(status))
{
DbgPrint("PsSetCreateProcessNotifyRoutineEx() failed 0x%X\n", status);
goto Abort;
}
notifyRoutineRegistered = true;
//
// Create the thread that will be servicing events.
//
OBJECT_ATTRIBUTES threadAttributes;
InitializeObjectAttributes(&threadAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
HANDLE threadHandle;
status = PsCreateSystemThread
(
&threadHandle,
THREAD_ALL_ACCESS,
&threadAttributes,
NULL,
NULL,
DispatchWorker,
context
);
if (!NT_SUCCESS(status))
{
DbgPrint("PsCreateSystemThread() failed 0x%X\n", status);
DbgPrint("Could not create process monitoring thread\n");
goto Abort;
}
//
// ObReference... will never fail if the handle is valid.
//
status = ObReferenceObjectByHandle
(
threadHandle,
THREAD_ALL_ACCESS,
NULL,
KernelMode,
(PVOID *)&context->DispatchWorker,
NULL
);
ZwClose(threadHandle);
*Context = context;
return STATUS_SUCCESS;
Abort:
if (notifyRoutineRegistered)
{
PsSetCreateProcessNotifyRoutineEx(SystemProcessEvent, TRUE);
//
// Drain event queue to avoid leaking events.
//
LIST_ENTRY *record;
while ((record = RemoveHeadList(&context->EventQueue)) != &context->EventQueue)
{
ExFreePoolWithTag(record, ST_POOL_TAG);
}
}
if (context->QueueLock != NULL)
{
WdfObjectDelete(context->QueueLock);
}
ExFreePoolWithTag(context, ST_POOL_TAG);
g_Context = NULL;
return status;
}
void
TearDown
(
CONTEXT **Context
)
{
auto context = *Context;
//
// Deregister notify routine so we stop queuing events.
// This can never fail according to documentation.
//
PsSetCreateProcessNotifyRoutineEx(SystemProcessEvent, TRUE);
//
// Tell worker thread to exit and wait for it to happen.
//
WdfWaitLockAcquire(context->QueueLock, NULL);
KeSetEvent(&context->ExitWorker, 0, FALSE);
KeSetEvent(&context->WakeUpWorker, 1, FALSE);
WdfWaitLockRelease(context->QueueLock);
KeWaitForSingleObject(context->DispatchWorker, Executive, KernelMode, FALSE, NULL);
ObDereferenceObject(context->DispatchWorker);
//
// Drain event queue to avoid leaking events.
//
LIST_ENTRY *record;
while ((record = RemoveHeadList(&context->EventQueue)) != &context->EventQueue)
{
ExFreePoolWithTag(record, ST_POOL_TAG);
}
//
// Release remaining resources.
//
WdfObjectDelete(context->QueueLock);
ExFreePoolWithTag(context, ST_POOL_TAG);
*Context = NULL;
}
void
EnableDispatching
(
CONTEXT *Context
)
{
WdfWaitLockAcquire(Context->QueueLock, NULL);
Context->DispatchingEnabled = true;
if (!IsListEmpty(&Context->EventQueue))
{
KeSetEvent(&Context->WakeUpWorker, 0, FALSE);
}
WdfWaitLockRelease(Context->QueueLock);
}
}
| 9,537
|
C++
|
.cpp
| 297
| 25.784512
| 126
| 0.661084
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,031
|
procmgmt.cpp
|
mullvad_win-split-tunnel/src/procmgmt/procmgmt.cpp
|
#include "procmgmt.h"
#include "context.h"
#include "../util.h"
#include "../defs/events.h"
#include "../eventing/builder.h"
#include "../trace.h"
#include "procmgmt.tmh"
namespace procmgmt
{
namespace
{
//
// EmitAddEntryErrorEvents()
//
// During process arrival event processing, it may happen that `procregistry::AddEntry()`
// fails to complete successfully.
//
// This has to be communicated through an event.
//
// Additionally, if the arriving process would have been split, then this is a compound
// failure that is communicated separately.
//
void
EmitAddEntryErrorEvents
(
eventing::CONTEXT *Eventing,
NTSTATUS ErrorCode,
HANDLE ProcessId,
LOWER_UNICODE_STRING *ImageName,
bool EmitSplittingEvent
)
{
NT_ASSERT(!NT_SUCCESS(ErrorCode));
DbgPrint("Failed to add entry for arriving process\n");
DbgPrint(" Status: 0x%X\n", ErrorCode);
DbgPrint(" PID: %p\n", ProcessId);
DbgPrint(" Imagename: %wZ\n", (UNICODE_STRING*)ImageName);
util::StopIfDebugBuild();
DECLARE_CONST_UNICODE_STRING(errorMessage, L"Failed in call to procregistry::AddEntry()");
auto errorEvent = eventing::BuildErrorMessageEvent(ErrorCode, &errorMessage);
eventing::Emit(Eventing, &errorEvent);
if (!EmitSplittingEvent)
{
return;
}
auto splittingErrorEvent = eventing::BuildStartSplittingErrorEvent
(
ProcessId,
ImageName
);
eventing::Emit(Eventing, &splittingErrorEvent);
}
//
// ValidateCollision()
//
// Find and validate existing entry in process registry that prevented the insertion
// of a new entry, because they share the same PID.
//
bool
ValidateCollision
(
CONTEXT *Context,
const procregistry::PROCESS_REGISTRY_ENTRY *newEntry
)
{
auto processRegistry = Context->ProcessRegistry;
const auto existingEntry = procregistry::FindEntry(processRegistry->Instance, newEntry->ProcessId);
if (existingEntry == NULL)
{
DbgPrint("Validate PR collision - could not look up existing entry\n");
goto Abort_unlock_break;
}
if (existingEntry->ParentProcessId != newEntry->ParentProcessId)
{
DbgPrint("Validate PR collision - different parent process\n");
goto Abort_unlock_break;
}
if (existingEntry->ImageName.Length == 0)
{
if (newEntry->ImageName.Length != 0)
{
DbgPrint("Validate PR collision - "\
"registered entry is without image name but proposed entry is not\n");
goto Abort_unlock_break;
}
goto Approved;
}
if (!util::Equal(&existingEntry->ImageName, &newEntry->ImageName))
{
DbgPrint("Validate PR collision - mismatched image name\n");
goto Abort_unlock_break;
}
Approved:
DbgPrint("Process registry collision validation has succeeded\n");
return true;
Abort_unlock_break:
DbgPrint("Process registry collision validation has failed\n");
DbgPrint("Existing entry at %p\n", existingEntry);
DbgPrint("New proposed entry at %p\n", newEntry);
util::StopIfDebugBuild();
return false;
}
struct ArrivalEvent
{
UINT32 SplittingReason;
bool EmitEvent;
//
// Successfully adding a new entry in the process registry makes the
// registry take ownership of the imagename buffer passed.
//
// Therefore, if we need to emit a splitting event for a successful addition,
// we have to duplicate the imagename here to preserve it.
//
LOWER_UNICODE_STRING Imagename;
};
void
EvaluateSplitting
(
CONTEXT *Context,
procregistry::PROCESS_REGISTRY_ENTRY *RegistryEntry,
ArrivalEvent *ArrivalEvent
)
{
auto registeredImage = Context->RegisteredImage->Instance;
if (registeredimage::HasEntryExact(registeredImage, &RegistryEntry->ImageName))
{
RegistryEntry->Settings.Split = ST_PROCESS_SPLIT_STATUS_ON_BY_CONFIG;
ArrivalEvent->SplittingReason |= ST_SPLITTING_REASON_BY_CONFIG;
goto Duplicate_imagename;
}
//
// Note that we're providing an entry which is not yet added to the registry.
// This may seem wrong but is totally fine.
//
auto processRegistry = Context->ProcessRegistry;
auto parent = procregistry::GetParentEntry(processRegistry->Instance, RegistryEntry);
if (parent == NULL || !util::SplittingEnabled(parent->Settings.Split))
{
return;
}
RegistryEntry->Settings.Split = ST_PROCESS_SPLIT_STATUS_ON_BY_INHERITANCE;
ArrivalEvent->SplittingReason |= ST_SPLITTING_REASON_BY_INHERITANCE;
Duplicate_imagename:
ArrivalEvent->EmitEvent = true;
auto status = util::DuplicateString
(
&ArrivalEvent->Imagename,
&RegistryEntry->ImageName,
ST_PAGEABLE::NO
);
if (NT_SUCCESS(status))
{
return;
}
DbgPrint("Cannot emit splitting event for arriving process due to resource exhaustion\n");
ArrivalEvent->EmitEvent = false;
}
void
HandleProcessArriving
(
CONTEXT *Context,
const procmon::PROCESS_EVENT *Record
)
{
//
// State lock is held and is locking out IOCTL handlers.
//
// The process registry lock will be required for updating the process registry.
// The configuration lock won't be required.
//
auto processRegistry = Context->ProcessRegistry;
procregistry::PROCESS_REGISTRY_ENTRY registryEntry = { 0 };
auto status = procregistry::InitializeEntry
(
processRegistry->Instance,
Record->Details->ParentProcessId,
Record->ProcessId,
ST_PROCESS_SPLIT_STATUS_OFF,
&(Record->Details->ImageName),
®istryEntry
);
if (!NT_SUCCESS(status))
{
DbgPrint("Failed to initialize entry for arriving process\n");
DbgPrint(" Status: 0x%X\n", status);
DbgPrint(" PID: %p\n", Record->ProcessId);
DbgPrint(" Imagename: %wZ\n", &(Record->Details->ImageName));
return;
}
ArrivalEvent arrivalEvent =
{
.SplittingReason = ST_SPLITTING_REASON_PROCESS_ARRIVING,
.EmitEvent = false,
.Imagename = { 0, 0, NULL }
};
if (Context->EngagedStateActive(Context->CallbackContext))
{
EvaluateSplitting(Context, ®istryEntry, &arrivalEvent);
}
//
// Insert entry into registry.
//
WdfSpinLockAcquire(processRegistry->Lock);
status = procregistry::AddEntry(processRegistry->Instance, ®istryEntry);
WdfSpinLockRelease(processRegistry->Lock);
if (NT_SUCCESS(status))
{
//
// Entry was successfully added and we no longer own the imagename buffer
// referenced by the registry entry.
//
if (arrivalEvent.EmitEvent)
{
auto splittingEvent = eventing::BuildStartSplittingEvent
(
Record->ProcessId,
(ST_SPLITTING_STATUS_CHANGE_REASON)arrivalEvent.SplittingReason,
&arrivalEvent.Imagename
);
eventing::Emit(Context->Eventing, &splittingEvent);
}
}
else if (status == STATUS_DUPLICATE_OBJECTID)
{
//
// During driver initialization it may happen that the process registry is
// populated with processes that are also queued to the current function.
//
// This is usually fine, but has to be verified to ensure it's an exact duplicate
// and not just a PID collision.
//
// The latter would indicate that events are not being queued in an orderly fashion
// or went missing alltogether.
//
// In case the collision is approved - Do NOT emit an event since the corresponding
// event will already have been emitted.
//
const auto validationStatus = ValidateCollision(Context, ®istryEntry);
if (!validationStatus)
{
EmitAddEntryErrorEvents(Context->Eventing, status, registryEntry.ProcessId,
®istryEntry.ImageName, arrivalEvent.EmitEvent);
}
procregistry::ReleaseEntry(®istryEntry);
}
else
{
//
// General error handling.
//
EmitAddEntryErrorEvents(Context->Eventing, status, registryEntry.ProcessId,
®istryEntry.ImageName, arrivalEvent.EmitEvent);
procregistry::ReleaseEntry(®istryEntry);
}
//
// Clean up event data.
//
if (arrivalEvent.Imagename.Buffer != NULL)
{
util::FreeStringBuffer(&arrivalEvent.Imagename);
}
//
// No need to update the firewall because the arriving process won't
// have any existing connections.
//
}
NTSTATUS
UpdateFirewallDepartingProcess
(
CONTEXT *Context,
procregistry::PROCESS_REGISTRY_ENTRY *registryEntry
)
{
//
// It's inferred that we're in the engaged state.
// Because we found a process record that has firewall state.
// But leave this assert here for now.
//
NT_ASSERT(Context->EngagedStateActive(Context->CallbackContext));
auto status = firewall::TransactionBegin(Context->Firewall);
if (!NT_SUCCESS(status))
{
DbgPrint("Failed to create firewall transaction: 0x%X\n", status);
return status;
}
status = firewall::RegisterAppBecomingUnsplitTx(Context->Firewall, ®istryEntry->ImageName);
if (!NT_SUCCESS(status))
{
DbgPrint("Failed to update firewall: 0x%X\n", status);
auto s2 = firewall::TransactionAbort(Context->Firewall);
if (!NT_SUCCESS(s2))
{
DbgPrint("Failed to abort firewall transaction: 0x%X\n", s2);
}
return status;
}
status = firewall::TransactionCommit(Context->Firewall);
if (!NT_SUCCESS(status))
{
DbgPrint("Failed to commit firewall transaction: 0x%X\n", status);
auto s2 = firewall::TransactionAbort(Context->Firewall);
if (!NT_SUCCESS(s2))
{
DbgPrint("Failed to abort firewall transaction: 0x%X\n", s2);
}
}
return status;
}
void
HandleProcessDeparting
(
CONTEXT *Context,
const procmon::PROCESS_EVENT *Record
)
{
//DbgPrint("Process departing: 0x%X\n", Record->ProcessId);
//
// We're still at PASSIVE_LEVEL and the state lock is held.
// IOCTL handlers are locked out.
//
// Complete all processing and acquire the spin lock only when
// updating the process tree.
//
auto processRegistry = Context->ProcessRegistry;
auto registryEntry = procregistry::FindEntry(processRegistry->Instance, Record->ProcessId);
if (NULL == registryEntry)
{
DbgPrint("Received process-departing event for unknown PID\n");
return;
}
if (registryEntry->Settings.HasFirewallState)
{
auto status = UpdateFirewallDepartingProcess(Context, registryEntry);
eventing::RAW_EVENT *evt = NULL;
if (NT_SUCCESS(status))
{
evt = eventing::BuildStopSplittingEvent(registryEntry->ProcessId,
ST_SPLITTING_REASON_PROCESS_DEPARTING, ®istryEntry->ImageName);
}
else
{
evt = eventing::BuildStopSplittingErrorEvent(registryEntry->ProcessId,
®istryEntry->ImageName);
}
eventing::Emit(Context->Eventing, &evt);
}
else if (util::SplittingEnabled(registryEntry->Settings.Split))
{
auto splittingEvent = eventing::BuildStopSplittingEvent(Record->ProcessId,
ST_SPLITTING_REASON_PROCESS_DEPARTING, ®istryEntry->ImageName);
eventing::Emit(Context->Eventing, &splittingEvent);
}
WdfSpinLockAcquire(processRegistry->Lock);
const bool deleteSuccessful = procregistry::DeleteEntry(processRegistry->Instance, registryEntry);
WdfSpinLockRelease(processRegistry->Lock);
NT_ASSERT(deleteSuccessful);
//
// This is unlikely to ever be an issue,
// but if it was, we'd want to know about it.
//
if (!deleteSuccessful)
{
DECLARE_CONST_UNICODE_STRING(errorMessage, L"Failed in call to procregistry::DeleteEntry()");
auto errorEvent = eventing::BuildErrorMessageEvent(STATUS_UNSUCCESSFUL, &errorMessage);
eventing::Emit(Context->Eventing, &errorEvent);
}
}
void
NTAPI
ProcessEventSink
(
const procmon::PROCESS_EVENT *Event,
void *Context
)
{
auto context = (CONTEXT*)Context;
const auto arriving = (Event->Details != NULL);
context->AcquireStateLock(context->CallbackContext);
if (arriving)
{
HandleProcessArriving(context, Event);
}
else
{
HandleProcessDeparting(context, Event);
}
context->ReleaseStateLock(context->CallbackContext);
procbroker::Publish(context->ProcessEventBroker, Event->ProcessId, arriving);
}
} // anonymous namespace
NTSTATUS
Initialize
(
CONTEXT **Context,
procbroker::CONTEXT *ProcessEventBroker,
PROCESS_REGISTRY_MGMT *ProcessRegistry,
REGISTERED_IMAGE_MGMT *RegisteredImage,
eventing::CONTEXT *Eventing,
firewall::CONTEXT *Firewall,
ACQUIRE_STATE_LOCK_FN AcquireStateLock,
RELEASE_STATE_LOCK_FN ReleaseStateLock,
ENGAGED_STATE_ACTIVE_FN EngagedStateActive,
void *CallbackContext
)
{
auto context = (CONTEXT*)ExAllocatePoolUninitialized(NonPagedPool, sizeof(CONTEXT), ST_POOL_TAG);
if (NULL == context)
{
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory(context, sizeof(*context));
auto status = procmon::Initialize(&context->ProcessMonitor, ProcessEventSink, context);
if (!NT_SUCCESS(status))
{
DbgPrint("procmon::Initialize() failed 0x%X\n", status);
ExFreePoolWithTag(context, ST_POOL_TAG);
return status;
}
context->ProcessEventBroker = ProcessEventBroker;
context->ProcessRegistry = ProcessRegistry;
context->RegisteredImage = RegisteredImage;
context->Eventing = Eventing;
context->Firewall = Firewall;
context->AcquireStateLock = AcquireStateLock;
context->ReleaseStateLock = ReleaseStateLock;
context->EngagedStateActive = EngagedStateActive;
context->CallbackContext = CallbackContext;
*Context = context;
return STATUS_SUCCESS;
}
void
TearDown
(
CONTEXT **Context
)
{
auto context = *Context;
procmon::TearDown(&context->ProcessMonitor);
ExFreePoolWithTag(context, ST_POOL_TAG);
*Context = NULL;
}
void
Activate
(
CONTEXT *Context
)
{
procmon::EnableDispatching(Context->ProcessMonitor);
}
} // namespace procmgmt
| 14,525
|
C++
|
.cpp
| 450
| 26.588889
| 103
| 0.686716
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,032
|
eventing.cpp
|
mullvad_win-split-tunnel/src/eventing/eventing.cpp
|
#include "eventing.h"
#include "context.h"
#include "builder.h"
#include "../defs/types.h"
#include "../trace.h"
#include "eventing.tmh"
namespace eventing
{
namespace
{
void EnqueueEvent
(
CONTEXT *Context,
RAW_EVENT *evt
)
{
WdfSpinLockAcquire(Context->EventQueueLock);
const SIZE_T MAX_QUEUED_EVENTS = 100;
//
// Discard oldest events if events are too numerous.
//
while (Context->NumEvents >= MAX_QUEUED_EVENTS)
{
auto oldEvent = (RAW_EVENT*)RemoveHeadList(&Context->EventQueue);
--Context->NumEvents;
ReleaseEvent(&oldEvent);
}
//
// Add new event at end of queue.
//
InsertTailList(&Context->EventQueue, &evt->ListEntry);
++Context->NumEvents;
WdfSpinLockRelease(Context->EventQueueLock);
}
void CompleteRequestReleaseEvent
(
WDFREQUEST Request,
void *RequestBuffer,
RAW_EVENT *Event
)
{
RtlCopyMemory(RequestBuffer, Event->Buffer, Event->BufferSize);
WdfRequestCompleteWithInformation(Request, STATUS_SUCCESS, Event->BufferSize);
ReleaseEvent(&Event);
}
} // anonymous namespace
NTSTATUS
Initialize
(
CONTEXT **Context,
WDFDEVICE Device
)
{
*Context = NULL;
auto context = (CONTEXT*)ExAllocatePoolUninitialized(NonPagedPool, sizeof(CONTEXT), ST_POOL_TAG);
if (NULL == context)
{
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory(context, sizeof(*context));
InitializeListHead(&context->EventQueue);
auto status = WdfSpinLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &context->EventQueueLock);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfSpinLockCreate() failed 0x%X\n", status);
goto Abort;
}
WDF_IO_QUEUE_CONFIG queueConfig;
WDF_IO_QUEUE_CONFIG_INIT
(
&queueConfig,
WdfIoQueueDispatchManual
);
queueConfig.PowerManaged = WdfFalse;
status = WdfIoQueueCreate
(
Device,
&queueConfig,
WDF_NO_OBJECT_ATTRIBUTES,
&context->RequestQueue
);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfIoQueueCreate() failed 0x%X\n", status);
goto Abort_delete_lock;
}
*Context = context;
return STATUS_SUCCESS;
Abort_delete_lock:
WdfObjectDelete(context->EventQueueLock);
Abort:
ExFreePoolWithTag(context, ST_POOL_TAG);
return status;
}
void
TearDown
(
CONTEXT **Context
)
{
auto context = *Context;
//
// Discard and release all queued events.
// Don't use the lock because if there's contension we've already failed.
//
while (FALSE == IsListEmpty(&context->EventQueue))
{
auto evt = (RAW_EVENT*)RemoveHeadList(&context->EventQueue);
ReleaseEvent(&evt);
}
context->NumEvents = 0;
//
// Cancel all queued requests.
//
WDFREQUEST pendedRequest;
for (;;)
{
auto status = WdfIoQueueRetrieveNextRequest(context->RequestQueue, &pendedRequest);
if (!NT_SUCCESS(status) || pendedRequest == NULL)
{
break;
}
WdfRequestComplete(pendedRequest, STATUS_CANCELLED);
}
//
// Delete all objects.
//
WdfObjectDelete(context->RequestQueue);
WdfObjectDelete(context->EventQueueLock);
//
// Release context.
//
ExFreePoolWithTag(context, ST_POOL_TAG);
*Context = NULL;
}
void
Emit
(
CONTEXT *Context,
RAW_EVENT **Event
)
{
auto evt = *Event;
if (evt == NULL)
{
return;
}
*Event = NULL;
WDFREQUEST pendedRequest;
void *buffer;
//
// Look for a pended request with a correctly sized buffer.
//
// Fail all requests we encounter that have tiny buffers.
// User mode should know better.
//
for (;;)
{
auto status = WdfIoQueueRetrieveNextRequest(Context->RequestQueue, &pendedRequest);
if (!NT_SUCCESS(status) || pendedRequest == NULL)
{
EnqueueEvent(Context, evt);
return;
}
status = WdfRequestRetrieveOutputBuffer
(
pendedRequest,
evt->BufferSize,
&buffer,
NULL
);
if (NT_SUCCESS(status))
{
break;
}
WdfRequestComplete(pendedRequest, status);
}
CompleteRequestReleaseEvent(pendedRequest, buffer, evt);
}
void
CollectOne
(
CONTEXT *Context,
WDFREQUEST Request
)
{
RAW_EVENT *evt = NULL;
WdfSpinLockAcquire(Context->EventQueueLock);
if (FALSE == IsListEmpty(&Context->EventQueue))
{
evt = (RAW_EVENT*)RemoveHeadList(&Context->EventQueue);
--Context->NumEvents;
}
WdfSpinLockRelease(Context->EventQueueLock);
if (evt == NULL)
{
auto status = WdfRequestForwardToIoQueue(Request, Context->RequestQueue);
if (!NT_SUCCESS(status))
{
DbgPrint("Failed to pend event request\n");
WdfRequestComplete(Request, STATUS_INTERNAL_ERROR);
}
return;
}
//
// Acquire and validate request buffer.
//
void *buffer;
auto status = WdfRequestRetrieveOutputBuffer
(
Request,
evt->BufferSize,
&buffer,
NULL
);
if (!NT_SUCCESS(status))
{
WdfRequestComplete(Request, status);
//
// Put the event back.
//
WdfSpinLockAcquire(Context->EventQueueLock);
InsertHeadList(&Context->EventQueue, &evt->ListEntry);
++Context->NumEvents;
WdfSpinLockRelease(Context->EventQueueLock);
return;
}
CompleteRequestReleaseEvent(Request, buffer, evt);
}
} // eventing
| 5,633
|
C++
|
.cpp
| 230
| 18.878261
| 101
| 0.646539
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,033
|
builder.cpp
|
mullvad_win-split-tunnel/src/eventing/builder.cpp
|
#include "builder.h"
namespace eventing
{
namespace
{
bool
BuildSplittingEvent
(
HANDLE ProcessId,
ST_SPLITTING_STATUS_CHANGE_REASON Reason,
LOWER_UNICODE_STRING *ImageName,
bool Start,
void **Buffer,
size_t *BufferSize
)
{
auto headerSize = FIELD_OFFSET(ST_EVENT_HEADER, EventData);
auto eventSize = FIELD_OFFSET(ST_SPLITTING_EVENT, ImageName) + ImageName->Length;
auto allocationSize = headerSize + eventSize;
auto buffer = ExAllocatePoolUninitialized(NonPagedPool, allocationSize, ST_POOL_TAG);
if (buffer == NULL)
{
return false;
}
auto header = (ST_EVENT_HEADER*)buffer;
auto evt = (ST_SPLITTING_EVENT*)(((UCHAR*)buffer) + FIELD_OFFSET(ST_EVENT_HEADER, EventData));
header->EventId = (Start ? ST_EVENT_ID_START_SPLITTING_PROCESS : ST_EVENT_ID_STOP_SPLITTING_PROCESS);
header->EventSize = eventSize;
evt->ProcessId = ProcessId;
evt->Reason = Reason;
evt->ImageNameLength = ImageName->Length;
RtlCopyMemory(evt->ImageName, ImageName->Buffer, ImageName->Length);
*Buffer = buffer;
*BufferSize = allocationSize;
return true;
}
bool
BuildSplittingErrorEvent
(
HANDLE ProcessId,
LOWER_UNICODE_STRING *ImageName,
bool Start,
void **Buffer,
size_t *BufferSize
)
{
auto headerSize = FIELD_OFFSET(ST_EVENT_HEADER, EventData);
auto eventSize = FIELD_OFFSET(ST_SPLITTING_ERROR_EVENT, ImageName) + ImageName->Length;
auto allocationSize = headerSize + eventSize;
auto buffer = ExAllocatePoolUninitialized(NonPagedPool, allocationSize, ST_POOL_TAG);
if (buffer == NULL)
{
return false;
}
auto header = (ST_EVENT_HEADER*)buffer;
auto evt = (ST_SPLITTING_ERROR_EVENT*)(((UCHAR*)buffer) + FIELD_OFFSET(ST_EVENT_HEADER, EventData));
header->EventId = (Start ? ST_EVENT_ID_ERROR_START_SPLITTING_PROCESS : ST_EVENT_ID_ERROR_STOP_SPLITTING_PROCESS);
header->EventSize = eventSize;
evt->ProcessId = ProcessId;
evt->ImageNameLength = ImageName->Length;
RtlCopyMemory(evt->ImageName, ImageName->Buffer, ImageName->Length);
*Buffer = buffer;
*BufferSize = allocationSize;
return true;
}
RAW_EVENT*
WrapEvent
(
void *Buffer,
size_t BufferSize
)
{
auto evt = (RAW_EVENT*)ExAllocatePoolUninitialized(NonPagedPool, sizeof(RAW_EVENT), ST_POOL_TAG);
if (evt == NULL)
{
ExFreePoolWithTag(Buffer, ST_POOL_TAG);
return NULL;
}
InitializeListHead(&evt->ListEntry);
evt->Buffer = Buffer;
evt->BufferSize = BufferSize;
return evt;
}
} // anonymous namespace
RAW_EVENT*
BuildStartSplittingEvent
(
HANDLE ProcessId,
ST_SPLITTING_STATUS_CHANGE_REASON Reason,
LOWER_UNICODE_STRING *ImageName
)
{
void *buffer;
size_t bufferSize;
auto status = BuildSplittingEvent(ProcessId, Reason, ImageName, true, &buffer, &bufferSize);
if (!status)
{
return NULL;
}
return WrapEvent(buffer, bufferSize);
}
RAW_EVENT*
BuildStopSplittingEvent
(
HANDLE ProcessId,
ST_SPLITTING_STATUS_CHANGE_REASON Reason,
LOWER_UNICODE_STRING *ImageName
)
{
void *buffer;
size_t bufferSize;
auto status = BuildSplittingEvent(ProcessId, Reason, ImageName, false, &buffer, &bufferSize);
if (!status)
{
return NULL;
}
return WrapEvent(buffer, bufferSize);
}
RAW_EVENT*
BuildStartSplittingErrorEvent
(
HANDLE ProcessId,
LOWER_UNICODE_STRING *ImageName
)
{
void *buffer;
size_t bufferSize;
auto status = BuildSplittingErrorEvent(ProcessId, ImageName, false, &buffer, &bufferSize);
if (!status)
{
return NULL;
}
return WrapEvent(buffer, bufferSize);
}
RAW_EVENT*
BuildStopSplittingErrorEvent
(
HANDLE ProcessId,
LOWER_UNICODE_STRING *ImageName
)
{
void *buffer;
size_t bufferSize;
auto status = BuildSplittingErrorEvent(ProcessId, ImageName, false, &buffer, &bufferSize);
if (!status)
{
return NULL;
}
return WrapEvent(buffer, bufferSize);
}
RAW_EVENT*
BuildErrorMessageEvent
(
NTSTATUS Status,
const UNICODE_STRING *ErrorMessage
)
{
auto headerSize = FIELD_OFFSET(ST_EVENT_HEADER, EventData);
auto eventSize = FIELD_OFFSET(ST_ERROR_MESSAGE_EVENT, ErrorMessage) + ErrorMessage->Length;
auto allocationSize = headerSize + eventSize;
auto buffer = ExAllocatePoolUninitialized(NonPagedPool, allocationSize, ST_POOL_TAG);
if (buffer == NULL)
{
return NULL;
}
auto header = (ST_EVENT_HEADER*)buffer;
auto evt = (ST_ERROR_MESSAGE_EVENT*)(((UCHAR*)buffer) + FIELD_OFFSET(ST_EVENT_HEADER, EventData));
header->EventId = ST_EVENT_ID_ERROR_MESSAGE;
header->EventSize = eventSize;
evt->Status = Status;
evt->ErrorMessageLength = ErrorMessage->Length;
RtlCopyMemory(evt->ErrorMessage, ErrorMessage->Buffer, ErrorMessage->Length);
return WrapEvent(buffer, allocationSize);
}
void
ReleaseEvent
(
RAW_EVENT **Event
)
{
auto evt = *Event;
if (evt == NULL)
{
return;
}
*Event = NULL;
ExFreePoolWithTag(evt->Buffer, ST_POOL_TAG);
ExFreePoolWithTag(evt, ST_POOL_TAG);
}
} // namespace eventing
| 4,801
|
C++
|
.cpp
| 190
| 23.210526
| 114
| 0.77124
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,034
|
procbroker.cpp
|
mullvad_win-split-tunnel/src/procbroker/procbroker.cpp
|
#include "procbroker.h"
#include "context.h"
#include "../defs/types.h"
#include "../trace.h"
#include "procbroker.tmh"
namespace procbroker
{
NTSTATUS
Initialize
(
CONTEXT **Context
)
{
auto context = (CONTEXT*)ExAllocatePoolUninitialized(PagedPool, sizeof(CONTEXT), ST_POOL_TAG);
if (NULL == context)
{
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory(context, sizeof(*context));
auto status = WdfWaitLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &context->SubscriptionsLock);
if (!NT_SUCCESS(status))
{
DbgPrint("WdfWaitLockCreate() failed 0x%X\n", status);
ExFreePoolWithTag(context, ST_POOL_TAG);
return status;
}
InitializeListHead(&context->Subscriptions);
*Context = context;
return STATUS_SUCCESS;
}
void
TearDown
(
CONTEXT **Context
)
{
auto context = *Context;
LIST_ENTRY *record;
while ((record = RemoveHeadList(&context->Subscriptions)) != &context->Subscriptions)
{
ExFreePoolWithTag(record, ST_POOL_TAG);
}
WdfObjectDelete(context->SubscriptionsLock);
ExFreePoolWithTag(context, ST_POOL_TAG);
*Context = NULL;
}
NTSTATUS
Subscribe
(
CONTEXT *Context,
ST_PB_CALLBACK Callback,
void *ClientContext
)
{
auto sub = (SUBSCRIPTION*)ExAllocatePoolUninitialized(PagedPool, sizeof(SUBSCRIPTION), ST_POOL_TAG);
if (NULL == sub)
{
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory(sub, sizeof(SUBSCRIPTION));
sub->Callback = Callback;
sub->ClientContext = ClientContext;
WdfWaitLockAcquire(Context->SubscriptionsLock, NULL);
InsertTailList(&Context->Subscriptions, &sub->ListEntry);
WdfWaitLockRelease(Context->SubscriptionsLock);
return STATUS_SUCCESS;
}
void
CancelSubscription
(
CONTEXT *Context,
ST_PB_CALLBACK Callback
)
{
WdfWaitLockAcquire(Context->SubscriptionsLock, NULL);
for (auto entry = Context->Subscriptions.Flink;
entry != &Context->Subscriptions;
entry = entry->Flink)
{
if (((SUBSCRIPTION*)entry)->Callback == Callback)
{
RemoveEntryList(entry);
break;
}
}
WdfWaitLockRelease(Context->SubscriptionsLock);
}
void
Publish
(
CONTEXT *Context,
HANDLE ProcessId,
bool Arriving
)
{
WdfWaitLockAcquire(Context->SubscriptionsLock, NULL);
for (auto entry = Context->Subscriptions.Flink;
entry != &Context->Subscriptions;
entry = entry->Flink)
{
auto sub = (SUBSCRIPTION*)entry;
sub->Callback(ProcessId, Arriving, sub->ClientContext);
}
WdfWaitLockRelease(Context->SubscriptionsLock);
}
} // namespace procbroker
| 2,663
|
C++
|
.cpp
| 106
| 20.933962
| 104
| 0.709012
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,035
|
procregistry.cpp
|
mullvad_win-split-tunnel/src/containers/procregistry.cpp
|
#include <ntifs.h>
#include "procregistry.h"
#include "../util.h"
namespace procregistry
{
struct CONTEXT
{
RTL_AVL_TABLE Tree;
ST_PAGEABLE Pageable;
};
namespace
{
RTL_GENERIC_COMPARE_RESULTS
TreeCompareRoutine
(
__in struct _RTL_AVL_TABLE *Table,
__in PVOID FirstStruct,
__in PVOID SecondStruct
)
{
UNREFERENCED_PARAMETER(Table);
auto first = ((PROCESS_REGISTRY_ENTRY*)FirstStruct)->ProcessId;
auto second = ((PROCESS_REGISTRY_ENTRY*)SecondStruct)->ProcessId;
if (first < second)
{
return GenericLessThan;
}
if (first > second)
{
return GenericGreaterThan;
}
return GenericEqual;
}
PVOID
TreeAllocateRoutineNonPaged
(
__in struct _RTL_AVL_TABLE *Table,
__in CLONG ByteSize
)
{
UNREFERENCED_PARAMETER(Table);
return ExAllocatePoolUninitialized(NonPagedPool, ByteSize, ST_POOL_TAG);
}
PVOID
TreeAllocateRoutinePaged
(
__in struct _RTL_AVL_TABLE *Table,
__in CLONG ByteSize
)
{
UNREFERENCED_PARAMETER(Table);
return ExAllocatePoolUninitialized(PagedPool, ByteSize, ST_POOL_TAG);
}
VOID
TreeFreeRoutine
(
__in struct _RTL_AVL_TABLE *Table,
__in PVOID Buffer
)
{
UNREFERENCED_PARAMETER(Table);
ExFreePoolWithTag(Buffer, ST_POOL_TAG);
}
//
// ClearDepartingParentLink()
//
// `Entry` is an enumerated entry in the tree.
// `Context` is the PID corresponding to an entry that's being removed from the tree.
//
// If `Entry` is a child of `Context` it needs to be updated to indicate that the parent process
// is no longer available.
//
bool
NTAPI
ClearDepartingParentLink
(
PROCESS_REGISTRY_ENTRY *Entry,
void *Context
)
{
auto departingProcessId = (HANDLE)Context;
if (Entry->ParentProcessId == departingProcessId)
{
Entry->ParentProcessId = 0;
Entry->ParentEntry = NULL;
}
return true;
}
bool
InnerDeleteEntry
(
CONTEXT *Context,
PROCESS_REGISTRY_ENTRY *Entry
)
{
LOWER_UNICODE_STRING imageName = { 0 };
util::Swap(&Entry->ImageName, &imageName);
const auto status = RtlDeleteElementGenericTableAvl(&Context->Tree, Entry);
if (FALSE == status)
{
util::Swap(&Entry->ImageName, &imageName);
return false;
}
if (imageName.Buffer != NULL)
{
util::FreeStringBuffer(&imageName);
}
return true;
}
} // anonymous namespace
NTSTATUS
Initialize
(
CONTEXT **Context,
ST_PAGEABLE Pageable
)
{
const auto poolType = (Pageable == ST_PAGEABLE::YES) ? PagedPool : NonPagedPool;
*Context = (CONTEXT*)
ExAllocatePoolUninitialized(poolType, sizeof(CONTEXT), ST_POOL_TAG);
if (*Context == NULL)
{
return STATUS_INSUFFICIENT_RESOURCES;
}
(*Context)->Pageable = Pageable;
const auto allocRoutine = (Pageable == ST_PAGEABLE::YES)
? TreeAllocateRoutinePaged : TreeAllocateRoutineNonPaged;
RtlInitializeGenericTableAvl(&(*Context)->Tree, TreeCompareRoutine,
allocRoutine, TreeFreeRoutine, NULL);
return STATUS_SUCCESS;
}
void
TearDown
(
CONTEXT **Context
)
{
Reset(*Context);
ExFreePoolWithTag(*Context, ST_POOL_TAG);
*Context = NULL;
}
void
Reset
(
CONTEXT *Context
)
{
for (;;)
{
auto entry = (PROCESS_REGISTRY_ENTRY*)RtlGetElementGenericTableAvl(&Context->Tree, 0);
if (NULL == entry)
{
break;
}
//
// It's believed that `InnerDeleteEntry` will never fail as long as
// the following conditions are met:
//
// - The tree's CompareRoutine and FreeRoutine are correctly implemented.
// - Nodes in the tree are regarded as internally consistent by tree CompareRoutine.
// - `entry` argument is valid.
//
InnerDeleteEntry(Context, entry);
}
}
NTSTATUS
InitializeEntry
(
CONTEXT *Context,
HANDLE ParentProcessId,
HANDLE ProcessId,
ST_PROCESS_SPLIT_STATUS Split,
UNICODE_STRING *ImageName,
PROCESS_REGISTRY_ENTRY *Entry
)
{
RtlZeroMemory(Entry, sizeof(*Entry));
if (ImageName != NULL
&& ImageName->Length != 0)
{
LOWER_UNICODE_STRING lowerImageName;
auto status = util::AllocateCopyDowncaseString(&lowerImageName, ImageName, Context->Pageable);
if (!NT_SUCCESS(status))
{
return status;
}
Entry->ImageName = lowerImageName;
}
Entry->ParentProcessId = ParentProcessId;
Entry->ProcessId = ProcessId;
static const PROCESS_REGISTRY_ENTRY_SETTINGS settings =
{
.Split = ST_PROCESS_SPLIT_STATUS_OFF,
.HasFirewallState = false
};
Entry->Settings = { Split, false };
Entry->TargetSettings = settings;
Entry->PreviousSettings = settings;
Entry->ParentEntry = NULL;
return STATUS_SUCCESS;
}
NTSTATUS
AddEntry
(
CONTEXT *Context,
PROCESS_REGISTRY_ENTRY *Entry
)
{
//
// Insert entry into tree.
// This makes a copy of the entry.
//
BOOLEAN newElement;
auto record = RtlInsertElementGenericTableAvl(&Context->Tree, Entry, (CLONG)sizeof(*Entry), &newElement);
if (record != NULL && newElement != FALSE)
{
return STATUS_SUCCESS;
}
//
// Handle failure cases.
//
if (record == NULL)
{
// Allocation of record failed.
return STATUS_INSUFFICIENT_RESOURCES;
}
// There's already a record for this PID.
return STATUS_DUPLICATE_OBJECTID;
}
void
ReleaseEntry
(
PROCESS_REGISTRY_ENTRY *Entry
)
{
if (Entry->ImageName.Buffer != NULL)
{
util::FreeStringBuffer(&Entry->ImageName);
}
}
PROCESS_REGISTRY_ENTRY*
FindEntry
(
CONTEXT *Context,
HANDLE ProcessId
)
{
PROCESS_REGISTRY_ENTRY record = { 0 };
record.ProcessId = ProcessId;
return (PROCESS_REGISTRY_ENTRY*)RtlLookupElementGenericTableAvl(&Context->Tree, &record);
}
bool
DeleteEntry
(
CONTEXT *Context,
PROCESS_REGISTRY_ENTRY *Entry
)
{
const auto processId = Entry->ProcessId;
const auto status = InnerDeleteEntry(Context, Entry);
if (status)
{
ForEach(Context, ClearDepartingParentLink, processId);
}
return status;
}
bool
DeleteEntryById
(
CONTEXT *Context,
HANDLE ProcessId
)
{
auto entry = FindEntry(Context, ProcessId);
if (entry == NULL)
{
return false;
}
return DeleteEntry(Context, entry);
}
bool
ForEach
(
CONTEXT *Context,
ST_PR_FOREACH Callback,
void *ClientContext
)
{
for (auto entry = RtlEnumerateGenericTableAvl(&Context->Tree, TRUE);
entry != NULL;
entry = RtlEnumerateGenericTableAvl(&Context->Tree, FALSE))
{
if (!Callback((PROCESS_REGISTRY_ENTRY*)entry, ClientContext))
{
return false;
}
}
return true;
}
PROCESS_REGISTRY_ENTRY*
GetParentEntry
(
CONTEXT *Context,
PROCESS_REGISTRY_ENTRY *Entry
)
{
if (NULL != Entry->ParentEntry)
{
return Entry->ParentEntry;
}
if (0 == Entry->ParentProcessId)
{
return NULL;
}
return (Entry->ParentEntry = FindEntry(Context, Entry->ParentProcessId));
}
bool
IsEmpty
(
CONTEXT *Context
)
{
return FALSE != RtlIsGenericTableEmptyAvl(&Context->Tree);
}
} // namespace procregistry
| 6,557
|
C++
|
.cpp
| 325
| 18.181538
| 106
| 0.758525
|
mullvad/win-split-tunnel
| 37
| 9
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.