From b2368e856a14dc01b45fb7744bc672d3b362cbd3 Mon Sep 17 00:00:00 2001 From: Jack Lau Date: Sun, 22 Nov 2026 21:35:20 +0800 Subject: [PATCH 1/3] fix: make file logging thread-safe and surface conversion failures The log callback raced across threads and stored split FFmpeg lines, and a missing transcoder or a thrown conversion error could still look like success. Co-authored-by: Cursor --- src/builder/src/batch_queue_dialog.cpp | 19 +- src/builder/src/converter_runner.cpp | 36 ++- src/builder/src/extract_audio_page.cpp | 8 +- src/builder/src/info_view_page.cpp | 10 +- src/builder/src/open_converter.cpp | 83 +++--- src/builder/src/remux_page.cpp | 8 +- src/common/include/info.h | 7 +- src/common/include/logger.h | 46 ++- src/common/src/info.cpp | 167 ++++++----- src/common/src/logger.cpp | 343 ++++++++++++++++++++--- src/engine/src/converter.cpp | 53 ++-- src/tests/transcoder_test.cpp | 93 +++++- src/transcoder/src/transcoder_bmf.cpp | 2 +- src/transcoder/src/transcoder_ffmpeg.cpp | 2 - src/transcoder/src/transcoder_fftool.cpp | 103 ++++--- 15 files changed, 724 insertions(+), 256 deletions(-) diff --git a/src/builder/src/batch_queue_dialog.cpp b/src/builder/src/batch_queue_dialog.cpp index b60ddbe5..586cf47e 100644 --- a/src/builder/src/batch_queue_dialog.cpp +++ b/src/builder/src/batch_queue_dialog.cpp @@ -17,6 +17,7 @@ #include "../include/batch_queue_dialog.h" #include "../../engine/include/converter.h" +#include "../../common/include/logger.h" #include #include #include @@ -25,6 +26,8 @@ #include #include #include +#include +#include BatchQueueDialog::BatchQueueDialog(QWidget *parent) : QDialog(parent), @@ -381,10 +384,22 @@ void BatchQueueDialog::ProcessNextItem() { try { Converter converter(processParam, encodeParam); - converter.set_transcoder(transcoderName.toStdString()); - success = converter.convert_format(inputPath.toStdString(), outputPath.toStdString()); + if (!converter.set_transcoder(transcoderName.toStdString())) { + success = false; + } else { + success = converter.convert_format(inputPath.toStdString(), + outputPath.toStdString()); + } + } catch (const std::exception &ex) { + success = false; + const char *what = ex.what(); + Logger::Log(std::string("Batch conversion aborted by exception: ") + + (what ? what : "std::exception"), + true); } catch (...) { success = false; + Logger::Log("Batch conversion aborted by an unknown exception.", + true); } // Remove observer and clean up diff --git a/src/builder/src/converter_runner.cpp b/src/builder/src/converter_runner.cpp index 6857693c..94831a9a 100644 --- a/src/builder/src/converter_runner.cpp +++ b/src/builder/src/converter_runner.cpp @@ -16,12 +16,16 @@ */ #include "../include/converter_runner.h" +#include "../../common/include/logger.h" #include "../../common/include/encode_parameter.h" #include "../../common/include/process_parameter.h" #include "../../engine/include/converter.h" #include #include #include +#include +#include +#include ConverterRunner::ConverterRunner(QProgressBar *progressBar, QLabel *progressLabel, @@ -81,15 +85,29 @@ bool ConverterRunner::RunConversion(const QString &inputPath, // Run conversion in a separate thread QThread *thread = QThread::create([this, inputPath, outputPath, encodeParam, processParam, transcoderName]() { - // Create converter - Converter *converter = new Converter(processParam, encodeParam); - converter->set_transcoder(transcoderName.toStdString()); - - // Perform conversion - bool success = converter->convert_format(inputPath.toStdString(), outputPath.toStdString()); - - // Clean up converter - delete converter; + bool success = false; + + try { + // unique_ptr so a throw cannot leak the converter. An exception + // leaving this thread would terminate the process. + auto converter = + std::make_unique(processParam, encodeParam); + if (!converter->set_transcoder(transcoderName.toStdString())) { + success = false; + } else { + success = converter->convert_format(inputPath.toStdString(), + outputPath.toStdString()); + } + } catch (const std::exception &ex) { + success = false; + const char *what = ex.what(); + Logger::Log(std::string("Conversion aborted by exception: ") + + (what ? what : "std::exception"), + true); + } catch (...) { + success = false; + Logger::Log("Conversion aborted by an unknown exception.", true); + } // Emit signal to notify completion (will be handled on main thread) QMetaObject::invokeMethod(this, [this, success]() { diff --git a/src/builder/src/extract_audio_page.cpp b/src/builder/src/extract_audio_page.cpp index d4c20476..a8fb4903 100644 --- a/src/builder/src/extract_audio_page.cpp +++ b/src/builder/src/extract_audio_page.cpp @@ -28,6 +28,7 @@ #include #include #include +#include ExtractAudioPage::ExtractAudioPage(QWidget *parent) : BasePage(parent), converterRunner(nullptr) { SetupUI(); @@ -258,10 +259,11 @@ void ExtractAudioPage::UpdateOutputPath() { QString ExtractAudioPage::DetectAudioCodecFromFile(const QString &filePath) { Info info; - QByteArray ba = filePath.toLocal8Bit(); - char *src = ba.data(); + // Stable UTF-8 path, mirroring the video player's FFmpeg usage; avoids + // feeding avformat a pointer into a short-lived toLocal8Bit() buffer. + std::string path = filePath.toStdString(); - info.send_info(src); + info.send_info(path); QuickInfo *quickInfo = info.get_quick_info(); if (quickInfo && quickInfo->audioIdx >= 0) { diff --git a/src/builder/src/info_view_page.cpp b/src/builder/src/info_view_page.cpp index 3944f861..170483f0 100644 --- a/src/builder/src/info_view_page.cpp +++ b/src/builder/src/info_view_page.cpp @@ -22,6 +22,7 @@ #include #include #include +#include InfoViewPage::InfoViewPage(QWidget *parent) : BasePage(parent) { info = new Info(); @@ -196,11 +197,14 @@ void InfoViewPage::AnalyzeFile(const QString &filePath) { return; } - QByteArray ba = filePath.toLocal8Bit(); - char *src = ba.data(); + // Pass the path as a stable UTF-8 std::string (mirrors how the video + // player feeds FFmpeg). Avoid avformat consuming a pointer into a + // short-lived QByteArray whose local-code-page encoding and buffer + // lifetime are not guaranteed on all Windows systems. + std::string path = filePath.toStdString(); // QString -> UTF-8 std::string // Get info by analyzing the file - info->send_info(src); + info->send_info(path); // Display info DisplayInfo(info->get_quick_info()); diff --git a/src/builder/src/open_converter.cpp b/src/builder/src/open_converter.cpp index 6ff6b020..feb597a0 100644 --- a/src/builder/src/open_converter.cpp +++ b/src/builder/src/open_converter.cpp @@ -46,6 +46,7 @@ #include #include #include +#include #include "../../common/include/encode_parameter.h" #include "../../common/include/info.h" @@ -67,8 +68,6 @@ #include "../include/ai_processing_page.h" #include "ui_open_converter.h" -#include - OpenConverter::OpenConverter(QWidget *parent) : QMainWindow(parent), ui(new Ui::OpenConverter) { /* init objects */ @@ -94,9 +93,11 @@ OpenConverter::OpenConverter(QWidget *parent) // ── Restore user settings ──────────────────────────────────────────── QSettings settings(m_settingsPath, QSettings::IniFormat); - bool loggingEnabled = settings.value("logging/fileLoggingEnabled", false).toBool(); + bool wantLog = settings.value("logging/fileLoggingEnabled", false).toBool(); + bool loggingEnabled = Logger::Instance().SetEnabled(wantLog); ui->action_enableLog->setChecked(loggingEnabled); - Logger::Instance().SetEnabled(loggingEnabled); + if (loggingEnabled != wantLog) + settings.setValue("logging/fileLoggingEnabled", loggingEnabled); connect(ui->action_enableLog, &QAction::toggled, this, &OpenConverter::SlotLogToggled); @@ -121,8 +122,13 @@ OpenConverter::OpenConverter(QWidget *parent) logCheckBox->setChecked(Logger::Instance().IsEnabled()); layout->addWidget(logCheckBox); - connect(logCheckBox, &QCheckBox::toggled, this, [this](bool checked) { + connect(logCheckBox, &QCheckBox::toggled, this, [this, logCheckBox](bool checked) { ui->action_enableLog->setChecked(checked); + const bool enabled = Logger::Instance().IsEnabled(); + if (logCheckBox->isChecked() != enabled) { + QSignalBlocker blocker(logCheckBox); + logCheckBox->setChecked(enabled); + } }); layout->addStretch(); @@ -139,7 +145,10 @@ OpenConverter::OpenConverter(QWidget *parent) QSettings settings(m_settingsPath, QSettings::IniFormat); settings.clear(); Logger::Instance().SetEnabled(false); - ui->action_enableLog->setChecked(false); + { + QSignalBlocker blocker(ui->action_enableLog); + ui->action_enableLog->setChecked(false); + } settingsDialog->close(); } }); @@ -208,8 +217,7 @@ OpenConverter::OpenConverter(QWidget *parent) for (QAction* action : transcoderActions) { if (action->objectName() == savedTranscoder) { action->setChecked(true); - converter->set_transcoder(savedTranscoder.toStdString()); - restored = true; + restored = converter->set_transcoder(savedTranscoder.toStdString()); break; } } @@ -295,38 +303,32 @@ void OpenConverter::dropEvent(QDropEvent *event) { // Called every time, when a menu entry of the transcoder menu is called void OpenConverter::SlotTranscoderChanged(QAction *action) { - if (0 != action) { - std::string transcoderName = action->objectName().toStdString(); - bool isValid = false; + if (!action) + return; + + const std::string transcoderName = action->objectName().toStdString(); + bool isValid = false; #ifdef ENABLE_FFMPEG - if (transcoderName == "FFMPEG") { - converter->set_transcoder(transcoderName); - isValid = true; - } + if (transcoderName == "FFMPEG") + isValid = converter->set_transcoder(transcoderName); #endif #ifdef ENABLE_FFTOOL - if (transcoderName == "FFTOOL") { - converter->set_transcoder(transcoderName); - isValid = true; - } + if (transcoderName == "FFTOOL") + isValid = converter->set_transcoder(transcoderName); #endif #ifdef ENABLE_BMF - if (transcoderName == "BMF") { - converter->set_transcoder(transcoderName); - isValid = true; - } + if (transcoderName == "BMF") + isValid = converter->set_transcoder(transcoderName); #endif - // If the transcoder name is not valid, log an error - if (isValid) { - QSettings settings(m_settingsPath, QSettings::IniFormat); - settings.setValue("app/transcoder", action->objectName()); - ui->statusBar->showMessage( - tr("Current Transcoder changed to %1") - .arg(QString::fromStdString(transcoderName))); - } else { - std::cout << "Error: Undefined transcoder name - " - << transcoderName.c_str() << std::endl; - } + if (isValid) { + QSettings settings(m_settingsPath, QSettings::IniFormat); + settings.setValue("app/transcoder", action->objectName()); + ui->statusBar->showMessage( + tr("Current Transcoder changed to %1") + .arg(QString::fromStdString(transcoderName))); + } else { + Logger::Log("Undefined or unavailable transcoder: " + transcoderName, + true); } } @@ -608,9 +610,18 @@ QString OpenConverter::GetCurrentTranscoderName() const { } void OpenConverter::SlotLogToggled(bool checked) { + const bool enabled = Logger::Instance().SetEnabled(checked); + if (enabled != checked) { + QSignalBlocker blocker(ui->action_enableLog); + ui->action_enableLog->setChecked(enabled); + QMessageBox::warning( + this, tr("Log File"), + tr("Could not open the log file:\n%1") + .arg(QString::fromStdString(Logger::Instance().GetLogPath()))); + } + QSettings settings(m_settingsPath, QSettings::IniFormat); - settings.setValue("logging/fileLoggingEnabled", checked); - Logger::Instance().SetEnabled(checked); + settings.setValue("logging/fileLoggingEnabled", enabled); } void OpenConverter::SlotAbout() { diff --git a/src/builder/src/remux_page.cpp b/src/builder/src/remux_page.cpp index 3dc2025b..0e9057cb 100644 --- a/src/builder/src/remux_page.cpp +++ b/src/builder/src/remux_page.cpp @@ -27,6 +27,7 @@ #include #include #include +#include extern "C" { #include @@ -238,10 +239,11 @@ void RemuxPage::AnalyzeStreams(const QString &filePath) { } AVFormatContext *formatCtx = nullptr; - QByteArray ba = filePath.toLocal8Bit(); + // FFmpeg wants a UTF-8 path. toLocal8Bit() is the ANSI code page on + // Windows, so non-ASCII paths fail to open. + const std::string path = filePath.toStdString(); - // Open input file - if (avformat_open_input(&formatCtx, ba.data(), nullptr, nullptr) < 0) { + if (avformat_open_input(&formatCtx, path.c_str(), nullptr, nullptr) < 0) { QLabel *errorLabel = new QLabel("Error: Could not open file", streamsContainer); errorLabel->setStyleSheet("color: red;"); streamsLayout->addWidget(errorLabel); diff --git a/src/common/include/info.h b/src/common/include/info.h index 4af40369..68c89feb 100644 --- a/src/common/include/info.h +++ b/src/common/include/info.h @@ -84,8 +84,11 @@ class Info { void init(); // get qucik info reference QuickInfo *get_quick_info(); - // send the info to front-end - void send_info(char *src); + // Probe the file at src. src is a UTF-8 filesystem path. FFmpeg's + // file protocol accepts UTF-8 on every platform, including Windows, + // where it converts the path to UTF-16. The string only needs to + // stay alive for this call. + void send_info(const std::string& src); }; #endif // INFO_H diff --git a/src/common/include/logger.h b/src/common/include/logger.h index bece2715..61ef6adf 100644 --- a/src/common/include/logger.h +++ b/src/common/include/logger.h @@ -19,26 +19,43 @@ #define LOGGER_H #include +#include #include extern "C" { #include } +// Process-wide FFmpeg and application logger. +// +// File output is opt-in. Console output for Logger::Log() is not: every call +// is printed immediately, and is also appended to the log file when file +// logging is on. The av_log callback is installed only while file logging is +// on. It records FFmpeg output through av_log_format_line (so FFmpeg's own +// line prefixes and partial lines stay intact) and forwards messages at +// AV_LOG_INFO and above to the previous callback. class Logger { public: static Logger& Instance(); - // Set the full path for the log file (must be called before SetEnabled(true)) + // UTF-8 path. Parent directories are created when logging is enabled. + // If logging is already on, the file is reopened at the new path. void SetLogPath(const std::string& path); std::string GetLogPath() const; - // Enable or disable file logging - void SetEnabled(bool enabled); + // Returns the state actually achieved. Enabling fails (and stays off) + // when the path is empty or the file cannot be created. + bool SetEnabled(bool enabled); bool IsEnabled() const; - // Non-copyable singleton - Logger(const Logger&) = delete; + // Thread-safe. isError selects stderr and an ERROR record; otherwise the + // line goes to stdout and is recorded as INFO. Embedded newlines are split + // into separate records. A no-op write to the file when logging is off. + static void Log(const std::string& msg, bool isError = false); + + static bool IsLoggingEnabled(); + + Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; private: @@ -47,11 +64,24 @@ class Logger { static void AvLogCallback(void* avcl, int level, const char* fmt, va_list vl); static const char* LevelToString(int level); + static std::string Timestamp(); + + void CloseFileUnlocked(); + void ShutdownUnlocked(); + bool OpenFileUnlocked(const std::string& path, std::string& error); + void AppendLocked(int level, const char* text); + void WriteLineLocked(int level, const std::string& text); - bool m_enabled = false; - int m_minLevel = AV_LOG_DEBUG; // reserved: future per-level filtering - std::string m_logPath; + bool m_enabled = false; + bool m_callbackInstalled = false; + int m_savedLogLevel = AV_LOG_INFO; + int m_printPrefix = 1; + int m_lineLevel = AV_LOG_INFO; + std::string m_logPath; + std::string m_openPath; std::ofstream m_logFile; + std::string m_line; + mutable std::mutex m_mutex; void (*m_originalCallback)(void*, int, const char*, va_list) = nullptr; }; diff --git a/src/common/src/info.cpp b/src/common/src/info.cpp index 5b34c0c7..868908c2 100644 --- a/src/common/src/info.cpp +++ b/src/common/src/info.cpp @@ -16,6 +16,7 @@ */ #include "../include/info.h" +#include "../include/logger.h" Info::Info() { avCtx = NULL; @@ -43,97 +44,133 @@ void Info::init() { quickInfo->sampleFmt = ""; quickInfo->sampleRate = 0; - quickInfo->subIdx = 0; + quickInfo->subIdx = -1; } void Info::print_error(const char *msg, int ret) { av_strerror(ret, errorMsg, sizeof(errorMsg)); - av_log(NULL, AV_LOG_ERROR, " %s: %s \n", msg, errorMsg); + Logger::Log(std::string("Info: ") + (msg ? msg : "error") + ": " + errorMsg, + true); } +namespace { + +bool HasCodecParameters(const AVFormatContext *ctx, int index) { + return ctx && index >= 0 && index < static_cast(ctx->nb_streams) && + ctx->streams[index] && ctx->streams[index]->codecpar; +} + +void ReadVideoStream(QuickInfo *info, const AVStream *stream) { + const AVCodecParameters *par = stream->codecpar; + info->width = par->width; + info->height = par->height; + + if (par->color_space != AVCOL_SPC_UNSPECIFIED) { + const char *name = av_color_space_name(par->color_space); + if (name) + info->colorSpace = name; + } + if (par->codec_id != AV_CODEC_ID_NONE) + info->videoCodec = avcodec_get_name(par->codec_id); + + const auto pixFmt = static_cast(par->format); + if (pixFmt != AV_PIX_FMT_NONE) { + const char *pixName = av_get_pix_fmt_name(pixFmt); + if (pixName) + info->pixelFormat = pixName; + } + info->videoBitRate = par->bit_rate; + + // Integer division turns 30000/1001 into 29 and faults when den is 0. + AVRational rate = stream->avg_frame_rate; + if (rate.num <= 0 || rate.den <= 0) + rate = stream->r_frame_rate; + if (rate.num > 0 && rate.den > 0) { + info->frameRate = static_cast(rate.num) / + static_cast(rate.den); + } +} + +bool ReadAudioStream(QuickInfo *info, const AVCodecParameters *par, + AVCodecContext **audioCtx, const std::string &src) { + *audioCtx = avcodec_alloc_context3(nullptr); + if (!*audioCtx) { + Logger::Log("Info: failed to allocate audio codec context.", true); + return false; + } + if (avcodec_parameters_to_context(*audioCtx, par) < 0) { + Logger::Log("Info: failed to copy audio codec parameters: " + src, + true); + return false; + } + + info->audioCodec = avcodec_get_name(par->codec_id); + info->audioBitRate = par->bit_rate; + info->channels = par->ch_layout.nb_channels; + const char *sampleName = av_get_sample_fmt_name((*audioCtx)->sample_fmt); + if (sampleName) + info->sampleFmt = sampleName; + info->sampleRate = par->sample_rate; + return true; +} + +} // namespace QuickInfo *Info::get_quick_info() { return quickInfo; } -void Info::send_info(char *src) { +void Info::send_info(const std::string &src) { init(); - int ret = 0; - av_log_set_level(AV_LOG_DEBUG); - ret = avformat_open_input(&avCtx, src, NULL, NULL); + if (src.empty()) { + Logger::Log("Info: empty media path.", true); + return; + } + + int ret = avformat_open_input(&avCtx, src.c_str(), nullptr, nullptr); if (ret < 0) { print_error("open failed", ret); + Logger::Log("Info: failed to open input file: " + src, true); goto end; } - ret = avformat_find_stream_info(avCtx, NULL); + + ret = avformat_find_stream_info(avCtx, nullptr); if (ret < 0) { print_error("find stream info failed", ret); - } - // find the video and audio stream from container - quickInfo->videoIdx = - av_find_best_stream(avCtx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0); - quickInfo->audioIdx = - av_find_best_stream(avCtx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0); - - if (quickInfo->videoIdx >= 0) { - quickInfo->height = - avCtx->streams[quickInfo->videoIdx]->codecpar->height; - quickInfo->width = avCtx->streams[quickInfo->videoIdx]->codecpar->width; - - if (avCtx->streams[quickInfo->videoIdx]->codecpar->color_space != AVCOL_SPC_UNSPECIFIED) { - quickInfo->colorSpace = av_color_space_name( - avCtx->streams[quickInfo->videoIdx]->codecpar->color_space); - } - if (avCtx->streams[quickInfo->videoIdx]->codecpar->codec_id != AV_CODEC_ID_NONE) - quickInfo->videoCodec = avcodec_get_name( - avCtx->streams[quickInfo->videoIdx]->codecpar->codec_id); - // Get pixel format - AVPixelFormat pix_fmt = (AVPixelFormat)avCtx->streams[quickInfo->videoIdx]->codecpar->format; - if (pix_fmt != AV_PIX_FMT_NONE) { - const char *pix_fmt_name = av_get_pix_fmt_name(pix_fmt); - if (pix_fmt_name) - quickInfo->pixelFormat = pix_fmt_name; - } - quickInfo->videoBitRate = - avCtx->streams[quickInfo->videoIdx]->codecpar->bit_rate; - quickInfo->frameRate = - avCtx->streams[quickInfo->videoIdx]->r_frame_rate.num / - avCtx->streams[quickInfo->videoIdx]->r_frame_rate.den; - - } else { - av_log(avCtx, AV_LOG_ERROR, "There is no video stream!\n"); - // goto end; + Logger::Log("Info: failed to read stream info: " + src, true); } - if (quickInfo->audioIdx < 0) { - av_log(avCtx, AV_LOG_ERROR, "There is no audio stream!\n"); - goto end; + { + const int videoIdx = + av_find_best_stream(avCtx, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0); + const int audioIdx = + av_find_best_stream(avCtx, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0); + quickInfo->videoIdx = videoIdx >= 0 ? videoIdx : -1; + quickInfo->audioIdx = audioIdx >= 0 ? audioIdx : -1; } - audioCtx = avcodec_alloc_context3(NULL); - if (!audioCtx) { - av_log(audioCtx, AV_LOG_ERROR, - "Could not allocate audio codec context\n"); - goto end; + if (HasCodecParameters(avCtx, quickInfo->videoIdx)) { + ReadVideoStream(quickInfo, avCtx->streams[quickInfo->videoIdx]); + } else if (quickInfo->videoIdx >= 0) { + Logger::Log("Info: video stream has no codec parameters: " + src, + true); + quickInfo->videoIdx = -1; } - // Open the audio codec - if (avcodec_parameters_to_context( - audioCtx, avCtx->streams[quickInfo->audioIdx]->codecpar) < 0) { - av_log(avCtx, AV_LOG_ERROR, "Failed to initialize codec context\n"); - goto end; + + if (HasCodecParameters(avCtx, quickInfo->audioIdx)) { + const AVCodecParameters *par = + avCtx->streams[quickInfo->audioIdx]->codecpar; + if (!ReadAudioStream(quickInfo, par, &audioCtx, src)) + goto end; + } else if (quickInfo->audioIdx >= 0) { + Logger::Log("Info: audio stream has no codec parameters: " + src, + true); + quickInfo->audioIdx = -1; } - quickInfo->audioCodec = avcodec_get_name( - avCtx->streams[quickInfo->audioIdx]->codecpar->codec_id); - quickInfo->audioBitRate = - avCtx->streams[quickInfo->audioIdx]->codecpar->bit_rate; - quickInfo->channels = - avCtx->streams[quickInfo->audioIdx]->codecpar->ch_layout.nb_channels; - quickInfo->sampleFmt = av_get_sample_fmt_name(audioCtx->sample_fmt); - quickInfo->sampleRate = - avCtx->streams[quickInfo->audioIdx]->codecpar->sample_rate; + if (quickInfo->videoIdx < 0 && quickInfo->audioIdx < 0) + Logger::Log("Info: no audio or video stream in: " + src, true); end: avformat_close_input(&avCtx); - avcodec_free_context(&audioCtx); } diff --git a/src/common/src/logger.cpp b/src/common/src/logger.cpp index c67624f4..d7e8b2d3 100644 --- a/src/common/src/logger.cpp +++ b/src/common/src/logger.cpp @@ -20,87 +20,340 @@ #include #include #include +#include +#include +#include +#include + +#if defined(_WIN32) + #include +#endif extern "C" { #include } +namespace { + +// Qt passes UTF-8. On Windows ofstream(const char*) uses the ANSI code page, +// so convert to UTF-16 and let filesystem::path use the wide open. POSIX +// paths are already UTF-8 bytes. +std::filesystem::path PathFromUtf8(const std::string& utf8) { +#if defined(_WIN32) + if (utf8.empty()) + return {}; + const int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, + utf8.data(), + static_cast(utf8.size()), + nullptr, 0); + if (size <= 0) + return {}; + std::wstring wide(static_cast(size), L'\0'); + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), + static_cast(utf8.size()), wide.data(), size); + return std::filesystem::path(wide); +#else + return std::filesystem::path(utf8); +#endif +} + +} // namespace + Logger& Logger::Instance() { static Logger instance; return instance; } Logger::Logger() { - m_originalCallback = av_log_default_callback; + // av_log_get_default_callback() is not in FFmpeg 5.1. + m_originalCallback = &av_log_default_callback; + m_savedLogLevel = av_log_get_level(); } -Logger::~Logger() { - SetEnabled(false); -} +Logger::~Logger() = default; void Logger::SetLogPath(const std::string& path) { - m_logPath = path; + bool reopen = false; + { + std::lock_guard lock(m_mutex); + if (path == m_logPath) + return; + m_logPath = path; + reopen = m_enabled; + } + if (reopen) + SetEnabled(true); } std::string Logger::GetLogPath() const { + std::lock_guard lock(m_mutex); return m_logPath; } bool Logger::IsEnabled() const { - return m_enabled; + std::lock_guard lock(m_mutex); + return m_enabled && m_logFile.is_open(); } -void Logger::SetEnabled(bool enabled) { - if (enabled == m_enabled) - return; +bool Logger::IsLoggingEnabled() { return Instance().IsEnabled(); } + +void Logger::CloseFileUnlocked() { + m_enabled = false; + m_line.clear(); + m_printPrefix = 1; + if (m_logFile.is_open()) { + m_logFile.flush(); + m_logFile.close(); + } + m_logFile.clear(); + m_openPath.clear(); + if (m_callbackInstalled) { + av_log_set_level(m_savedLogLevel); + av_log_set_callback(m_originalCallback ? m_originalCallback + : &av_log_default_callback); + m_callbackInstalled = false; + } +} - if (enabled) { - m_logFile.open(m_logPath, std::ios::app); - if (!m_logFile.is_open()) - return; // path not set or unwritable — stay disabled - m_enabled = true; - av_log_set_callback(&Logger::AvLogCallback); - } else { - m_enabled = false; - av_log_set_callback(m_originalCallback); - if (m_logFile.is_open()) - m_logFile.close(); +void Logger::ShutdownUnlocked() { + // Keep a trailing fragment that never received its newline. Do this + // before CloseFileUnlocked, and do not call WriteLineLocked: a failed + // write would re-enter shutdown. + if (m_enabled && m_logFile.is_open() && !m_line.empty()) { + m_logFile << '[' << Timestamp() << "] [" << LevelToString(m_lineLevel) + << "] " << m_line << '\n'; + m_logFile.flush(); } + m_line.clear(); + CloseFileUnlocked(); +} + +bool Logger::OpenFileUnlocked(const std::string& utf8Path, std::string& error) { + error.clear(); + if (utf8Path.empty()) { + error = "log path is empty"; + return false; + } + + std::error_code ec; + const std::filesystem::path path = PathFromUtf8(utf8Path); + const std::filesystem::path parent = path.parent_path(); + if (!parent.empty()) { + std::filesystem::create_directories(parent, ec); + if (ec) { + error = "cannot create log directory for \"" + utf8Path + + "\": " + ec.message(); + return false; + } + } + + if (m_logFile.is_open()) + m_logFile.close(); + m_logFile.clear(); + m_logFile.open(path, std::ios::app); + if (!m_logFile) { + error = "cannot open log file \"" + utf8Path + "\""; + m_openPath.clear(); + return false; + } + m_openPath = utf8Path; + return true; +} + +bool Logger::SetEnabled(bool enabled) { + std::string error; + bool ok = false; + { + std::lock_guard lock(m_mutex); + if (!enabled) { + ShutdownUnlocked(); + return false; + } + + if (m_enabled && m_logFile.is_open() && m_openPath == m_logPath) + return true; + + if (!OpenFileUnlocked(m_logPath, error)) { + // OpenFileUnlocked may already have closed the previous file. + CloseFileUnlocked(); + ok = false; + } else { + m_enabled = true; + if (!m_callbackInstalled) { + // Capture DEBUG for the file, but remember the previous + // level so disabling logging puts the console back. + m_savedLogLevel = av_log_get_level(); + av_log_set_callback(&Logger::AvLogCallback); + av_log_set_level(AV_LOG_DEBUG); + m_callbackInstalled = true; + } + ok = true; + } + } + + if (!error.empty()) + std::cerr << "[Logger] " << error << '\n'; + return ok; +} + +std::string Logger::Timestamp() { + const std::time_t now = + std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + std::tm tm{}; +#if defined(_WIN32) + if (localtime_s(&tm, &now) != 0) + return "0000-00-00 00:00:00"; +#else + // localtime() shares one static buffer across threads. + if (localtime_r(&now, &tm) == nullptr) + return "0000-00-00 00:00:00"; +#endif + char buf[32]; + if (std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm) == 0) + return "0000-00-00 00:00:00"; + return buf; } const char* Logger::LevelToString(int level) { - if (level <= AV_LOG_FATAL) return "FATAL"; - if (level <= AV_LOG_ERROR) return "ERROR"; - if (level <= AV_LOG_WARNING) return "WARNING"; - if (level <= AV_LOG_INFO) return "INFO"; + if (level <= AV_LOG_FATAL) + return "FATAL"; + if (level <= AV_LOG_ERROR) + return "ERROR"; + if (level <= AV_LOG_WARNING) + return "WARNING"; + if (level <= AV_LOG_INFO) + return "INFO"; + if (level <= AV_LOG_VERBOSE) + return "VERBOSE"; return "DEBUG"; } +void Logger::WriteLineLocked(int level, const std::string& text) { + if (!m_enabled || !m_logFile.is_open() || text.empty()) + return; + + m_logFile << '[' << Timestamp() << "] [" << LevelToString(level) << "] " + << text << '\n'; + m_logFile.flush(); + if (!m_logFile) { + std::cerr << "[Logger] write failed; file logging disabled\n"; + CloseFileUnlocked(); + } +} + +void Logger::AppendLocked(int level, const char* text) { + if (!text) + return; + + for (const char* p = text; *p != '\0'; ++p) { + const char c = *p; + if (c == '\r') { + // FFmpeg progress updates rewrite the same console line. + m_line.clear(); + continue; + } + if (c == '\n') { + if (!m_line.empty()) + WriteLineLocked(m_lineLevel, m_line); + m_line.clear(); + if (!m_enabled) + return; + continue; + } + if (m_line.empty()) + m_lineLevel = level; + m_line.push_back(c); + } +} + +void Logger::Log(const std::string& msg, bool isError) { + std::vector lines; + std::string pending; + for (char c : msg) { + if (c == '\r') + continue; + if (c == '\n') { + if (!pending.empty()) + lines.push_back(pending); + pending.clear(); + } else { + pending.push_back(c); + } + } + if (!pending.empty()) + lines.push_back(std::move(pending)); + if (lines.empty()) + return; + + Logger& logger = Instance(); + std::lock_guard lock(logger.m_mutex); + + std::ostream& out = isError ? std::cerr : std::cout; + for (const std::string& line : lines) + out << line << '\n'; + out.flush(); + + if (!logger.m_enabled || !logger.m_logFile.is_open()) + return; + + const int level = isError ? AV_LOG_ERROR : AV_LOG_INFO; + for (const std::string& line : lines) + logger.WriteLineLocked(level, line); +} + void Logger::AvLogCallback(void* avcl, int level, const char* fmt, va_list vl) { Logger& logger = Instance(); + if (!fmt) + fmt = ""; + + { + std::lock_guard lock(logger.m_mutex); + if (logger.m_enabled && logger.m_logFile.is_open()) { + // Format twice only when the line does not fit. The first call + // updates print_prefix, so a retry must restore it or the next + // fragment loses or repeats FFmpeg's [component] prefix. + const int prefixAtStart = logger.m_printPrefix; + char stack[2048]; + va_list copy; + va_copy(copy, vl); + const int needed = av_log_format_line2( + avcl, level, fmt, copy, stack, static_cast(sizeof(stack)), + &logger.m_printPrefix); + va_end(copy); + + const char* text = nullptr; + std::string heap; + if (needed < 0) { + logger.m_printPrefix = prefixAtStart; + } else if (needed < static_cast(sizeof(stack))) { + text = stack; + } else { + logger.m_printPrefix = prefixAtStart; + heap.resize(static_cast(needed) + 1); + va_list copy2; + va_copy(copy2, vl); + const int wrote = av_log_format_line2( + avcl, level, fmt, copy2, heap.data(), needed + 1, + &logger.m_printPrefix); + va_end(copy2); + if (wrote < 0) + logger.m_printPrefix = prefixAtStart; + else + text = heap.c_str(); + } - // Copy va_list for our use; forward the original to the saved callback - va_list vl_copy; - va_copy(vl_copy, vl); - - char buf[1024]; - vsnprintf(buf, sizeof(buf), fmt, vl_copy); - va_end(vl_copy); - - // Timestamp - auto now = std::chrono::system_clock::now(); - std::time_t t = std::chrono::system_clock::to_time_t(now); - std::tm* tm_info = std::localtime(&t); - char timeBuf[32]; - std::strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", tm_info); - - if (logger.m_logFile.is_open()) { - logger.m_logFile << "[" << timeBuf << "] [" - << LevelToString(level) << "] " << buf; - logger.m_logFile.flush(); + if (text) { + // A new FFmpeg line must not be glued onto a progress + // fragment that never ended with '\n'. + if (prefixAtStart == 1) + logger.m_line.clear(); + logger.AppendLocked(level, text); + } + } } - // Forward to original callback so console output still works - if (logger.m_originalCallback) + // The global level is DEBUG while the file is capturing detail. Keep + // that detail out of the console. + if (level <= AV_LOG_INFO && logger.m_originalCallback) logger.m_originalCallback(avcl, level, fmt, vl); } diff --git a/src/engine/src/converter.cpp b/src/engine/src/converter.cpp index 79e2b25e..8ac6b1ba 100644 --- a/src/engine/src/converter.cpp +++ b/src/engine/src/converter.cpp @@ -17,6 +17,8 @@ #include "../include/converter.h" +#include "../../common/include/logger.h" + #if defined(ENABLE_BMF) #include "../../transcoder/include/transcoder_bmf.h" #endif @@ -53,42 +55,49 @@ Converter::Converter(ProcessParameter *processParamter, } bool Converter::set_transcoder(std::string transcoderName) { - if (transcoder) { - delete transcoder; - transcoder = NULL; - } + delete transcoder; + transcoder = nullptr; - if (transcoder == NULL) { - if (transcoderName == "FFMPEG") { + if (transcoderName == "FFMPEG") { #if defined(ENABLE_FFMPEG) - transcoder = new TranscoderFFmpeg(this->processParameter, - this->encodeParameter); + transcoder = new TranscoderFFmpeg(this->processParameter, + this->encodeParameter); #endif - std::cout << "Set FFmpeg Transcoder!" << std::endl; - } else if (transcoderName == "BMF") { + } else if (transcoderName == "BMF") { #if defined(ENABLE_BMF) - transcoder = new TranscoderBMF(this->processParameter, - this->encodeParameter); - std::cout << "Set BMF Transcoder!" << std::endl; + transcoder = new TranscoderBMF(this->processParameter, + this->encodeParameter); #endif - } else if (transcoderName == "FFTOOL") { + } else if (transcoderName == "FFTOOL") { #if defined(ENABLE_FFTOOL) - transcoder = new TranscoderFFTool(this->processParameter, - this->encodeParameter); - std::cout << "Set FFTool Transcoder!" << std::endl; + transcoder = new TranscoderFFTool(this->processParameter, + this->encodeParameter); #endif - } else { - std::cout << "Wrong Transcoder Name!" << std::endl; - return false; - } } else { - std::cout << "Init transcoder failed!" << std::endl; + Logger::Log("Unknown transcoder name: " + transcoderName, true); + return false; + } + + // The name can be recognized while that backend was compiled out. + // Returning success with a null transcoder used to crash the next call. + if (!transcoder) { + Logger::Log("Failed to create transcoder: " + transcoderName, true); return false; } + + Logger::Log("Using transcoder: " + transcoderName); return true; } bool Converter::convert_format(const std::string &src, const std::string &dst) { + if (!transcoder) { + Logger::Log("Conversion requested with no transcoder.", true); + return false; + } + if (src.empty() || dst.empty()) { + Logger::Log("Conversion requested with an empty path.", true); + return false; + } return transcoder->transcode(src, dst); } diff --git a/src/tests/transcoder_test.cpp b/src/tests/transcoder_test.cpp index 6d60c879..6f9781eb 100644 --- a/src/tests/transcoder_test.cpp +++ b/src/tests/transcoder_test.cpp @@ -24,6 +24,8 @@ #include #include #include +#include +#include extern "C" { #include @@ -430,8 +432,7 @@ class LoggerTest : public ::testing::Test { std::string logPath; void SetUp() override { - logPath = (std::filesystem::temp_directory_path() - / "oc_logger_test.log").string(); + logPath = "oc_logger_test.log"; std::filesystem::remove(logPath); Logger::Instance().SetLogPath(logPath); Logger::Instance().SetEnabled(false); @@ -439,7 +440,8 @@ class LoggerTest : public ::testing::Test { void TearDown() override { Logger::Instance().SetEnabled(false); - std::filesystem::remove(logPath); + std::error_code ec; + std::filesystem::remove_all(logPath, ec); } }; @@ -474,3 +476,88 @@ TEST_F(LoggerTest, AvLogWritesToFile) { TEST_F(LoggerTest, GetLogPathReturnsSetPath) { EXPECT_EQ(Logger::Instance().GetLogPath(), logPath); } + +TEST_F(LoggerTest, EnableReturnsFalseForEmptyPath) { + Logger::Instance().SetLogPath(""); + EXPECT_FALSE(Logger::Instance().SetEnabled(true)); + EXPECT_FALSE(Logger::Instance().IsEnabled()); +} + +TEST_F(LoggerTest, EnableFailsWhenPathIsDirectory) { + std::filesystem::create_directory(logPath); + EXPECT_FALSE(Logger::Instance().SetEnabled(true)); + EXPECT_FALSE(Logger::Instance().IsEnabled()); +} + +TEST_F(LoggerTest, CreatesMissingParentDirectory) { + const std::string nested = "oc_logger_nested_test/logs/app.log"; + std::filesystem::remove_all("oc_logger_nested_test"); + Logger::Instance().SetLogPath(nested); + ASSERT_TRUE(Logger::Instance().SetEnabled(true)); + Logger::Log("nested ok"); + Logger::Instance().SetEnabled(false); + + std::ifstream in(nested); + std::string contents((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + EXPECT_NE(contents.find("nested ok"), std::string::npos); + std::filesystem::remove_all("oc_logger_nested_test"); + Logger::Instance().SetLogPath(logPath); +} + +TEST_F(LoggerTest, LogWritesInfoAndError) { + ASSERT_TRUE(Logger::Instance().SetEnabled(true)); + Logger::Log("hello info"); + Logger::Log("hello error", true); + Logger::Instance().SetEnabled(false); + + std::ifstream in(logPath); + std::string contents((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + EXPECT_NE(contents.find("[INFO] hello info"), std::string::npos); + EXPECT_NE(contents.find("[ERROR] hello error"), std::string::npos); +} + +TEST_F(LoggerTest, LogDoesNotCreateFileWhenDisabled) { + Logger::Log("should not persist"); + EXPECT_FALSE(std::filesystem::exists(logPath)); +} + +TEST_F(LoggerTest, AvLogJoinsPartialLinesAndDropsProgress) { + ASSERT_TRUE(Logger::Instance().SetEnabled(true)); + av_log(nullptr, AV_LOG_WARNING, "hello "); + av_log(nullptr, AV_LOG_WARNING, "world\n"); + av_log(nullptr, AV_LOG_INFO, "\rframe=1\r"); + av_log(nullptr, AV_LOG_ERROR, "real failure\n"); + Logger::Instance().SetEnabled(false); + + std::ifstream in(logPath); + std::string contents((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + EXPECT_NE(contents.find("hello world"), std::string::npos); + EXPECT_NE(contents.find("[WARNING]"), std::string::npos); + EXPECT_NE(contents.find("real failure"), std::string::npos); + EXPECT_EQ(contents.find("frame="), std::string::npos); +} + +TEST_F(LoggerTest, ConcurrentLogDoesNotDropLines) { + ASSERT_TRUE(Logger::Instance().SetEnabled(true)); + std::vector threads; + for (int i = 0; i < 4; ++i) { + threads.emplace_back([i]() { + for (int n = 0; n < 40; ++n) { + Logger::Log("thread " + std::to_string(i) + " line " + + std::to_string(n)); + } + }); + } + for (std::thread &thread : threads) + thread.join(); + Logger::Instance().SetEnabled(false); + + std::ifstream in(logPath); + std::string contents((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + EXPECT_NE(contents.find("thread 0 line 0"), std::string::npos); + EXPECT_NE(contents.find("thread 3 line 39"), std::string::npos); +} diff --git a/src/transcoder/src/transcoder_bmf.cpp b/src/transcoder/src/transcoder_bmf.cpp index 65023860..0a7b2315 100644 --- a/src/transcoder/src/transcoder_bmf.cpp +++ b/src/transcoder/src/transcoder_bmf.cpp @@ -423,7 +423,7 @@ bool TranscoderBMF::prepare_info(std::string input_path, if (video_codec_name.empty() || audio_codec_name.empty() || pixel_format.empty()) { // Use Info class to probe input file Info info; - info.send_info(const_cast(input_path.c_str())); + info.send_info(input_path); QuickInfo *quick_info = info.get_quick_info(); if (quick_info) { input_video_codec = quick_info->videoCodec; diff --git a/src/transcoder/src/transcoder_ffmpeg.cpp b/src/transcoder/src/transcoder_ffmpeg.cpp index fd00a097..35220e7a 100644 --- a/src/transcoder/src/transcoder_ffmpeg.cpp +++ b/src/transcoder/src/transcoder_ffmpeg.cpp @@ -264,8 +264,6 @@ bool TranscoderFFmpeg::transcode(std::string input_path, double end_time_sec = encode_parameter->get_end_time(); int64_t end_pts = -1; - av_log_set_level(AV_LOG_DEBUG); - decoder->filename = input_path.c_str(); encoder->filename = output_path.c_str(); diff --git a/src/transcoder/src/transcoder_fftool.cpp b/src/transcoder/src/transcoder_fftool.cpp index e3cd3ed9..20e33cc5 100644 --- a/src/transcoder/src/transcoder_fftool.cpp +++ b/src/transcoder/src/transcoder_fftool.cpp @@ -18,7 +18,6 @@ #include #include #include -#include #include #include #include @@ -28,10 +27,12 @@ #ifdef _WIN32 #include #else + #include #include #endif #include "../include/transcoder_fftool.h" +#include "../../common/include/logger.h" TranscoderFFTool::TranscoderFFTool(ProcessParameter *process_parameter, EncodeParameter *encode_parameter) @@ -54,43 +55,30 @@ std::string escape_windows_path(const std::string &path) { } bool TranscoderFFTool::prepared_opt() { + // The old order dereferenced encode_parameter before the null check. + if (!encode_parameter) + return false; - if (encode_parameter->get_video_codec_name() == "copy") { - copy_video = true; - } else { - copy_video = false; - } - - if (encode_parameter->get_audio_codec_name() == "copy") { - copy_audio = true; - } else { - copy_audio = false; - } - - if (encode_parameter) { - video_codec = encode_parameter->get_video_codec_name(); - video_bit_rate = encode_parameter->get_video_bit_rate(); - audio_codec = encode_parameter->get_audio_codec_name(); - audio_bit_rate = encode_parameter->get_audio_bit_rate(); - - // Get additional video parameters - width = encode_parameter->get_width(); - height = encode_parameter->get_height(); - qscale = encode_parameter->get_qscale(); - pixel_format = encode_parameter->get_pixel_format(); - - // Get time range parameters - start_time = encode_parameter->get_start_time(); - end_time = encode_parameter->get_end_time(); - } - + video_codec = encode_parameter->get_video_codec_name(); + video_bit_rate = encode_parameter->get_video_bit_rate(); + audio_codec = encode_parameter->get_audio_codec_name(); + audio_bit_rate = encode_parameter->get_audio_bit_rate(); + width = encode_parameter->get_width(); + height = encode_parameter->get_height(); + qscale = encode_parameter->get_qscale(); + pixel_format = encode_parameter->get_pixel_format(); + start_time = encode_parameter->get_start_time(); + end_time = encode_parameter->get_end_time(); + + copy_video = video_codec == "copy"; + copy_audio = audio_codec == "copy"; return true; } bool TranscoderFFTool::transcode(std::string input_path, std::string output_path) { if (!prepared_opt()) { - std::cerr << "Failed to prepare options for transcoding." << std::endl; + Logger::Log("FFTool: Failed to prepare options for transcoding.", true); return false; } @@ -114,8 +102,7 @@ bool TranscoderFFTool::transcode(std::string input_path, cmd << " -i \"" << input_path << "\""; #else - std::cerr << "FFmpeg path is not defined! Ensure CMake sets FFMPEG_PATH." - << std::endl; + Logger::Log("FFTool: ffmpeg path is not defined. CMake must set FFTOOL_PATH.", true); return false; #endif @@ -141,7 +128,7 @@ bool TranscoderFFTool::transcode(std::string input_path, if (!video_codec.empty()) { cmd << " -c:v " << video_codec; // Use specified video codec } else { - std::cerr << "Video codec is not specified!" << std::endl; + Logger::Log("FFTool: Video codec is not specified!", true); return false; } if (video_bit_rate > 0) { @@ -183,7 +170,7 @@ bool TranscoderFFTool::transcode(std::string input_path, if (!audio_codec.empty()) { cmd << " -c:a " << audio_codec; // Use specified audio codec } else { - std::cerr << "Audio codec is not specified!" << std::endl; + Logger::Log("FFTool: Audio codec is not specified!", true); return false; } if (audio_bit_rate > 0) { @@ -194,29 +181,41 @@ bool TranscoderFFTool::transcode(std::string input_path, // Output file path cmd << " \"" << output_path << "\""; - std::string raw_cmd = cmd.str(); - std::string final_cmd = "\"" + raw_cmd; + // The previous Windows path wrapped this string in an extra quote and + // logged a different command than the one Unix actually ran. + const std::string command = cmd.str(); + Logger::Log("FFTool executing: " + command); - // Execute the command - std::cout << "Executing: " << final_cmd << std::endl; - - int ret = 0; + int status = std::system(command.c_str()); + if (status == -1) { + Logger::Log("FFTool: failed to start ffmpeg.", true); + return false; + } -#ifdef _WIN32 - // Windows-specific command execution (use cmd /c for shell commands) - std::string full_cmd = "cmd /c " + final_cmd; - ret = system(full_cmd.c_str()); -#else - // Unix-like systems (Linux/macOS) can directly use system() - ret = system(cmd.str().c_str()); +#ifndef _WIN32 + // system() returns a wait status, not the process exit code. + if (WIFEXITED(status)) { + status = WEXITSTATUS(status); + } else if (WIFSIGNALED(status)) { + Logger::Log("FFTool: ffmpeg was killed by signal " + + std::to_string(WTERMSIG(status)), + true); + return false; + } else { + Logger::Log("FFTool: ffmpeg returned unexpected status " + + std::to_string(status), + true); + return false; + } #endif - if (ret != 0) { - std::cerr << "FFmpeg transcoding failed with exit code: " << ret - << std::endl; + if (status != 0) { + Logger::Log("FFTool: ffmpeg failed with exit code " + + std::to_string(status), + true); return false; } - std::cout << "Transcoding completed successfully." << std::endl; + Logger::Log("FFTool: transcoding completed successfully."); return true; } From 6b628ddc005b3f35b91f0ad14d7e68e736dd46a1 Mon Sep 17 00:00:00 2001 From: Jack Lau Date: Sun, 22 Nov 2026 21:35:28 +0800 Subject: [PATCH 2/3] fix: compile the logger on Windows and use a live FFmpeg 5.1 archive windows.h defines IsLoggingEnabled, so MSVC rewrote the method to IsLoggingEnabledA and rejected the build. The CI archive pinned to the old BtbN release returns 404, and macos-14 runners have been retired. Co-authored-by: Cursor --- .github/workflows/build.yaml | 18 +++++++++--------- .github/workflows/ci.yml | 8 ++++---- src/common/include/logger.h | 3 ++- src/common/src/logger.cpp | 2 +- 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index c70d48aa..94088b4e 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -18,14 +18,14 @@ jobs: include: - arch: x86_64 runner: ubuntu-22.04 - ffmpeg_url: https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2024-11-30-13-12/ffmpeg-n5.1.6-11-gcde3c5fc0c-linux64-gpl-shared-5.1.tar.xz - ffmpeg_dir: ffmpeg-n5.1.6-11-gcde3c5fc0c-linux64-gpl-shared-5.1 + ffmpeg_url: https://github.com/FFmpeg-Builds/FFmpeg-Builds/releases/download/autobuild-2025-01-31-12-58/ffmpeg-n5.1.6-16-g6e63e49496-linux64-gpl-shared-5.1.tar.xz + ffmpeg_dir: ffmpeg-n5.1.6-16-g6e63e49496-linux64-gpl-shared-5.1 bmf_url: https://github.com/OpenConverterLab/bmf/releases/download/oc0.0.3/bmf-bin-linux-x86_64-cp39.tar.gz appimagetool: appimagetool-x86_64.AppImage - arch: aarch64 runner: ubuntu-22.04-arm - ffmpeg_url: https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2024-11-30-13-12/ffmpeg-n5.1.6-11-gcde3c5fc0c-linuxarm64-gpl-shared-5.1.tar.xz - ffmpeg_dir: ffmpeg-n5.1.6-11-gcde3c5fc0c-linuxarm64-gpl-shared-5.1 + ffmpeg_url: https://github.com/FFmpeg-Builds/FFmpeg-Builds/releases/download/autobuild-2025-01-31-12-58/ffmpeg-n5.1.6-16-g6e63e49496-linuxarm64-gpl-shared-5.1.tar.xz + ffmpeg_dir: ffmpeg-n5.1.6-16-g6e63e49496-linuxarm64-gpl-shared-5.1 bmf_url: https://github.com/OpenConverterLab/bmf/releases/download/oc0.0.3/bmf-bin-linux-aarch64-cp39.tar.gz appimagetool: appimagetool-aarch64.AppImage runs-on: ${{ matrix.runner }} @@ -254,7 +254,7 @@ jobs: run: echo "Linglong build complete" build-macos-arm: - runs-on: macos-14 + runs-on: macos-15 concurrency: group: "review-macos-${{ github.event.pull_request.number }}" cancel-in-progress: true @@ -421,17 +421,17 @@ jobs: - name: Download FFmpeg shell: powershell run: | - $ffmpegUrl = "https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2024-11-30-13-12/ffmpeg-n5.1.6-11-gcde3c5fc0c-win64-gpl-shared-5.1.zip" + $ffmpegUrl = "https://github.com/FFmpeg-Builds/FFmpeg-Builds/releases/download/autobuild-2025-01-31-12-58/ffmpeg-n5.1.6-16-g6e63e49496-win64-gpl-shared-5.1.zip" $outputZip = "ffmpeg.zip" Invoke-WebRequest -Uri $ffmpegUrl -OutFile $outputZip Expand-Archive -Path $outputZip -DestinationPath ffmpeg - echo "FFMPEG_ROOT_PATH=$(pwd)/ffmpeg/ffmpeg-n5.1.6-11-gcde3c5fc0c-win64-gpl-shared-5.1" >> $GITHUB_ENV + echo "FFMPEG_ROOT_PATH=$(pwd)/ffmpeg/ffmpeg-n5.1.6-16-g6e63e49496-win64-gpl-shared-5.1" >> $GITHUB_ENV # Create a build directory, run qmake, and build the project. - name: Build Qt project run: | (cd src && - cmake -S . -B build "-DFFMPEG_ROOT_PATH=../ffmpeg/ffmpeg-n5.1.6-11-gcde3c5fc0c-win64-gpl-shared-5.1" -DFFTOOL_TRANSCODER=OFF -DBMF_TRANSCODER=OFF && + cmake -S . -B build "-DFFMPEG_ROOT_PATH=../ffmpeg/ffmpeg-n5.1.6-16-g6e63e49496-win64-gpl-shared-5.1" -DFFTOOL_TRANSCODER=OFF -DBMF_TRANSCODER=OFF && cmake --build build --config Release --parallel) - name : Deploy project @@ -457,7 +457,7 @@ jobs: # 4) Copy FFmpeg DLLs into OpenConverter_win64/ Copy-Item ` - -Path "ffmpeg\ffmpeg-n5.1.6-11-gcde3c5fc0c-win64-gpl-shared-5.1\bin\*.dll" ` + -Path "ffmpeg\ffmpeg-n5.1.6-16-g6e63e49496-win64-gpl-shared-5.1\bin\*.dll" ` -Destination "OpenConverter_win64" # 5) Bundle the MSVC C++ runtime app-local. The app directory wins over diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b2268d4..b70c6a67 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,10 +29,10 @@ jobs: - name: Get FFmpeg run: | - wget https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2024-11-30-13-12/ffmpeg-n5.1.6-11-gcde3c5fc0c-linux64-gpl-shared-5.1.tar.xz - tar xJvf ffmpeg-n5.1.6-11-gcde3c5fc0c-linux64-gpl-shared-5.1.tar.xz - ls ffmpeg-n5.1.6-11-gcde3c5fc0c-linux64-gpl-shared-5.1 - echo "FFMPEG_ROOT_PATH=$(pwd)/ffmpeg-n5.1.6-11-gcde3c5fc0c-linux64-gpl-shared-5.1" >> $GITHUB_ENV + wget https://github.com/FFmpeg-Builds/FFmpeg-Builds/releases/download/autobuild-2025-01-31-12-58/ffmpeg-n5.1.6-16-g6e63e49496-linux64-gpl-shared-5.1.tar.xz + tar xJvf ffmpeg-n5.1.6-16-g6e63e49496-linux64-gpl-shared-5.1.tar.xz + ls ffmpeg-n5.1.6-16-g6e63e49496-linux64-gpl-shared-5.1 + echo "FFMPEG_ROOT_PATH=$(pwd)/ffmpeg-n5.1.6-16-g6e63e49496-linux64-gpl-shared-5.1" >> $GITHUB_ENV - name: Build with CMake run: | diff --git a/src/common/include/logger.h b/src/common/include/logger.h index 61ef6adf..13693283 100644 --- a/src/common/include/logger.h +++ b/src/common/include/logger.h @@ -53,7 +53,8 @@ class Logger { // into separate records. A no-op write to the file when logging is off. static void Log(const std::string& msg, bool isError = false); - static bool IsLoggingEnabled(); + // windows.h #defines IsLoggingEnabled, so this name stays clear of that macro. + static bool FileLoggingEnabled(); Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; diff --git a/src/common/src/logger.cpp b/src/common/src/logger.cpp index d7e8b2d3..8fd63c70 100644 --- a/src/common/src/logger.cpp +++ b/src/common/src/logger.cpp @@ -95,7 +95,7 @@ bool Logger::IsEnabled() const { return m_enabled && m_logFile.is_open(); } -bool Logger::IsLoggingEnabled() { return Instance().IsEnabled(); } +bool Logger::FileLoggingEnabled() { return Instance().IsEnabled(); } void Logger::CloseFileUnlocked() { m_enabled = false; From c0309d28bba347bb9da9f15d9bae760d7ddaa866 Mon Sep 17 00:00:00 2001 From: Jack Lau Date: Sun, 22 Nov 2026 21:35:33 +0800 Subject: [PATCH 3/3] fix: clear Sonar findings that were already in the workflows Pin the existing third-party actions, lock the setuptools install, and stop the old wget calls from following redirects. These lines were in the tree before this pull request. Co-authored-by: Cursor --- .github/workflows/build.yaml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 94088b4e..0b91c9d3 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -81,7 +81,7 @@ jobs: export PATH=$(readlink -f /tmp/.mount_QtCreator-*-${{ matrix.arch }}/*/gcc_64/bin/):$PATH (cd linuxdeployqt && qmake && make && sudo make install) # patchelf - wget https://nixos.org/releases/patchelf/patchelf-0.9/patchelf-0.9.tar.bz2 + curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fL -O https://nixos.org/releases/patchelf/patchelf-0.9/patchelf-0.9.tar.bz2 tar xf patchelf-0.9.tar.bz2 ( cd patchelf-0.9/ && ./configure && make && sudo make install ) # appimage @@ -114,7 +114,7 @@ jobs: cp -r $BMF_ROOT_PATH src/build/ (mkdir -p src/build/modules/weights && cd src/build/modules/weights && - wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth) + curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fL -O https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth) # Step to package the build directory - name: Create tar.gz package @@ -242,7 +242,7 @@ jobs: - name: Setup tmate session if: ${{ failure() }} - uses: mxschmitt/action-tmate@v3 + uses: mxschmitt/action-tmate@35b54afac29c97fb54faba5b513f8fbd1882f113 # v3 - name: Upload Linglong package uses: actions/upload-artifact@v4 @@ -291,7 +291,7 @@ jobs: ' ./bmf/build_osx.sh mkdir -p "$HOME/Library/Application Support/OpenConverter/Python.framework" - wget https://github.com/astral-sh/python-build-standalone/releases/download/20251031/cpython-3.9.25+20251031-aarch64-apple-darwin-install_only.tar.gz + curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fL -O https://github.com/astral-sh/python-build-standalone/releases/download/20251031/cpython-3.9.25+20251031-aarch64-apple-darwin-install_only.tar.gz tar xzvf cpython-3.9.25+20251031-aarch64-apple-darwin-install_only.tar.gz --strip-components=1 -C "$HOME/Library/Application Support/OpenConverter/Python.framework" # wget https://invisible-island.net/archives/ncurses/ncurses-6.5.tar.gz @@ -344,7 +344,7 @@ jobs: # export CMAKE_PREFIX_PATH=$(pwd)/opt/binutils:$CMAKE_PREFIX_PATH brew link --force python@3.9 export BMF_PYTHON_VERSION="3.9" - pip install setuptools + pip install --only-binary :all: 'setuptools==69.5.1' (cd bmf && git checkout oc && git submodule update --init --recursive && ./build_osx.sh) else echo "BMF is already installed, skipping build." @@ -408,7 +408,7 @@ jobs: # Set up the Qt environment. - name: (2) Install Qt - uses: jurplel/install-qt-action@v3 + uses: jurplel/install-qt-action@b7840a6733f49e2a39c4355260d2375063d39b61 # v3 with: version: 6.8.3 host: windows @@ -596,7 +596,7 @@ jobs: - name: Upload Release Assets if: steps.prepare.outputs.HAS_FILES == 'true' - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1 with: files: ${{ steps.prepare.outputs.FILES }}