===============================================================================
                    ZAP AUDIO CODEC v1.0.0
                   TECHNICAL DOCUMENTATION
===============================================================================

OVERVIEW
--------
ZAP (Zero Audible Psychoacoustic) is a high-fidelity audio codec designed 
for studio reference quality compression. It employs advanced psychoacoustic 
principles, transparent dynamics processing, and intelligent stereo encoding 
to achieve exceptional audio quality at bitrates below 280 kbps.

===============================================================================
CORE FEATURES
===============================================================================

PERCEPTUAL AUDIO ENCODING
--------------------------
- DCT-IV Transform: Discrete Cosine Transform Type IV with 2048-sample 
  blocks and 50% overlap for optimal frequency resolution
- Psychoacoustic Masking: Frequency-dependent weighting based on human 
  hearing sensitivity
- Spectral Scrubbing: Intelligent removal of inaudible components below 
  10 Hz and above 22 kHz
- Non-linear Quantization: Power law compression (exponent 0.85) for 
  optimal signal preservation

SMART STEREO PROCESSING
------------------------
- Adaptive Mid/Side Encoding: Automatically enabled only when beneficial 
  for compression and phase coherence
- Dual Weighting System: Separate spectral weights for mid and side 
  channels (side channel: 95% weight)
- Energy Analysis: Real-time evaluation of stereo field to determine 
  optimal encoding strategy

TRANSPARENT AUDIO ENHANCEMENT
------------------------------
- Transient Shaper: Subtle dynamics enhancement (max 0.5% gain) for 
  improved punch without audible artifacts
- Pre-emphasis Filtering: Coefficient 0.28 for high-frequency clarity 
  preservation
- DC Blocker: IIR minimum-phase filter (coefficient 0.9995) to eliminate 
  low-frequency drift

HIGH-PRECISION PROCESSING
--------------------------
- 64-bit Internal Processing: Ensures archival stability and numerical 
  accuracy
- Multi-core Parallelization: Rayon-based parallel processing for optimal 
  performance
- Deterministic Output: Consistent results across different systems and runs

===============================================================================
TECHNICAL SPECIFICATIONS
===============================================================================

SIGNAL PROCESSING PARAMETERS
-----------------------------
Parameter                  | Value          | Purpose
---------------------------|----------------|--------------------------------
Block Size                 | 2048 samples   | Frequency resolution
Hop Size                   | 1024 samples   | 50% overlap for reconstruction
Window Function            | Sine window    | Time-frequency localization
Power Law Exponent         | 0.85           | Non-linear quantization curve
Pre-emphasis Coefficient   | 0.28           | High-frequency preservation
DC Blocker Coefficient     | 0.9995         | Low-frequency drift removal
Target Bitrate             | < 280 kbps     | Studio-grade quality threshold

COMPRESSION PIPELINE
--------------------
1. Input Validation: Enforces lossless sources (WAV, FLAC, AIFF) - 
   rejects lossy formats
2. Pre-processing:
   - Padding with reflection for boundary handling
   - Pre-emphasis filtering
   - Transient shaping
3. Stereo Analysis: Determines optimal Mid/Side encoding
4. Transform:
   - DCT-IV with sine windowing
   - Spectral scrubbing
   - Frequency-dependent weighting
5. Quantization:
   - Non-linear power law compression
   - Adaptive scaling for target bitrate
   - Delta encoding with temporal prediction
6. Entropy Coding: Zstandard compression (Ultra level 21)

DECOMPRESSION PIPELINE
-----------------------
1. Decompression: Zstandard decompression
2. Delta Decoding: Reconstruction with temporal prediction
3. Inverse Quantization: Power law expansion
4. Inverse Transform: DCT-IV with overlap-add synthesis
5. Post-processing:
   - Mid/Side to Left/Right conversion (if applicable)
   - Pre-emphasis removal
   - DC blocking
   - Hard limiting to ±1.0

===============================================================================
USAGE
===============================================================================

COMMAND LINE INTERFACE
-----------------------

ENCODING:
    zap_codec encode input.wav [OPTIONS]

OPTIONS:
    --title "Song Title"     Set track title
    --artist "Artist Name"   Set artist name
    --album "Album Name"     Set album name
    --year "2025"            Set release year
    --genre "Genre"          Set music genre
    --track 1                Set track number
    --comment "Comment"      Add comment

PLAYBACK:
    zap_codec play file.zap

DECODING:
    zap_codec decode file.zap [output.wav]

EXAMPLE WORKFLOWS
-----------------

Basic Encoding:
    zap_codec encode studio_recording.flac

Encoding with Metadata:
    zap_codec encode track.wav --title "Midnight Jazz" 
              --artist "The Quartet" --album "Live Sessions" --year "2025"

Decode to Custom Location:
    zap_codec decode compressed.zap restored_audio.wav

===============================================================================
METADATA SUPPORT
===============================================================================

ZAP preserves and embeds the following metadata:
- Title
- Artist
- Album
- Year
- Genre
- Track Number
- Comment
- Album Art Presence Flag

Metadata is automatically extracted from input files and can be overridden 
via command-line parameters.

