hyperion.ng/libsrc/hyperion/SettingsManager.cpp
Markus c135d91986
Media Foundation/V4L2 grabber ... (#1119)
* - New Media Foundation grabber
- JsonAPI available grabber fix
- commented json config removed

* Added libjpeg-turbo to dependencies

* Fix OSX build
Removed Azure Pipelines from build scripts

* Remove Platform from Dashboard

* Correct Grabber Namings

* Grabber UI improvements, generic JSONEditor Selection Update

* Active grabber fix

* Stop Framebuffer grabber on failure

* - Image format NV12 and I420 added
- Flip mode
- Scaling factor for MJPEG
- VSCode (compile before run)
- CI (push) dependency libjpeg-turbo added

* Refactor MediaFoundation (Part 1)

* Remove QDebug output

* Added image flipping ability to MF Grabber

* fix issue 1160

* -Reload MF Grabber only once per WebUI update
- Cleanup

* Improvements

* - Set 'Software Frame Decimation' begin to 0
- Removed grabber specific device name from Log
- Keep pixel format when switching resolution
- Display 'Flip mode' correct in Log
- BGR24 images always flipped

* Refactor MediaFoundation (Part 2)

* Refactor V4L2 grabber (part 1) (#62)

* Media Foundation grabber adapted to V4L2 change

* Enable Media Foundation grabber on windows

* Have fps as int, fix height typo

* Added video standards to JsonAPI output

* Error handling in source reader improved

* Fix "Frame to small" error

* Discovery VideoSources and Dynamically Update Editor

* Hide all element when no video grabber discovered, upate naming

* Do not show unsupported grabbers

* Copy Log to Clipboard

* Update Grabber schema and Defaults

* Update access levels and validate crop ranges

* Height and width in Qt grabber corrected

* Correct formatting

* Untabify

* Global component states across instances

* Components divided on the dashboard

* refactor

* Fix Merge-issues

* Database migration aligning with updated grabber model

* Align Grabber.js with new utility functions

* Allow editor-validation for enum-lists

* Handle "Show Explainations scenario" correctly

* Grabber - Ensure save is only possible on valid content

* Dashboard update + fix GlobalSignal connection

* Ensure default database is populated with current release

* Correct grabber4L2 access level

* Display Signal detection area in preview

* Write Hyperion version into default config on compiling.

* Create defaultconfig.json dynamically

* WebUI changes

* Correct grabber config look-ups

* Refactor i18n language loading

* Fix en.json

* Split global capture from instance capture config

* Update grabber default values

* Standalone grabber: Add --debug switch

* Enhance showInputOptionsForKey for multiple keys

* Add grabber instance link to system grabber config

* Only show signal detection area, if grabber is enabled

* Always show Active element on grabber page

* Remote control - Only display gabber status, if global grabber is enabled

* WebUI optimization (thx to @mkcologne)
Start Grabber only when global settings are enabled
Fixed an issue in the WebUI preview

* V4L2/MF changes

* Jsoneditor, Correct translation for default values

* Refactor LED-Device handling in UI and make element naming consistent

* MF Discovery extended

* Fix LGTM finding

* Support Grabber Bri, Hue, Sat and Con in UI, plus their defaults

* Concider Access level for item filtering

* Concider Access level for item filtering

* Revert "Concider Access level for item filtering"

This reverts commit 5b0ce3c0f2.

* Disable fpsSoftwareDecimation for framegrabber, as not supported yet

* JSON-Editor- Add updated schema for validation on dynamic elements

* added V4L2 color IDs

* LGTM findings fix

* destroy SR callback only on exit

* Grabber.js - Hide elements not supported by platform

* Fixed freezing start effect

* Grabber UI - Hardware controls - Show current values and allow to reset to defaults

* Grabber - Discovery - Add current values to properties

* Small things

* Clean-up Effects and have ENDLESS consistently defined

* Fix on/off/on priority during startup, by initializing _prevVisComp in line with background priority

* Add missing translation mappings

* DirectX Grabber reactivated/ QT Grabber size decimation fixed

* typo in push-master workflow

* Use PreciseTimer for Grabber to ensure stable FPS timing

* Set default Screencapture rate consistently

* Fix libjpeg-turbo download

* Remove Zero character from file

* docker-compile Add PLATFORM parameter, only copy output file after successful compile

* Framebuffer, Dispmanx, OSX, AML Grabber discovery, various clean-up and consistencies across grabbers

* Fix merge problem - on docker-compile Add PLATFORM parameter, only copy output file after successful compile

* Fix definition

* OSXFRameGrabber - Revert cast

* Clean-ups nach Feedback

* Disable certain libraries when building armlogic via standard stretch image as developer

* Add CEC availability to ServerInfo to have it platform independent

* Grabber UI - Fix problem that crop values are not populated when refining editor rage

* Preserve value when updating json-editor range

* LEDVisualisation - Clear image when source changes

* Fix - Preserve value when updating json-editor range

* LEDVisualisation - Clear image when no component is active

* Allow to have password handled by Password-Manager (#1263)

* Update default signal detection area to green assuming rainbow grabber

* LED Visualisation - Handle empty priority update

* Fix yuv420 in v4l2 grabber

* V4L2-Grabber discovery - Only report grabbers with valid video input information

* Grabber - Update static variables to have them working in release build

* LED Visualisation - ClearImage when no priorities

* LED Visualisation - Fix Logo resizing issue

* LED Visualisation - Have nearly black background and negative logo

Co-authored-by: LordGrey <lordgrey.emmel@gmail.com>
Co-authored-by: LordGrey <48840279+Lord-Grey@users.noreply.github.com>
2021-07-14 20:48:33 +02:00

460 lines
13 KiB
C++

// proj
#include <hyperion/SettingsManager.h>
// util
#include <utils/JsonUtils.h>
#include <db/SettingsTable.h>
#include "HyperionConfig.h"
// json schema process
#include <utils/jsonschema/QJsonFactory.h>
#include <utils/jsonschema/QJsonSchemaChecker.h>
// write config to filesystem
#include <utils/JsonUtils.h>
#include <utils/version.hpp>
using namespace semver;
// Constants
namespace {
const char DEFAULT_VERSION[] = "2.0.0-alpha.8";
} //End of constants
QJsonObject SettingsManager::schemaJson;
SettingsManager::SettingsManager(quint8 instance, QObject* parent, bool readonlyMode)
: QObject(parent)
, _log(Logger::getInstance("SETTINGSMGR"))
, _instance(instance)
, _sTable(new SettingsTable(instance, this))
, _configVersion(DEFAULT_VERSION)
, _previousVersion(DEFAULT_VERSION)
, _readonlyMode(readonlyMode)
{
_sTable->setReadonlyMode(_readonlyMode);
// get schema
if(schemaJson.isEmpty())
{
Q_INIT_RESOURCE(resource);
try
{
schemaJson = QJsonFactory::readSchema(":/hyperion-schema");
}
catch(const std::runtime_error& error)
{
throw std::runtime_error(error.what());
}
}
// get default config
QJsonObject defaultConfig;
if(!JsonUtils::readFile(":/hyperion_default.config", defaultConfig, _log))
{
throw std::runtime_error("Failed to read default config");
}
// transform json to string lists
QStringList keyList = defaultConfig.keys();
QStringList defValueList;
for(const auto & key : keyList)
{
if(defaultConfig[key].isObject())
{
defValueList << QString(QJsonDocument(defaultConfig[key].toObject()).toJson(QJsonDocument::Compact));
}
else if(defaultConfig[key].isArray())
{
defValueList << QString(QJsonDocument(defaultConfig[key].toArray()).toJson(QJsonDocument::Compact));
}
}
// fill database with default data if required
for(const auto & key : keyList)
{
QString val = defValueList.takeFirst();
// prevent overwrite
if(!_sTable->recordExist(key))
_sTable->createSettingsRecord(key,val);
}
// need to validate all data in database construct the entire data object
// TODO refactor schemaChecker to accept QJsonArray in validate(); QJsonDocument container? To validate them per entry...
QJsonObject dbConfig;
for(const auto & key : keyList)
{
QJsonDocument doc = _sTable->getSettingsRecord(key);
if(doc.isArray())
dbConfig[key] = doc.array();
else
dbConfig[key] = doc.object();
}
//Check, if database requires migration
bool isNewRelease = false;
// Use instance independent SettingsManager to track migration status
if ( instance == GLOABL_INSTANCE_ID)
{
if ( resolveConfigVersion(dbConfig) )
{
QJsonObject newGeneralConfig = dbConfig["general"].toObject();
semver::version BUILD_VERSION(HYPERION_VERSION);
if ( _configVersion > BUILD_VERSION )
{
Error(_log, "Database version [%s] is greater that current Hyperion version [%s]", _configVersion.getVersion().c_str(), BUILD_VERSION.getVersion().c_str());
// TODO: Remove version checking and Settingsmanager from components' constructor to be able to stop hyperion.
}
else
{
if ( _previousVersion < BUILD_VERSION )
{
if ( _configVersion == BUILD_VERSION )
{
newGeneralConfig["previousVersion"] = BUILD_VERSION.getVersion().c_str();
dbConfig["general"] = newGeneralConfig;
isNewRelease = true;
Info(_log, "Migration completed to version [%s]", BUILD_VERSION.getVersion().c_str());
}
else
{
Info(_log, "Migration from current version [%s] to new version [%s] started", _previousVersion.getVersion().c_str(), BUILD_VERSION.getVersion().c_str());
newGeneralConfig["previousVersion"] = _configVersion.getVersion().c_str();
newGeneralConfig["configVersion"] = BUILD_VERSION.getVersion().c_str();
dbConfig["general"] = newGeneralConfig;
isNewRelease = true;
}
}
}
}
}
// possible data upgrade steps to prevent data loss
bool migrated = handleConfigUpgrade(dbConfig);
if ( isNewRelease || migrated )
{
saveSettings(dbConfig, true);
}
// validate full dbconfig against schema, on error we need to rewrite entire table
QJsonSchemaChecker schemaChecker;
schemaChecker.setSchema(schemaJson);
QPair<bool,bool> valid = schemaChecker.validate(dbConfig);
// check if our main schema syntax is IO
if (!valid.second)
{
for (auto & schemaError : schemaChecker.getMessages())
Error(_log, "Schema Syntax Error: %s", QSTRING_CSTR(schemaError));
throw std::runtime_error("The config schema has invalid syntax. This should never happen! Go fix it!");
}
if (!valid.first)
{
Info(_log,"Table upgrade required...");
dbConfig = schemaChecker.getAutoCorrectedConfig(dbConfig);
for (auto & schemaError : schemaChecker.getMessages())
Warning(_log, "Config Fix: %s", QSTRING_CSTR(schemaError));
saveSettings(dbConfig,true);
}
else
_qconfig = dbConfig;
Debug(_log,"Settings database initialized");
}
QJsonDocument SettingsManager::getSetting(settings::type type) const
{
return _sTable->getSettingsRecord(settings::typeToString(type));
}
QJsonObject SettingsManager::getSettings() const
{
QJsonObject config;
for(const auto & key : _qconfig.keys())
{
//Read all records from database to ensure that global settings are read across instances
QJsonDocument doc = _sTable->getSettingsRecord(key);
if(doc.isArray())
{
config.insert(key, doc.array());
}
else
{
config.insert(key, doc.object());
}
}
return config;
}
bool SettingsManager::saveSettings(QJsonObject config, bool correct)
{
// optional data upgrades e.g. imported legacy/older configs
// handleConfigUpgrade(config);
// we need to validate data against schema
QJsonSchemaChecker schemaChecker;
schemaChecker.setSchema(schemaJson);
if (!schemaChecker.validate(config).first)
{
if(!correct)
{
Error(_log,"Failed to save configuration, errors during validation");
return false;
}
Warning(_log,"Fixing json data!");
config = schemaChecker.getAutoCorrectedConfig(config);
for (const auto & schemaError : schemaChecker.getMessages())
Warning(_log, "Config Fix: %s", QSTRING_CSTR(schemaError));
}
// store the new config
_qconfig = config;
// extract keys and data
QStringList keyList = config.keys();
QStringList newValueList;
for(const auto & key : keyList)
{
if(config[key].isObject())
{
newValueList << QString(QJsonDocument(config[key].toObject()).toJson(QJsonDocument::Compact));
}
else if(config[key].isArray())
{
newValueList << QString(QJsonDocument(config[key].toArray()).toJson(QJsonDocument::Compact));
}
}
int rc = true;
// compare database data with new data to emit/save changes accordingly
for(const auto & key : keyList)
{
QString data = newValueList.takeFirst();
if(_sTable->getSettingsRecordString(key) != data)
{
if ( ! _sTable->createSettingsRecord(key, data) )
{
rc = false;
}
else
{
emit settingsChanged(settings::stringToType(key), QJsonDocument::fromJson(data.toLocal8Bit()));
}
}
}
return rc;
}
bool SettingsManager::resolveConfigVersion(QJsonObject& config)
{
bool isValid = false;
if (config.contains("general"))
{
QJsonObject generalConfig = config["general"].toObject();
QString configVersion = generalConfig["configVersion"].toString();
QString previousVersion = generalConfig["previousVersion"].toString();
if ( !configVersion.isEmpty() )
{
isValid = _configVersion.setVersion(configVersion.toStdString());
}
else
{
_configVersion.setVersion(DEFAULT_VERSION);
isValid = true;
}
if ( !previousVersion.isEmpty() && isValid )
{
isValid = _previousVersion.setVersion(previousVersion.toStdString());
}
else
{
_previousVersion.setVersion(DEFAULT_VERSION);
isValid = true;
}
}
return isValid;
}
bool SettingsManager::handleConfigUpgrade(QJsonObject& config)
{
bool migrated = false;
resolveConfigVersion(config);
//Do only migrate, if configuration is not up to date
if (_previousVersion < _configVersion)
{
//Migration steps for versions <= alpha 9
semver::version targetVersion {"2.0.0-alpha.9"};
if (_previousVersion <= targetVersion )
{
Info(_log, "Instance [%u]: Migrate LED Layout from current version [%s] to version [%s] or later", _instance, _previousVersion.getVersion().c_str(), targetVersion.getVersion().c_str());
// LED LAYOUT UPGRADE
// from { hscan: { minimum: 0.2, maximum: 0.3 }, vscan: { minimum: 0.2, maximum: 0.3 } }
// from { h: { min: 0.2, max: 0.3 }, v: { min: 0.2, max: 0.3 } }
// to { hmin: 0.2, hmax: 0.3, vmin: 0.2, vmax: 0.3}
if(config.contains("leds"))
{
const QJsonArray ledarr = config["leds"].toArray();
const QJsonObject led = ledarr[0].toObject();
if(led.contains("hscan") || led.contains("h"))
{
const bool whscan = led.contains("hscan");
QJsonArray newLedarr;
for(const auto & entry : ledarr)
{
const QJsonObject led = entry.toObject();
QJsonObject hscan;
QJsonObject vscan;
QJsonValue hmin;
QJsonValue hmax;
QJsonValue vmin;
QJsonValue vmax;
QJsonObject nL;
if(whscan)
{
hscan = led["hscan"].toObject();
vscan = led["vscan"].toObject();
hmin = hscan["minimum"];
hmax = hscan["maximum"];
vmin = vscan["minimum"];
vmax = vscan["maximum"];
}
else
{
hscan = led["h"].toObject();
vscan = led["v"].toObject();
hmin = hscan["min"];
hmax = hscan["max"];
vmin = vscan["min"];
vmax = vscan["max"];
}
// append to led object
nL["hmin"] = hmin;
nL["hmax"] = hmax;
nL["vmin"] = vmin;
nL["vmax"] = vmax;
newLedarr.append(nL);
}
// replace
config["leds"] = newLedarr;
migrated = true;
Info(_log,"Instance [%u]: LED Layout migrated", _instance);
}
}
if(config.contains("ledConfig"))
{
QJsonObject oldLedConfig = config["ledConfig"].toObject();
if ( !oldLedConfig.contains("classic"))
{
QJsonObject newLedConfig;
newLedConfig.insert("classic", oldLedConfig );
QJsonObject defaultMatrixConfig {{"ledshoriz", 1}
,{"ledsvert", 1}
,{"cabling","snake"}
,{"start","top-left"}
};
newLedConfig.insert("matrix", defaultMatrixConfig );
config["ledConfig"] = newLedConfig;
migrated = true;
Info(_log,"Instance [%u]: LED-Config migrated", _instance);
}
}
// LED Hardware count is leading for versions after alpha 9
// Setting Hardware LED count to number of LEDs configured via layout, if layout number is greater than number of hardware LEDs
if (config.contains("device"))
{
QJsonObject newDeviceConfig = config["device"].toObject();
if (newDeviceConfig.contains("hardwareLedCount"))
{
int hwLedcount = newDeviceConfig["hardwareLedCount"].toInt();
if (config.contains("leds"))
{
const QJsonArray ledarr = config["leds"].toArray();
int layoutLedCount = ledarr.size();
if (hwLedcount < layoutLedCount )
{
Warning(_log, "Instance [%u]: HwLedCount/Layout mismatch! Setting Hardware LED count to number of LEDs configured via layout", _instance);
hwLedcount = layoutLedCount;
newDeviceConfig["hardwareLedCount"] = hwLedcount;
migrated = true;
}
}
}
if (newDeviceConfig.contains("type"))
{
QString type = newDeviceConfig["type"].toString();
if (type == "atmoorb" || type == "fadecandy" || type == "philipshue" )
{
if (newDeviceConfig.contains("output"))
{
newDeviceConfig["host"] = newDeviceConfig["output"].toString();
newDeviceConfig.remove("output");
migrated = true;
}
}
}
if (migrated)
{
config["device"] = newDeviceConfig;
Debug(_log, "LED-Device records migrated");
}
}
if (config.contains("grabberV4L2"))
{
QJsonObject newGrabberV4L2Config = config["grabberV4L2"].toObject();
if (newGrabberV4L2Config.contains("encoding_format"))
{
newGrabberV4L2Config.remove("encoding_format");
config["grabberV4L2"] = newGrabberV4L2Config;
migrated = true;
Debug(_log, "GrabberV4L2 records migrated");
}
}
if (config.contains("framegrabber"))
{
QJsonObject newFramegrabberConfig = config["framegrabber"].toObject();
//Align element namings with grabberV4L2
//Rename element type -> device
if (newFramegrabberConfig.contains("type"))
{
newFramegrabberConfig["device"] = newFramegrabberConfig["type"];
newFramegrabberConfig.remove("type");
migrated = true;
}
//Rename element frequency_Hz -> fps
if (newFramegrabberConfig.contains("frequency_Hz"))
{
newFramegrabberConfig["fps"] = newFramegrabberConfig["frequency_Hz"];
newFramegrabberConfig.remove("frequency_Hz");
migrated = true;
}
config["framegrabber"] = newFramegrabberConfig;
Debug(_log, "Framegrabber records migrated");
}
}
}
return migrated;
}