Holy Snail Player: building, testing and how it is put together
===============================================================

This is for people who want to build Holy Snail Player from the source
download, check the published exe against it, or find their way around the
code. Bug reports, feature requests and questions: contact@holysnail.org


1. Requirements
---------------
- Windows 10 or 11, x64.
- Visual Studio 2022 or newer with the "Desktop development with C++"
  workload (the free Build Tools are enough), including a Windows 10/11 SDK.
- CMake 3.21 or newer. The copy bundled with Visual Studio works.

No other libraries are needed: miniaudio is included in third_party/miniaudio,
and everything else comes from Windows.


2. Build
--------
From the folder that holds CMakeLists.txt:

  cmake -S . -B build -A x64
  cmake --build build --config Release

CMake picks the newest installed Visual Studio, so no Developer Command Prompt
is needed. The program is build\Release\HolySnailPlayer.exe. Release builds
compile without warnings at /W4.

The C++ runtime is linked statically, so the exe runs on a clean Windows
install without extra downloads.


3. Checking the published exe
-----------------------------
Release builds are reproducible: they record no build time and no folder
names, so the same source built with the same tools gives the same exe, byte
for byte, in any folder. The published exe was built with:

  - Visual Studio 2026 Build Tools, MSVC compiler 19.51.36260.0
  - Windows SDK 10.0.26100.0
  - CMake 4.3.1 (the copy bundled with Visual Studio), x64

With those versions installed, build as above and compare checksums:

  certutil -hashfile build\Release\HolySnailPlayer.exe SHA256

The result should match the checksum published next to the exe (see
CHECKING-DOWNLOADS.txt). With other versions the build works the same but its
bytes differ.


4. Test
-------
  build\Release\Player_tests.exe            all tests
  build\Release\Player_tests.exe playlist   only tests whose name contains
                                            "playlist"

The unit tests cover the playlist and play order, tag, MP4, ASF and ADTS
parsing, the settings file, the audio engine, the stream reader, radio and
podcast parsing, audio CD reading (from byte arrays) and the Audiobook mode
log. They create their own test files in the temp folder.

Some tests need material that isn't included and are skipped unless an
environment variable points at it:

  HSPLAYER_TEST_MP3
      Seek timing on a long MP3 of your choice.
  HSPLAYER_SCAN_DIR
      Folder scan timing on a large folder.
  HSPLAYER_GAPLESS_WHOLE, HSPLAYER_GAPLESS_PARTS
      Gapless check: a whole MP3 and the same audio cut into parts
      (part1|part2|part3) must play identically.
  HSPLAYER_AAC_DIR
      Media Foundation decoding, seeking and chapters on M4A/M4B files (the
      file names are listed in tests/test_mp4.cpp).
  HSPLAYER_MF_DIR
      ALAC, WMA and ADTS decoding, seeking and lossless checks through
      Media Foundation on generated files (the file names are listed in
      tests/test_formats.cpp).
  HSPLAYER_AAC_SERVER
      AAC stations and remote WMA/ALAC files against a local HTTP server
      that serves the HSPLAYER_MF_DIR files (see tests/test_formats.cpp).
  HSPLAYER_TEST_SERVER, HSPLAYER_PODCAST_DIR
      Range requests, feeds and remote episodes against a local HTTP server
      that serves the files in HSPLAYER_PODCAST_DIR (see
      tests/test_podcast.cpp).
  HSPLAYER_CD_DRIVE
      Reads the TOC, CD-Text and audio of an audio CD in that drive letter.


5. Command line
---------------
  HolySnailPlayer.exe [folder or audio file ...]

A folder plays from the top; a file plays its folder from that file (in
Audiobook mode, the file alone becomes the book). If the player is already
running, the paths go to that window.

Two options exist for testing: --measure-startup prints the time to the first
paint and exits, and --force-streaming streams every file instead of reading
it into memory.


6. Overview
-----------
C++20 and raw Win32 (wide-character APIs, standard common controls), no UI
framework. Audio output and decoding of MP3, WAV and FLAC use miniaudio's
low-level API (ma_decoder, ma_device on WASAPI). AAC and ALAC (M4A, M4B),
WMA and AAC radio streams are decoded by Windows Media Foundation, podcast
feeds are parsed with XmlLite, HTTP goes through WinHTTP, and the media keys
and flyout use the System Media Transport Controls (C++/WinRT, only in
src/smtc.cpp). WinHTTP, Media Foundation, XmlLite, dwmapi and the WinRT
imports are delay-loaded, so they cost nothing at startup.


