% =======================================================================================
%   WARLOCK-STUDIO 2.2 - USER MANUAL & TECHNICAL DOCUMENTATION
% =======================================================================================
% Manual Version: 5.0 (Final Documented 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 2.2 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, shadows} % Additional libraries are loaded for more styles.
                                          % 'breakable' allows boxes to split across pages.
                                          % 'shadows' adds shadow effects.

% 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}      % Adds a subtle shadow.
}

% 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}
}

% 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 2.2}}
\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 2.2\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.
This document is a comprehensive technical guide for Warlock-Studio 2.2. The information has been validated and enriched with a deep analysis of the source code to provide precise details about its architecture, an advanced optimization guide, and a robust troubleshooting manual.
\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 2.2 introduces key improvements in stability, performance, and user experience, establishing it as a robust tool for content creators and enthusiasts.

\subsection{What's New in Version 2.2}
The code analysis reveals the following substantial improvements:
% 'itemize' is used for bulleted lists. [leftmargin=*] aligns the list with the paragraph margin.
\begin{itemize}[leftmargin=*]
    \item \textbf{Thread Management and Safe Closures:} Concurrency management has been improved using \texttt{Lock} and \texttt{RLock} to ensure the process state is updated safely and to prevent race conditions when processing videos. The process termination (\texttt{terminate}) is now more robust.
    \item \textbf{Proactive Memory Optimization:} During long video processing, the application now explicitly calls Python's garbage collector (\texttt{gc.collect()}) after processing batches of frames, significantly reducing the likelihood of out-of-memory errors.
    \item \textbf{GPU Error Handling:} A specific handler for GPU memory errors during video upscaling has been added. If an "out of memory" error is detected, the application automatically reduces the \textit{tile} size and retries the process.
    \item \textbf{Splash Screen:} A 10-second splash screen has been added, improving the perception of the application's initial load time.
    \item \textbf{Logging and Diagnostics:} The application creates log files (\texttt{warlock\_studio.log} and \texttt{error\_log.txt}) in the user's \textbf{Documents} folder, making it easier to diagnose problems.
\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{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).
\end{itemize}


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

\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 2.2.}
\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 \inlinecode{Warlock-Studio_2.2_UserPreference.json} is saved in the user's \textbf{Documents} folder.
    \item \textbf{Logs:} Log files are stored in \texttt{Documents\textbackslash Warlock-Studio_2.2_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' is for tables that can span multiple pages. The column definition is similar to 'tabular'.
% 'p{<width>}' is used for the last column, creating a fixed-width paragraph with automatic line wrapping.
\begin{longtable}{l l c c p{6.5cm}}
\toprule
\textbf{Model} & \textbf{Main Function} & \textbf{Scale} & \textbf{VRAM Weight} & \textbf{Recommended Use Case} \\
\midrule
\endhead % \endhead defines the header that will be repeated on each page.

\multicolumn{5}{c}{\textit{Denoising Models}} \\
\midrule
\texttt{IRCNN\_Mx1} & Denoise & x1 & 4.0 & Moderate noise. \\
\texttt{IRCNN\_Lx1} & Denoise & x1 & 4.0 & Intense noise. \\
\midrule
\multicolumn{5}{c}{\textit{High-Quality Upscaling Models (Slow)}} \\
\midrule
\texttt{BSRGANx4} & Upscale & x4 & 0.6 & Realistic photos. Excellent fine detail. \\
\texttt{BSRGANx2} & Upscale & x2 & 0.7 & Similar to x4 but for a smaller upscale. \\
\texttt{RealESRGANx4} & Upscale & x4 & 0.6 & General purpose, good for textures. \\
\texttt{RealESRNetx4} & Upscale & x4 & 2.2 & Alternative to RealESRGAN, can be faster. \\
\midrule
\multicolumn{5}{c}{\textit{High-Speed Upscaling Models (Lightweight)}} \\
\midrule
\texttt{RealESR\_Gx4} & Upscale & x4 & 2.2 & Fast upscaling, ideal for videos. \\
\texttt{RealESR\_Animex4} & Upscale & x4 & 2.2 & Optimized for anime and cartoons. \\
\midrule
\multicolumn{5}{c}{\textit{Frame Interpolation Models (Video Only)}} \\
\midrule
\texttt{RIFE} & Interpolate & N/A & N/A & Maximum interpolation quality. \\
\texttt{RIFE\_Lite} & Interpolate & N/A & N/A & Faster version, ideal for GPUs with < 4 GB VRAM. \\
\bottomrule
\caption{Guide to AI model selection and their impact on VRAM.}
\label{tab:modelos} % \label to be able to reference the table with \ref{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}.
\end{itemize}

\subsection{The User Preferences File}
The \inlinecode{Warlock-Studio_2.2_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_2.2_UserPreference.json} file.
            \item Check the log files in \texttt{Documents\textbackslash Warlock-Studio_2.2_Logs} for detailed error messages.
            \item Ensure your GPU drivers are up to date.
        \end{enumerate}
\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.


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