===============================================================================
PERFORMANCE CHARACTERISTICS
===============================================================================

COMPRESSION EFFICIENCY
----------------------
- Target Bitrate: < 280 kbps (adaptive)
- Typical Compression Ratio: 70-85% reduction vs 16-bit PCM
- Fidelity Score: 93-99% (transparent quality)

PROCESSING SPEED
----------------
- Encoding: Multi-core parallelized analysis and quantization
- Decoding: Real-time capable on modern hardware
- Playback: Automatic sample rate conversion with linear interpolation

MEMORY FOOTPRINT
----------------
- Efficient Buffering: 1MB read buffers for optimal I/O
- Streaming Friendly: Minimal memory overhead during playback
- Scalable: Performance scales with available CPU cores

===============================================================================
FILE FORMAT SPECIFICATION
===============================================================================

BINARY STRUCTURE
----------------
[4 bytes]    Magic Number: 0x5A 0x41 0x50 0x31 (ZAP1)
[Variable]   Version String
[Variable]   Compressed Data Blob
[2 bytes]    Channel Count
[4 bytes]    Sample Rate
[16 bytes]   Spectrum Shape (rows, cols)
[4 bytes]    Quantization Scale
[Variable]   Metadata Structure
[4 bytes]    Fidelity Score
[8 bytes]    Frame Count
[8 bytes]    N Size
[8 bytes]    Hop Size
[Variable]   Mid Channel Weights
[Variable]   Side Channel Weights
[4 bytes]    Pre-emphasis Coefficient
[1 byte]     Mid/Side Flag
[8 bytes]    Original Sample Count

All multi-byte values use little-endian byte order.

===============================================================================
QUALITY ASSURANCE
===============================================================================

INPUT VALIDATION
----------------
- Format Enforcement: Only accepts lossless sources (WAV, FLAC, AIFF)
- Lossy Source Detection: Automatically rejects MP3, OGG, AAC, M4A, WMA, 
  Opus
- Error Reporting: Clear feedback on unsupported formats

SIGNAL INTEGRITY
----------------
- Boundary Handling: Reflection padding prevents edge artifacts
- Overflow Protection: Hard limiting prevents clipping
- Numerical Stability: 64-bit processing eliminates accumulation errors

PERCEPTUAL OPTIMIZATION
-----------------------
- Frequency Weighting: Enhanced preservation of critical 2-5 kHz range
- Stereo Imaging: Preserves spatial information when beneficial
- Transient Response: Maintains attack characteristics

===============================================================================
SYSTEM REQUIREMENTS
===============================================================================

BUILD DEPENDENCIES
------------------
- Rust 1.70 or newer
- Cargo package manager

RUNTIME DEPENDENCIES
--------------------
- Operating System: Windows, macOS, Linux
- Audio Output: Any CPAL-compatible audio device

RECOMMENDED HARDWARE
--------------------
- Multi-core CPU (4+ cores recommended for optimal encoding speed)
- 2GB RAM minimum
- Audio interface with 44.1 kHz or higher sample rate support

===============================================================================
ADVANCED CONFIGURATION
===============================================================================

MODIFYING CODEC PARAMETERS
---------------------------
The following constants in the source code can be adjusted for experimental 
purposes:

    const BLOCK_SIZE: usize = 2048;           // Transform block size
    const POWER_LAW_EXPONENT: f32 = 0.85;     // Quantization curve
    const LINEAR_DEADZONE: f32 = 0.00002;     // Noise floor threshold
    const MAX_ALLOWED_KBPS: u32 = 280;        // Target bitrate ceiling

WARNING: Modifying these values may affect compatibility and quality.

===============================================================================
TROUBLESHOOTING
===============================================================================

COMMON ISSUES
-------------

Problem: "Lossy format detected" error
Solution: Convert input to WAV or FLAC using a lossless converter

Problem: Playback stuttering
Solution: Ensure sufficient CPU resources; close background applications

Problem: Metadata not preserved
Solution: Verify input file contains embedded tags; use manual metadata flags

Problem: Output too large
Solution: Check input file quality; ZAP is optimized for studio recordings

===============================================================================
LICENSING & CREDITS
===============================================================================

Copyright: © 2025 Christian Schwarzer

License: Open-source (specific license TBD)

Attribution: Please credit this work for any modifications or derivative 
releases.

Contact: c-schwarzer@web.de

===============================================================================
VERSION HISTORY
===============================================================================

v1.0.0 (2025)
-------------
- Initial public release
- DCT-IV transform engine
- Smart Mid/Side stereo
- Transparent transient shaping
- Adaptive bitrate optimization
- Zstandard ultra compression
- Full metadata support
- Real-time playback capability

===============================================================================
FUTURE DEVELOPMENT
===============================================================================

Planned enhancements for future versions:
- Multi-channel support (5.1, 7.1 surround)
- Variable bit-depth output
- GPU acceleration for encoding
- Streaming mode for real-time applications
- Extended metadata schema
- Batch processing tools
- Integration with DAW software

===============================================================================

For additional information, bug reports, or feature requests, please contact 
the development team or visit the project repository.

===============================================================================
                         END OF DOCUMENTATION
===============================================================================