% =======================================================================================
%   WARLOCK-STUDIO 4.0 - USER MANUAL & TECHNICAL DOCUMENTATION
% =======================================================================================
% Manual Version: 8.0 (Updated Edition)
% Author: Iván Eduardo Chavez Ayub (Reviewed and Improved by AI)
%
% This document is a robust and professional LaTeX template designed for
% technical manuals. It includes a clear structure, custom styles, and a
% configuration optimized for readability and aesthetics.
% =======================================================================================


% ---------------------------------------------------------------------------------------
%   DOCUMENT SETUP
% ---------------------------------------------------------------------------------------
% \documentclass defines the document type and base options.
% - 11pt: Base font size. A good balance between density and readability.
% - a4paper: Defines the standard international paper size.
\documentclass[11pt, a4paper]{article}


% %%% --- PACKAGE IMPORTS --- %%%
% Packages add new functionalities to LaTeX.

% --- Essential Packages ---
\usepackage[utf8]{inputenc}             % Allows writing UTF-8 characters (like accents) directly.
\usepackage[T1]{fontenc}                % Modern font encoding for correct display and copying from PDF.
\usepackage[english]{babel}             % Support for the English language (hyphenation, etc.).

% --- Page Layout and Design ---
\usepackage{geometry}                   % For configuring margins and page layout.
\usepackage{graphicx}                   % For including images (\includegraphics).
\usepackage{fancyhdr}                   % For customizing headers and footers.
\usepackage{xcolor}                     % To use colors by name or code (HTML, RGB, etc.).
\usepackage{float}                      % Provides the [H] specifier to "float exactly here".

% --- Typography and Text Style ---
% \usepackage{firasans}                 % EXAMPLE: Modern Sans-Serif font (keep commented if not installed).
\usepackage{textcomp}                   % Provides additional symbols like the copyright symbol.
\usepackage{fontawesome5}               % Allows using Font Awesome icons (e.g., \faInfoCircle).

% --- Tables, Lists, and Boxes ---
\usepackage{booktabs}                   % For creating professional-looking tables (\toprule, \midrule, \bottomrule).
\usepackage{longtable}                  % For tables that can span multiple pages.
\usepackage{tabularx}                   % For tables with flexible-width columns that occupy the full text width.
\usepackage{array}                      % Advanced tools for table columns.
\usepackage{enumitem}                   % For advanced control over the format of lists (itemize, enumerate).
\usepackage{tcolorbox}                  % For creating colored and customizable text boxes.
\usepackage{titlesec}                   % For customizing the format of section titles (\section, \subsection).
\usepackage{titletoc}                   % Control over the table of contents.

% --- Utilities and Links ---
\usepackage{hyperref}                   % To create hyperlinks within the document and to external URLs.
                                        % It's good practice to load it last.


% %%% --- PAGE GEOMETRY SETUP --- %%%
% Defines the margins and spaces for the header/footer.
\geometry{
  a4paper,          % Paper size
  margin=2.5cm,     % Uniform margin for all sides
  headheight=15pt,  % Height reserved for the header
  footskip=30pt     % Distance from the bottom of the text to the footer
}


% %%% --- CUSTOM COLOR PALETTE --- %%%
% A corporate color palette is defined to maintain visual consistency.
% The HTML model is used for easy selection from design tools.
\definecolor{WarlockRed}{HTML}{C11919}
\definecolor{WarlockGold}{HTML}{ECD125}
\definecolor{WarlockDark}{HTML}{212325}
\definecolor{WarlockGray}{HTML}{333333}
\definecolor{WarlockLightGray}{HTML}{F5F5F5}
\definecolor{WarlockBlue}{HTML}{005A9B}
\definecolor{InfoBlue}{HTML}{E7F3FE}
\definecolor{WarnYellow}{HTML}{FFFBE6}
\definecolor{WarnBorder}{HTML}{FFBE0B}

% Sets the default text color for the entire document.
\color{WarlockGray}