7. Source map
-------------
  main.cpp       Entry point, single instance, command line
  ui.cpp         Main window, controls, layout, DPI, mini mode, the list
                 button, context menu, the list's scroll bar
  theme.cpp      Colors and owner-drawn buttons, sliders and list rows; high
                 contrast support
  app.cpp        App state: the playlist, the music and book lists,
                 transport, session restore; handles the workers' messages
  audio.cpp      Playback device, audio callback, the lock-free track
                 handoff, resampling
  loader.cpp     Worker that turns a path into a playable Track
  stream.cpp     Reader thread per streamed track (large files, M4A, WMA,
                 podcast episodes, CD tracks) feeding a PCM ring
  scanner.cpp    Folder walk and background tag reading for list titles
  playlist.cpp   Track list, natural sort, play order, shuffle bag, history
                 (pure C++, unit-tested)
  tags.cpp       ID3v1/v2, WAV and FLAC tags, ID3 chapters
  mp4.cpp        MP4 tags and chapters
  asf.cpp        WMA (ASF) tags and protection check
  mf.cpp         Media Foundation decoders: M4A, M4B and WMA files, AAC
                 station frames
  radio.cpp      Internet radio: stream reading, ICY metadata, decoding into
                 a time-shift ring
  adts.cpp       ADTS framing of AAC stations
  http.cpp       Bounded HTTP GET and Range reads
  podcast.cpp    RSS parsing and station links
  cd.cpp         Audio CD table of contents, CD-Text and raw sector reads
  booklog.cpp    Audiobook mode's listening log
  settings.cpp   The settings INI


8. Threads
----------
  UI
      Owns the window, controls, playlist, app state and copies of track
      metadata.
  Audio (miniaudio's WASAPI thread)
      Owns the playing Track and its decoder. Talks to the UI through
      atomics only.
  Loader
      Builds Track objects (reads the file, opens the decoder, reads tags).
      Talks to the UI through PostMessage with a heap payload.
  Scanner
      Folder walk, then tag titles for the list. PostMessage with a heap
      payload.
  Stream reader (one per streamed track)
      Owns the track's byte source and decoder; writes PCM into a
      single-producer, single-consumer ring. Ring and atomics to audio;
      PostMessage for errors.
  Radio
      Owns the station's HTTP connection, metadata parsing and decoder;
      writes PCM into a ring. Ring and atomics to audio; PostMessage for
      titles and errors.
  Podcast, disc lister
      One feed fetch or one CD table of contents at a time. PostMessage with
      a heap payload.

Rules every thread follows:

- The audio thread never allocates, frees, locks, logs, calls Win32 or
  throws. It only reads the current track (from memory, or from a ring
  filled by a reader thread) and the atomics.
- Track ownership: every handoff of a Track pointer is an atomic exchange,
  and whoever receives the pointer owns it. The UI thread never touches a
  Track after handing it to the audio thread; it keeps its own copy of the
  metadata it shows.
- Worker threads never touch windows. They post a message whose heap payload
  the UI thread frees.
- Paths are wide strings throughout and are never handed to miniaudio: the
  program reads files itself and decodes from memory or through its own read
  callbacks.
- Parsing: every length or offset read from a file or the network is checked
  against the data actually there before use.


9. Gapless playback and the track handoff
-----------------------------------------
The audio engine holds three slots: next (the preloaded following track),
switchTo (play this now: a jump, a seek elsewhere, a new folder) and a small
ring of retired tracks. In each audio callback it applies switchTo and any
pending seek, then reads frames from the current track. When the track ends
mid-buffer it takes next, retires the old track and keeps filling the same
buffer, which is the whole gapless mechanism. Repeat One seeks the current
track back to its start instead. One linear resampler converts to the device
rate and keeps running across track changes, so joins stay sample-exact even
when resampled.

The engine publishes the current track id, the play position and a counter
of track changes through atomics. A 200 ms UI timer, running only while
playing, reads them, updates the seek bar, frees retired tracks and asks the
loader for the next preload after each change.


10. Memory and idle cost
------------------------
Files up to 64 MB are read whole into memory and decoded from there. Larger
files, M4A and WMA files, podcast episodes and CD tracks stream through a
reader thread and a 10-second PCM ring. Radio buffers up to 20 minutes for
time-shift and releases memory as it plays.

When paused or stopped, the UI timer is killed and the audio device is
stopped, so a paused player uses no CPU. The exceptions are radio's
time-shift (the stream keeps downloading while paused) and a full stream
ring, which is checked twice a second.


11. Settings and state
----------------------
settings.ini in %LOCALAPPDATA%\HolySnailPlayer (UTF-16 so non-ASCII paths
survive) holds the window, the modes (mini mode, the list shown or hidden),
the music list's folder, track and position, the book's path, track and
position, stations, podcasts, resume positions and heard episodes. Audiobook
mode adds listening.log next to it: one line per play, pause, jump and
30-second checkpoint, used to recover the place after a crash and for
"Back to".