% %%% --- HYPERLINK CONFIGURATION --- %%%
% Customizes the appearance of links generated by 'hyperref'.
\hypersetup{
    colorlinks=true,                  % Links will be colored instead of boxed.
    linkcolor=WarlockRed,             % Color for internal links (to sections, figures, etc.).
    filecolor=WarlockRed,             % Color for links to local files.
    urlcolor=WarlockRed,              % Color for links to external URLs.
    pdftitle={Warlock-Studio 4.0 User Manual & Technical Documentation}, % PDF metadata.
    pdfauthor={Iván Eduardo Chavez Ayub (Reviewed by AI)}             % PDF metadata.
}


% %%% --- SECTION TITLE STYLE --- %%%
% 'titlesec' is used to define a custom style for sections.
% \titleformat{<command>}[<shape>]{<format>}{<label>}{<sep>}{<before-code>}
\titleformat{\section}
  {\normalfont\Large\bfseries\color{WarlockRed}} % Title format: Normal font, Large, bold, red color.
  {\thesection.}                                 % Label: The section number followed by a period.
  {1em}                                          % Horizontal separation between the label and the title.
  {}                                             % Code to execute before the title (none in this case).

\titleformat{\subsection}
  {\normalfont\large\bfseries\color{WarlockRed!70!black}} % Similar to \section, but with a darker color.
  {\thesubsection.}
  {1em}
  {}

% \titlespacing*{<command>}{<left-space>}{<before-space>}{<after-space>}
\titlespacing*{\section}
  {0pt}                 % Space to the left of the title.
  {3.5ex plus 1ex minus .2ex} % Vertical space BEFORE the title (with flexibility).
  {2.3ex plus .2ex}     % Vertical space AFTER the title (with flexibility).


% %%% --- CUSTOM TEXT BOX DEFINITIONS --- %%%
% 'tcolorbox' is used to create "box" environments for information and warnings.
\tcbuselibrary{skins, breakable} % Additional libraries are loaded for more styles.
                                          % 'breakable' allows boxes to split across pages.

% Box for general information.
\newtcolorbox{infobox}{
    colback=InfoBlue,                       % Background color of the box.
    colframe=WarlockBlue,                   % Border color.
    fonttitle=\bfseries,                    % Font for the box title (bold).
    coltitle=WarlockBlue,                   % Color of the title text.
    title=\faInfoCircle\hspace{0.5em} Information, % Title content (icon + text).
    breakable,                              % Allows the box to split across pages.
    pad at break=2mm,                       % Internal padding when the box breaks.
    enhanced,                               % Activates advanced rendering modes.
    % drop shadow={WarlockGray!50!white}      % Shadow effects removed due to library compatibility
}

% Box for important warnings.
\newtcolorbox{warnbox}{
    colback=WarnYellow,
    colframe=WarnBorder,
    fonttitle=\bfseries,
    coltitle=WarnBorder!80!black,
    title=\faExclamationTriangle\hspace{0.5em} Warning,
    breakable,
    pad at break=2mm,
    enhanced,
    % drop shadow={WarnBorder!50!white}    % Shadow effects removed due to library compatibility
}

% Custom command to format inline code.
% \newcommand{<name>}[<args>]{<definition>}
\newcommand{\inlinecode}[1]{\colorbox{WarlockLightGray}{\small\texttt{#1}}}


% %%% --- HEADER AND FOOTER SETUP --- %%%
% 'fancyhdr' is used to control the content of headers and footers.
\pagestyle{fancy}
\fancyhf{} % Clears all header and footer fields.

% \fancyhead[L/C/R]{...} defines the header content (Left, Center, Right).
\fancyhead[L]{\textit{Warlock-Studio 4.0}}
\fancyhead[R]{\leftmark} % \leftmark displays the current section name.

% \fancyfoot[L/C/R]{...} defines the footer content.
\fancyfoot[L]{\includegraphics[height=0.8cm]{logo.png}} % Assumes 'logo.png' is in the same folder.
\fancyfoot[C]{\thepage} % Displays the current page number.
\fancyfoot[R]{\textcopyright~2025 Warlock-Studio}

% Defines the thickness of the separator lines.
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}

% Redefines how the section mark is generated to include the number.
\renewcommand{\sectionmark}[1]{\markboth{\thesection. #1}{}}


% =======================================================================================
%   BEGIN DOCUMENT BODY
% =======================================================================================
\begin{document}

% %%% --- TITLE PAGE --- %%%
% A striking and professional cover page is created using a full-page 'tcolorbox'.
\begin{titlepage}
    \begin{tcolorbox}[
        %--- Box Style ---
        colback=WarlockDark,                    % Dark background.
        colframe=WarlockGold,                   % Gold border.
        sharp corners,                          % Straight corners instead of rounded.
        boxrule=1.5pt,                          % Border thickness.
        %--- Alignment and Size ---
        halign=center,                          % Horizontal content alignment.
        valign=center,                          % Vertical content alignment.
        height=\dimexpr\textheight-1cm\relax    % Box height (full text height minus 1cm).
      ]
      %--- Cover Page Content ---
      \centering % Centers the internal elements.

      \includegraphics[width=0.5\textwidth]{logo.png}\par % Logo.

      \vfill % Flexible space to push content.

      \color{white} % Changes text color to white for contrast.

      {\Huge\bfseries Warlock-Studio\par}
      \vspace{0.7cm} % Fixed vertical space.
      {\Large -- User Manual \& Technical Documentation --\par}
      \vspace{0.2cm}
      {\Large Version 4.0\par}

      \vfill % Another flexible space.

      {\large Iván Eduardo Chavez Ayub\par}
      \href{https://github.com/Ivan-Ayub97}{\texttt{\color{WarlockGold}@Ivan-Ayub97 on GitHub}}\par % Styled link.

      \vspace{1.5cm}

      {\large \today\par} % Displays the compilation date.
    \end{tcolorbox}
    \thispagestyle{empty} % Hides header and footer on the cover page.
\end{titlepage}


% %%% --- ABSTRACT AND TABLE OF CONTENTS --- %%%
\pagestyle{fancy} % Restores the 'fancy' page style after the cover page.

% The 'abstract' environment creates a summary of the document.
\begin{abstract}
\noindent % Prevents indentation on the first line.
\textbf{Warlock-Studio 4.0 Technical Documentation}

This comprehensive technical manual serves as the definitive guide for Warlock-Studio 4.0 "SuperResolution Revolution". The documentation encompasses detailed architectural analysis, implementation specifics, optimization strategies, and comprehensive troubleshooting procedures. Information has been validated through extensive source code analysis and real-world testing scenarios.

\textbf{Target Audience:} Technical users, system administrators, content creators, and AI enthusiasts seeking in-depth understanding of AI-powered media enhancement workflows.

\textbf{Coverage:} Installation procedures, system architecture, AI model specifications, performance optimization, error resolution, and advanced use cases.
\end{abstract}

\newpage % Page break before the table of contents.
\tableofcontents % Generates the table of contents automatically.
\newpage % Page break after the table of contents.


% %%% --- MAIN BODY OF THE MANUAL --- %%%

% --- Section 1: Introduction ---
\section{Introduction}
Warlock-Studio is an AI-powered media enhancement and upscaling suite, designed to deliver high-quality results through an accessible user interface. Version 4.0 introduces a revolutionary smart AI model distribution system that automatically downloads required components on first launch, reducing installer size from 1.4GB to just 150MB. Additionally, it includes key enhancements in GPU management, error handling, and performance efficiency, solidifying its position as a powerful tool for professional content creators.

\subsection{What's New in Version 4.0 - "SuperResolution Revolution"}
The latest version brings the following key enhancements:
% 'itemize' is used for bulleted lists. [leftmargin=*] aligns the list with the paragraph margin.
\begin{itemize}[leftmargin=*]
    \item \textbf{Smart AI Model Distribution:} Revolutionary lightweight installer (150MB vs 1.4GB) with automatic AI model download system that fetches models (327MB) on first launch.
    \item \textbf{SuperResolution-10 Model Integration:} Revolutionary 10x upscaling capabilities specifically designed for very low-resolution images, perfect for bringing old photos back to life.
    \item \textbf{Enhanced AI Architecture:} Implemented robust `AI\_model\_base` class with comprehensive error handling and GPU acceleration support.
    \item \textbf{Code Quality Improvements:} Fixed critical import errors, consolidated duplicate code sections, and improved type annotations for better maintainability.
    \item \textbf{Improved Error Handling:} Added graceful degradation mechanisms that prevent crashes and provide meaningful error messages.
    \item \textbf{Complete Model Integration:} SuperResolution-10 is fully integrated into UI, processing pipeline, and information dialogs with proper VRAM management.
\end{itemize}

\subsection{Main Features}
\begin{itemize}[leftmargin=*]
    \item \textbf{AI Upscaling:} Uses state-of-the-art models like Real-ESRGAN, BSRGAN, and SRVGGNetCompact.
    \item \textbf{Frame Interpolation:} Increases FPS or creates smooth slow-motion effects using RIFE models.
    \item \textbf{Noise Reduction:} Includes dedicated IRCNN models for cleaning images and videos.
    \item \textbf{Face Restoration:} GFPGAN model for enhancing and restoring faces in photos.
    \item \textbf{Hardware Acceleration:} Uses the ONNX Runtime engine with the DirectML provider (\texttt{DmlExecutionProvider}) for GPU acceleration compatible with DirectX 12.
    \item \textbf{Advanced Video Encoding:} Supports hardware-accelerated encoders from NVIDIA (NVENC), AMD (AMF), and Intel (QSV).
    \item \textbf{Smart Model Distribution:} Automatic AI model download system (327MB) on first launch, reducing installer size from 1.4GB to 150MB.
\end{itemize}


% --- Section 2: Installation ---
\section{Installation and Program Architecture}

\subsection{Smart AI Model Distribution System}
\begin{infobox}
Warlock-Studio 4.0 introduces a revolutionary AI model distribution system that automatically downloads required components during the application's first launch.
\end{infobox}

\subsubsection{Advantages of the New System}
\begin{itemize}[leftmargin=*]
    \item \textbf{Lightweight Installer:} 78\% size reduction (from 1.4GB to ~150MB)
    \item \textbf{Smart Download:} AI models (327MB) are automatically downloaded on first use
    \item \textbf{Multiple Sources:} Redundant URLs (GitHub, SourceForge) ensure availability
    \item \textbf{Progress Tracking:} Visual indicators show download speed and completion percentage
    \item \textbf{Error Recovery:} Automatic retry mechanisms and clear error messages
    \item \textbf{Resume Support:} Interrupted downloads can be resumed seamlessly
\end{itemize}

\subsubsection{Automatic Download Process}
When starting Warlock-Studio for the first time, the system will perform the following operations:
\begin{enumerate}[leftmargin=*]
    \item \textbf{Model Verification:} Checks if AI models are present
    \item \textbf{Confirmation Dialog:} Requests permission to download 327MB of AI models
    \item \textbf{Progressive Download:} Shows real-time progress with visual indicators
    \item \textbf{Integrity Validation:} Verifies that downloaded files are complete
    \item \textbf{Automatic Extraction:} Decompresses and organizes models in the correct structure
\end{enumerate}

\subsubsection{Offline Setup and Manual Configuration}
For users with limited connectivity or specific preferences:
\begin{description}[leftmargin=*, style=nextline]
    \item[Offline Installation:] Models can be downloaded separately and manually placed in the \texttt{AI-onnx} folder
    \item[Manual Location:] Download \texttt{AI-onnx-models.zip} from GitHub Releases and extract to the installation directory
    \item[File Verification:] The application will automatically verify the presence of all required models
\end{description}

\subsection{System Requirements}
% 'table' is used for tables that don't split across pages. [H] forces its position.
\begin{table}[H]
    \centering % Centers the table on the page.
    % 'tabular' is the environment that draws the table. {ll} defines two left-aligned columns.
    \begin{tabular}{ll}
        \toprule % Top line of the table (from booktabs).
        \textbf{Component} & \textbf{Requirement} \\
        \midrule % Middle line of the table (from booktabs).
        Operating System & Windows 10 (64-bit) or later \\
        RAM & 8 GB (Minimum), 16 GB (Recommended) \\
        Graphics Card (GPU) & \textbf{DirectX 12} compatible. \textbf{Recommended: 4+ GB VRAM}. \\
        Storage & 2 GB of free space. An SSD is recommended for better performance. \\
        \bottomrule % Bottom line of the table (from booktabs).
    \end{tabular}
    \caption{Hardware and software requirements for Warlock-Studio 4.0.}
\end{table}

\subsection{File Structure and Dependencies}
\begin{infobox}
Warlock-Studio is a self-contained application. The following components are included in the installation and require no action from the user.
\end{infobox}
\begin{itemize}[leftmargin=*]
    \item \inlinecode{ffmpeg.exe:} Located in the \texttt{Assets} folder, it is the engine for all video manipulation, encoding, and decoding.
    \item \inlinecode{exiftool.exe:} Also in \texttt{Assets}, it is used to read and write metadata (EXIF, XMP), ensuring that the original file information is preserved.
    \item \textbf{AI Models:} The models in \texttt{.onnx} format are located in the \texttt{AI-onnx} folder.
    \item \textbf{User Preferences:} A file named \texttt{Warlock-Studio\_4.0\_UserPreference.json} is saved in the user's \textbf{Documents} folder.
    \item \textbf{Logs:} Log files are stored in \texttt{Documents\textbackslash Warlock-Studio\_4.0\_Logs}.
\end{itemize}


% --- Section 3: Model Guide ---
\section{Detailed Guide to AI Models}
The choice of AI model is the most important factor for quality and processing time.

\subsection{Model Comparison Table}
The following table details the relative VRAM usage of each model.
% 'longtable' with adjusted column widths to fit page margins
% Using tabularx for better column control and text wrapping
\begin{longtable}{p{2.8cm} p{1.8cm} p{1.2cm} p{1.5cm} p{7.2cm}}
\toprule
\textbf{Model} & \textbf{Function} & \textbf{Scale} & \textbf{VRAM (GB)} & \textbf{Recommended Use Case \& Details} \\
\midrule
\endhead % \endhead defines the header that will be repeated on each page.

\multicolumn{5}{c}{\textit{\textbf{Denoising Models}}} \\
\midrule
\texttt{IRCNN\_Mx1} & Denoise & x1 & 4.0 & Moderate noise reduction. Good for cleaning old photos with medium artifact levels. \\
\texttt{IRCNN\_Lx1} & Denoise & x1 & 4.0 & Intense noise reduction. Best for heavily degraded images with severe artifacts. \\
\midrule
\multicolumn{5}{c}{\textit{\textbf{High-Quality Upscaling Models (Slower Processing)}}} \\
\midrule
\texttt{BSRGANx4} & Upscale & x4 & 0.6 & Realistic photos with excellent fine detail preservation. Best for portraits and natural scenes. \\
\texttt{BSRGANx2} & Upscale & x2 & 0.7 & Similar quality to x4 variant but for moderate upscaling needs. Faster processing. \\
\texttt{RealESRGANx4} & Upscale & x4 & 0.6 & General purpose model. Excellent for textures and mixed content types. \\
\texttt{RealESRNetx4} & Upscale & x4 & 2.2 & Alternative to RealESRGAN. May offer better speed-quality balance on some systems. \\
\midrule
\multicolumn{5}{c}{\textit{\textbf{High-Speed Upscaling Models (Lightweight)}}} \\
\midrule
\texttt{RealESR\_Gx4} & Upscale & x4 & 2.2 & Fast processing ideal for videos. Good balance of speed and quality. \\
\texttt{RealESR\_Animex4} & Upscale & x4 & 2.2 & Specialized for anime, cartoons, and illustrated content. Preserves artistic style. \\
\midrule
\multicolumn{5}{c}{\textit{\textbf{Face Restoration Models}}} \\
\midrule
\texttt{GFPGAN} & Restore & x1 & 1.8 & AI-powered face enhancement and restoration. Repairs damaged faces in old photos. \\
\midrule
\multicolumn{5}{c}{\textit{\textbf{Frame Interpolation Models (Video Only)}}} \\
\midrule
\texttt{RIFE} & Interpolate & N/A & N/A & Maximum interpolation quality. Creates smooth motion between frames for high FPS. \\
\texttt{RIFE\_Lite} & Interpolate & N/A & N/A & Optimized version for GPUs with limited VRAM (< 4 GB). Faster processing. \\
\midrule
\multicolumn{5}{c}{\textit{\textbf{Super Resolution Models}}} \\
\midrule
\texttt{SuperResolution-10} & Upscale & x10 & 0.8 & Extreme upscaling for very low-resolution images. Perfect for restoring old, small photos. \\
\bottomrule
\caption{Comprehensive guide to AI model selection and VRAM requirements.}
\label{tab:modelos}
\end{longtable}


% --- Section 4: Optimization ---
\section{Configuration and Performance Optimization}

\subsection{Critical Performance Parameters}
\begin{itemize}[leftmargin=*]
    \item \textbf{Input Resolution \%:} The most effective adjustment for speed. It reduces the resolution before processing it with AI. A value between \textbf{50\% and 75\%} is usually ideal.
    \item \textbf{GPU VRAM Limiter (GB):} Define your GPU's VRAM. It is used to calculate the size of the processing \textit{tiles} and prevent memory errors.
    \item \textbf{AI Multithreading:} For videos only. It processes multiple frames in parallel, speeding up the process but consuming more VRAM and CPU.
    \item \textbf{AI Blending:} Blends the original image with the processed image. Useful for reducing artifacts when using a low \textit{Input Resolution}.
    \item \textbf{Frame Generation:} For RIFE models, allows creating interpolated frames for higher FPS or slow-motion effects.
\end{itemize}

\subsection{The User Preferences File}
The Warlock-Studio4.0 UserPreference.json file saves your settings.
% 'tabularx' is used for the table to automatically occupy 100% of the text width.
% The 'X' column is a flexible column that expands to fill the available space.
\begin{table}[H]
    \centering
    \small % Reduces the font size inside the table.
    \begin{tabularx}{\textwidth}{l X}
        \toprule
        \textbf{JSON Key} & \textbf{Description} \\
        \midrule
        \texttt{default\_AI\_model} & The last selected AI model. \\
        \texttt{default\_AI\_multithreading} & The number of processing threads for video. \\
        \texttt{default\_gpu} & The last selected GPU (Auto, GPU 1, etc.). \\
        \texttt{default\_keep\_frames} & Whether to keep the video frames ("ON" or "OFF"). \\
        \texttt{default\_image\_extension} & Default image extension (\texttt{.png}, \texttt{.jpg}, etc.). \\
        \texttt{default\_video\_extension} & Default video extension (\texttt{.mp4}, \texttt{.mkv}, etc.). \\
        \texttt{default\_video\_codec} & The default video encoder (x264, hevc\_nvenc, etc.). \\
        \texttt{default\_blending} & The selected blending level (Low, Medium, High). \\
        \texttt{default\_output\_path} & The last selected output path. \\
        \texttt{default\_input\_resize\_factor} & The input resolution percentage value. \\
        \texttt{default\_output\_resize\_factor} & The output resolution percentage value. \\
        \texttt{default\_VRAM\_limiter} & The GPU VRAM limiter value. \\
        \bottomrule
    \end{tabularx}
    \caption{Keys saved in the user preferences file.}
\end{table}

% --- Section 5: Troubleshooting ---
\section{Advanced Troubleshooting Guide}
\begin{warnbox}
The \textbf{Number 1} cause of errors is \textbf{special characters} in file paths and names. Avoid using: \texttt{', ", @, \#, \$, \%, \&, *, [, ], ?, etc.}.
\end{warnbox}

% 'description' is for definition lists.
% [style=nextline] places the text on the line following the term.
\begin{description}[leftmargin=*, style=nextline, itemsep=0.8em]
    \item[\faBan\ Error: "FFmpeg encoding failed: Invalid argument"]
        \textbf{Cause:} Invalid file name or path.
        \textbf{Solution:} Rename the file and/or its containing folder, removing any special characters.

    \item[\faMemory\ Error: "out of memory" or unexpected crash]
        \textbf{Cause:} The GPU ran out of video memory (VRAM).
        \textbf{Solution:}
        % 'enumerate' is for numbered lists. 'nosep' reduces space between items.
        \begin{enumerate}[nosep, leftmargin=*]
            \item Lower the \textbf{VRAM Limiter} to a value equal to or less than your GPU's actual VRAM.
            \item Lower the \textbf{Input Resolution \%} to 75\% or less.
            \item For videos, decrease the \textbf{AI Multithreading} threads or turn it "OFF".
            \item The application will try to recover from this error automatically.
        \end{enumerate}

    \item[\faTachometerAlt\ Error: "cannot convert float NaN to integer"]
        \textbf{Cause:} GPU driver timeout, often due to overload or overheating.
        \textbf{Solution:} Restart the process \textbf{without deleting the generated frames folder}. The application will read the existing frames and resume work from where it failed.

    \item[\faVolumeMute\ Issue: Output video has no audio]
        \textbf{Cause:} The original video had no audio track, a \textit{Slowmotion} mode was used, or the audio codec was incompatible.
        \textbf{Solution:} The program first tries to copy the audio stream directly. If that fails, it tries to re-encode to AAC. If all fails, it saves the video without audio. Using the \inlinecode{.mkv} container for the output may help.

    \item[\faQuestionCircle\ Issue: Application won't open or closes on startup]
        \textbf{Cause:} Corrupt settings, lack of permissions, or an environment error.
        \textbf{Solution:}
        \begin{enumerate}[nosep, leftmargin=*]
            \item Go to your \textbf{Documents} folder and delete the \inlinecode{Warlock-Studio_4.0_UserPreference.json} file.
            \item Check the log files in \texttt{Documents\textbackslash Warlock-Studio_4.0_Logs} for detailed error messages.
            \item Ensure your GPU drivers are up to date.
        \end{enumerate}

    \item[\faExclamationTriangle\ Issue: Frame interpolation not working]
        \textbf{Cause:} RIFE models are not selected or incompatible video format.
        \textbf{Solution:} Ensure you have selected a RIFE model (RIFE or RIFE\_Lite) and that the frame generation option is properly configured.
\end{description}

% --- Section 6: Architecture ---
\section{Advanced Architecture and Processes}

\subsection{Inference Engine and Hardware Acceleration}
Warlock-Studio uses \textbf{ONNX Runtime} with the \textbf{DirectML} provider (\inlinecode{DmlExecutionProvider}). This translates AI operations into \textbf{DirectX 12} calls, ensuring broad compatibility with NVIDIA, AMD, and Intel GPUs.

\subsection{Tiling System and Memory Management}
To handle high-resolution files, the application splits each frame into fragments (\textit{tiles}). The size of these tiles is dynamically calculated using the \textbf{VRAM Limiter}. Additionally, Python's garbage collector (\inlinecode{gc.collect()}) is invoked to force memory release and ensure stability.

\subsection{Resume and Checkpoint Functionality}
If a video process is interrupted, the processed frames are saved. When restarting the task, the \inlinecode{check\_video\_upscaling\_resume} function detects these files and resumes work from where it left off, saving time.

\subsection{Asynchronous Frame Writing}
During video upscaling, the frames processed by the GPU are sent to a separate writer thread. This allows the GPU to immediately start processing the next batch without waiting for the (slower) disk writing operation to finish, thus maximizing performance.

\subsection{Frame Interpolation Pipeline}
The RIFE models use a specialized interpolation pipeline that analyzes motion between frames to generate smooth intermediate frames. This enables higher frame rates or slow-motion effects with minimal artifacts.

\subsection{Logging System and Diagnostics}
Warlock-Studio implements a comprehensive logging system that includes:
\begin{itemize}[leftmargin=*]
    \item \textbf{Process Logs:} Record every stage of AI processing
    \item \textbf{Error Logs:} Capture detailed errors with stack traces
    \item \textbf{Performance Logs:} Measure processing times and resource usage
    \item \textbf{Debug Logs:} Detailed information for troubleshooting
\end{itemize}

\subsection{SuperResolution-10 Model Optimization}
The SuperResolution-10 model requires specific configurations:
\begin{itemize}[leftmargin=*]
    \item \textbf{CHW Preprocessing:} Conversion from image format (height, width, channels) to (channels, height, width)
    \item \textbf{Float32 Normalization:} Conversion to 32-bit floating point for maximum precision
    \item \textbf{Memory Management:} Use of contiguous arrays for memory access optimization
    \item \textbf{GPU Memory Allocation:} Dynamic VRAM allocation based on image size and available resources
\end{itemize}

\subsection{Performance Monitoring and Metrics}
The application provides detailed performance metrics:
\begin{description}[leftmargin=*, style=nextline]
    \item[Processing Speed:] Frames per second (FPS) and images per minute metrics
    \item[Memory Usage:] Real-time VRAM and system RAM monitoring
    \item[GPU Utilization:] DirectML provider performance statistics
    \item[Disk I/O:] Read/write speeds for temporary frame storage
\end{description}

\section{Advanced Error Resolution and System Diagnostics}

\subsection{GPU Memory Management and VRAM Optimization}
Warlock-Studio implements sophisticated GPU memory management:
\begin{description}[leftmargin=*, style=nextline]
    \item[Dynamic Tile Sizing:] Automatically calculates optimal tile sizes based on available VRAM
    \item[Memory Pool Management:] Pre-allocates and reuses memory buffers to reduce allocation overhead
    \item[Garbage Collection Integration:] Forces Python garbage collection at strategic points to free unused memory
    \item[VRAM Monitoring:] Real-time monitoring of GPU memory usage with automatic fallback to smaller tiles
\end{description}

\subsection{Model Loading and Initialization Troubleshooting}
\begin{warnbox}
Model loading failures are often caused by corrupted ONNX files, insufficient system permissions, or DirectML provider initialization errors.
\end{warnbox}
\begin{description}[leftmargin=*, style=nextline]
    \item[Model File Corruption:] Verify model file integrity by checking file sizes against expected values
    \item[Provider Initialization Failures:] Check DirectML compatibility and ensure DirectX 12 is properly installed
    \item[Permission Issues:] Run application as administrator if model loading fails consistently
\end{description}

\subsection{Video Processing Pipeline Diagnostics}
The video processing pipeline consists of several stages that can be individually diagnosed:
\begin{enumerate}[leftmargin=*]
    \item \textbf{Frame Extraction:} Verify FFmpeg can read the input video format
    \item \textbf{AI Processing:} Monitor VRAM usage and processing times per frame
    \item \textbf{Frame Assembly:} Check for missing or corrupted intermediate frames
    \item \textbf{Video Encoding:} Validate codec compatibility and hardware encoder availability
\end{enumerate}

\subsection{Performance Optimization Guidelines}
\begin{table}[H]
    \centering
    \small
    \begin{tabularx}{\textwidth}{l X}
        \toprule
        \textbf{Scenario} & \textbf{Recommended Settings} \\
        \midrule
        Low VRAM (< 4GB) & Input Resolution: 50\%, Multithreading: OFF, Use RIFE\_Lite \\
        Medium VRAM (4-8GB) & Input Resolution: 75\%, Multithreading: 2-4 threads, Standard models \\
        High VRAM (> 8GB) & Input Resolution: 100\%, Multithreading: 6-8 threads, High-quality models \\
        SSD Storage & Keep frames: ON for faster resume, Use higher multithreading \\
        HDD Storage & Keep frames: OFF to save space, Lower multithreading to reduce I/O \\
        \bottomrule
    \end{tabularx}
    \caption{Optimization settings based on system configuration.}
\end{table}

\subsection{Log File Analysis and Debugging}
Warlock-Studio generates comprehensive logs in the Documents folder:
\begin{description}[leftmargin=*, style=nextline]
    \item[warlock\_studio.log:] General application events, model loading, and processing status
    \item[error\_log.txt:] Detailed error messages with Python stack traces
    \item[performance\_log.txt:] Processing times, memory usage, and performance metrics
\end{description}

\subsection{Common Error Patterns and Solutions}
\begin{longtable}{p{4cm} p{5cm} p{6cm}}
\toprule
\textbf{Error Pattern} & \textbf{Typical Cause} & \textbf{Solution Strategy} \\
\midrule
\endhead
"DirectML device not found" & GPU drivers outdated or DirectX 12 not supported & Update GPU drivers, verify DirectX 12 compatibility \\
"ONNX Runtime initialization failed" & Corrupted model files or insufficient permissions & Re-download models, run as administrator \\
"FFmpeg process terminated" & Unsupported codec or corrupted input file & Convert input to supported format (MP4, H.264) \\
"Tile processing timeout" & GPU overheating or driver instability & Reduce tile size, check GPU temperature, update drivers \\
"Memory allocation failed" & System RAM exhausted & Close other applications, reduce multithreading \\
\bottomrule
\caption{Common error patterns and resolution strategies.}
\end{longtable}


% =======================================================================================
%   END OF DOCUMENT
% =======================================================================================
\end{document}
