Leaving Fetch TV?Read the guideRead the guideSkip to content

Technical deep dive ​

Reference for the Freetvarr implementation: the modules, the data they keep, the calls they make, and the constants they use. The user-facing companion is the guide; the project summary is README.md.

Contents ​

Overview ​

Freetvarr is one Node.js process. It runs an Express server that serves a REST API under /api and a static Vue 3 single-page app. The process reads the TVHeadend API, the TVHeadend recordings folder, Plex, optional Sonarr and Radarr, and third-party lookup services. It writes files into the media library folders, rows into a SQLite database, and DVR entries and rules into TVHeadend.

Architecture ​

The first diagram shows the modules inside the process and what starts them.

The second diagram shows the external systems and the data paths between them.

Module map ​

ModulesJobTalks to
src/server.jsBuilds the Express app: security middleware, /api routes, /healthz, the guide feed at /guide/xmltv.xml, the static SPA, the startup sequenceEvery module below
src/scheduler.js, src/schedule-runs.jsRuns one node-cron task from the setting sync_cron; each tick starts a sync, a guide refresh, viewing-history upkeep, and For you upkeepsrc/sync.js, src/epg.js, src/user-events-log.js, src/for-you-service.js
src/sync.jsLists finished TVHeadend recordings, matches them to show rules, imports them, refreshes Plex, removes imported recordings from TVHeadendsrc/tvheadend.js, src/plex.js, src/commercials.js, src/show-folders.js, src/db.js
src/show-folders.js, src/show-identity*.js, src/database-ids.jsName a new show folder; find the TVmaze, TVDB, and TMDB ids of a showTVmaze, TMDB, shows, show_identity_picks
src/auto-import.js, src/recording-now.jsPoll the running recordings, then start a sync after a recording endssrc/tvheadend.js, src/sync.js
src/tvheadend.js, src/http-auth.jsHTTP client for the TVHeadend API with Digest or Basic authTVHeadend
src/tvheadend-bootstrap.js, src/tvheadend-setup.js, src/tvheadend-guide.js, src/tv-login.jsWizard steps: lock an open TVHeadend, set up tuners and channels, set up the guide, create a watch-only TV app loginTVHeadend access/*, passwd/*, mpegts/*, epggrab/*
src/guide-feed.js, src/guide-merge.js, src/guide-sources/, src/title-aliases.js, src/guide-source-health.js, src/guide-listings.js, src/guide-source-routes.jsBuild the merged XMLTV guide file from ranked guide sources, score each source, and serve it (or the source feed) with time-shifted copies of programmesFreeview API, mjh XMLTV feeds
src/epg.js, src/guide-cache.js, src/guide-history.js, src/guide-search.jsCache the TVHeadend guide and recording state; save airings; search the guidesrc/tvheadend.js, src/db.js
src/pending-skips.js, src/watchlist.js, src/repeat-match.js, src/autorec-match.js, src/title-countries.jsSingle-episode skips, watchlist titles, matching of airings to rules and repeats, and the country words of series rule titlessrc/epg.js, src/tvheadend.js
src/live-tv.js, src/live-encoder.js, src/live-streams.js, src/live-benchmark.js, src/live-measure-schedule.js, src/tuner-status.jsPipe a TVHeadend channel stream through FFmpeg into HLS files; pick the encoder; set the stream limit; read tuner useTVHeadend, ffmpeg
src/playback.js, src/in-progress-playback.js, src/in-progress-positions.jsPlay library files and running recordings as HLS sessionsffmpeg, ffprobe, media library, TVHeadend /dvrfile
src/commercials.js, src/ad-original-routes.jsDetect and cut ad breaks with Comskip and ffmpegcomskip, ffmpeg, ffprobe, media library
src/plex*.js, src/external-ids*.jsPlex discovery and section refresh; watched-state sync; whole-library listingPlex, plex_watch_state, library_items, external_ids
src/arr-*.js, src/foreign-delete.js, src/delete-manager-check.jsOptional Sonarr and Radarr client for file lists, unmonitor, and deleteSonarr, Radarr
src/for-you*.js, src/top-rated.js, src/user-events*.js, src/watch-tracker.jsRecord viewing events; score the guide against them; run the heavy work in a child processuser_events, text_embeddings, Hugging Face models, optional Ollama
src/home-hero-service.js, src/hero-picture-proof.js, src/art-pool.jsBuild the Home hero snapshotsrc/epg.js, src/for-you-service.js, settings
src/art-resolver.js, src/airing-memory.js, src/art-feed.js, src/art-warmer.js, src/art-warm-plan.js, src/visit-pattern.js, src/background-work.js, src/artwork*.js, src/show-artwork.js, src/fallback-artwork.js, src/programme-images.js, src/guide-pictures.js, src/picture-gate.js, src/picture-placeholders.js, src/picture-marks.js, src/freeview-au.js, src/image-thumbnails.js, src/image-focus*.jsFind, store, resize, crop, and warm picturesFreeview, TVmaze, TMDB, Wikidata, Wikipedia, Plex, config folder
src/programme-ratings.js, src/programme-credits.js, src/wikidata-film-credits.js, src/classification-labels.js, src/genre-enrichment.js, src/series-ratings.js, src/known-as.jsLook up ratings, cast, classifications, genres, series scores, and alternative titlessrc/outbound-http.js, lookup tables
src/outbound-http.js, src/lookup-gate.js, src/cache-prune.jsShared client for third-party requests; hourly lookup limit; daily deletion of expired lookup rowsThird-party hosts, lookup tables
src/library*.js, src/show-folder-rename.jsLibrary listing, watched marks, folder moves, deletes, and folder renamesrecordings, shows, media library
src/doctor.js, src/health-summary.js, src/path-check.js, src/docker-host.jsHealth checks and the health level in the navigationTVHeadend, Plex, media library
src/host-gate.jsThe Host check, the allowed hostnames, and the names seensettings
src/activity*.js, src/progress.js, src/event-loop-lag.jsJob registry, live progress, job-run storage, and event-loop monitoringjob_runs
src/web/, src/web-assets.js, src/build-id.jsVue 3 client files, asset caching, and the build idBrowser
src/db.js, knexfile.js, migrations/Knex connection, settings helpers, and schemastate.db

Startup order ​

docker-entrypoint.sh checks the config folder (Image), runs node node_modules/.bin/knex migrate:latest, then exec node src/server.js. src/server.js runs these steps in order.

The module load step registers the routes between resolveCsrfSecret and webAssets. liveEncoderReady and liveStreams.load run without a wait; the live routes await liveEncoderReady when a session starts.

Boot timers ​

TimerStarted byFirst runRepeatEffect
Cron tickstartSchedulerNext match of sync_cronCron (default */30 * * * *)Sync, guide refresh, viewing-history upkeep, For you upkeep
Recording pollwatchForFinishedRecordings60 s60 sDetects a finished recording (Auto-import)
ReapersModule load5 s5 sEnd idle or stalled live and playback sessions
Doctor checksscheduleDoctorChecks2 min3 hRefresh the health report
Ratings warm-upModule load2 min1 hLook up ratings for upcoming programmes
Cache prunestartCachePruning10 min24 hDelete expired lookup rows
Home hero buildhomeHero.start20 s5 minRebuild the hero snapshot
Library folder sortListen callback3 minNonerunReclassificationOnce (Folder moves)
Guide mergeguideMerge.start3 min6 hBuild guide/merged.xml.gz (Merged guide)
Guide warm-upkeepGuideWarmImmediate5 s after each local midnightReload the guide and recording state
Pending skipswatchPendingSkipsAfter each guide load5 minReload the recording state while a skip or a repeat waits
Watchlist sweepmountWatchlistNone15 minCreate a series rule for a title in mode record
Artwork nightlystartWarmScheduleNext 03:30 local24 hWarm every picture tier (Picture warm-up)
Visit windowstartWarmSchedule45 min before a likely visitChecked every 1 hWarm the top and next picture tiers

Storage ​

Freetvarr stores state in SQLite through Knex and better-sqlite3. knexfile.js sets useNullAsDefault: true and runs two pragmas on each new connection: journal_mode = WAL (WAL mode) and synchronous = NORMAL.

DB_PATH sets the database file; the default is config/state.db in the repository root. The config folder is the directory of DB_PATH. src/db.js exports the Knex instance, getSetting(key) (the value, or null), setSetting(key, value) (upsert), and deleteInChunks (deletes by rowid in chunks of 200 and yields between chunks).

Tables ​

TableMigrationsHoldsMain writer
settings0001Key and text value of every settingsrc/db.js
shows0001, 0037, 0038, 0039Series folders: show_pattern, dest_folder, season_template, enabled, delete_after_import, ad_removal; identity ids and identity_state; kept_folder; origin (user or auto)src/show-folders.js, src/server.js
recordings0001 and later, 0040, 0042One row per TVHeadend recording: status, paths, sizes, ad status and backups, episode details, playback position, watched time, library state, classification, genres_json, show_title_override, log_cleared_at (hidden from the Recordings log, still in the library), tvh_remove_pending_at (a Remove after import to try again)src/sync.js
syncs0001One row per sync: start, finish, status, summary_jsonsrc/sync.js
guide_programs0002Saved guide airings keyed by channel_id and start, with program_jsonsrc/guide-history.js
show_artwork0005Cached picture sources per title_keysrc/show-artwork.js
watchlist0008, 0014Titles to notify or record, with optional channel and paddingsrc/watchlist.js
user_events0010Viewing-history eventssrc/user-events-log.js
text_embeddings0011Embedding vectors per text_hash and model_idsrc/for-you-engine.js
title_genres0011Cached genres per title_keysrc/genre-enrichment.js
show_nicknames0012User-added search names per show_keysrc/search-aliases.js
title_known_as0012Cached alternative titles per title_keysrc/known-as.js
artwork_lookups0013Cached Wikipedia and TMDB picture lookupssrc/fallback-artwork.js
programme_ratings0015, 0020Cached rating lookups, with miss_reason; TVmaze series scores under keys that start with tvmaze:series:src/programme-ratings.js
programme_classifications0016, 0041Classification label per title_key, start_ms, and shift_hourssrc/classification-labels.js
programme_credits0017, 0020Cached cast and crew lookups, with miss_reasonsrc/programme-credits.js
programme_categories0019, 0041XMLTV category per title_key, start_ms, and shift_hourssrc/classification-labels.js
art_pools0021Cached picture pools per pool_keysrc/art-pool.js
show_artwork_choices0022The chosen picture per show_key and kindsrc/artwork-choices.js
image_focus0024, 0027Focus point and face box per picture URLsrc/image-focus-service.js
pending_skips0025, 0031Skipped single airings by program_idsrc/pending-skips.js
programme_kind_overrides0028, 0029User-set kind per show_keysrc/programme-kind.js
job_runs0032Finished job runs as run_jsonsrc/activity-store.js
series_evidence0033, 0039Series facts per show_key; database_ids and database_ids_atsrc/series-evidence.js
plex_watch_state0034Watched snapshot of both sides per recording_idsrc/plex-watch.js
library_items0035Plex library items keyed by rating_key and part_idsrc/plex-library-store.js
external_ids0036TVDB, TMDB, and IMDb ids per title_key, kind, and sourcesrc/external-ids-store.js
show_identity_picks0037The picked or declined identity per title_key and network_familysrc/show-identity-store.js
art_resolutions0044, 0045The resolved picture per title key, kind, and shape: stage, origin, transform, evidence fingerprint, miss_step, next_check_at, the picture stamp, and the client show_key. Marked due, never deleted, to ask againsrc/art-resolver.js
title_kinds0053One kind per show_key (movie, series, or one-off), the source that decided it (override, library, guide, or hint), the evidence_json, and decided_at. See Title kindssrc/title-kinds.js
programme_picture_stamps0050One stamp per show_key for guide airing and recording picture URLs, and changed_at. See Live picture updatessrc/programme-stamps.js
title_aliases0047Per guide source and source title: the title written instead (kind alias), or a source title that the other source never lists (kind variant-candidate); first_seen_at, last_seen_at
guide_source_windows0055One row per Freeview guide source, triplet, and 12 h window start: the parsed programmes (programmes_json), format (WINDOW_FORMAT), fetched_at, and expires_at. Rows of windows that ended are deleted at the next buildsrc/guide-sources/window-store.js
guide_source_health0048One row per merged guide build, guide source, and channel (channel '' for the whole source): covered_hours, horizon_hours, described_share, agreement, fetch_attempts, fetch_failures, below, degraded, led, built_at (Source health)src/guide-source-health.js
picture_checks0049, 0051One picture check per guide image address or recording copy (source_url; a copy is recording:<id>): the hash fingerprint, clear_share, the title families, the corner marks, the detail share, checked_at. See Stand-in picturessrc/picture-placeholders.js
guide_pictures0046One saved guide picture per image address (source_url), with its title_key, host, w, h, bytes, saved_at, last_seen_atsrc/guide-pictures.js

Config folder ​

PathHoldsSet by
state.db, state.db-wal, state.db-shmThe database and its WAL files; back them up togetherDB_PATH
csrf-secretThe CSRF secret when CSRF_SECRET is unset (CSRF)src/csrf-secret.js
artwork/Saved pictures of recordings (recordings/<uuid>.<ext>) and channel logos (channels/<id>.<ext>)ARTWORK_PATH, else artwork/ beside state.db
uploads/artwork/Pictures that a user uploadssrc/artwork-uploads.js
image-cache/Resized WebP pictures, IMAGE_CACHE_MAX_MB limitsrc/image-thumbnails.js
models/Downloaded For you modelssrc/for-you-engine.js
guide/merged.xml.gz (Merged guide), merged.json (the regions of the last good build), channels.json (the channel list of the last build with a working secondary source), last-source.xml.gz (the last complete download of a source feed)src/guide-merge.js, src/guide-feed.js
comskip.iniOptional Comskip settings; replaces the bundled assets/comskip.inisrc/commercials.js

TVHeadend client ​

TVHeadend exposes a JSON API at <tvh_url>/api/<path>. src/tvheadend.js holds the HTTP client and the normalisers for TVHeadend objects.

Transport ​

  • apiGet(path, params, conn) sends a GET with the parameters in the query string. apiPost(path, form, conn) sends a form-encoded POST; object fields travel as JSON strings in one field (node or conf).
  • tvhRead and tvhWrite export apiGet and apiPost. The setup, guide, bootstrap, and doctor modules build their own paths and call TVHeadend through these two functions.
  • resolveConnection reads the settings tvh_url, tvh_username, and tvh_password. A caller URL gets the stored password only when it has the origin (scheme, host, and port) of tvh_url (Secret binding).
  • sendAuthenticated sends every request. With a username set, it sends the cached Authorization header. On a 401 it stores the www-authenticate challenge, signs the request, and sends it once more.
  • authorizationFor in src/http-auth.js gives a Basic header, or a Digest response (MD5 or SHA-256, qop=auth). The challenge cache keys by <url>|<username> and drops an entry idle for 90 s.
Request or cacheValue
Default API call (REQUEST_TIMEOUT_MS)15 s timeout; also /dvrfile/<uuid> and channel icons
Discovery probe1.5 s timeout
Programme image (fetchProgrammeImage)5 s timeout, 4 MiB limit, JPEG, PNG, WebP, GIF, or SVG bytes
Live stream (openChannelStream)No timeout
Past airings cache10 min; apiPost clears it before and after every write
Tuner count and service multiplex caches10 min
Default DVR profile and default languagesProcess lifetime

Auto-discovery ​

detectServers serves POST /api/tvh-detect:

  1. When TVH_URL is set, it returns that URL with source: 'env' and probes nothing.
  2. rankCandidates lists URLs on port 9981: the request hostname and local socket address, then the host IPv4 addresses (private first; 172.17.0.0–172.31.255.255 and 169.254.x.x excluded), then tvheadend, host.docker.internal, and 127.0.0.1.
  3. probeServer requests /api/serverinfo on every candidate in parallel. A hit is a 200 with sw_version, or a 401 whose www-authenticate contains tvheadend.
  4. Loopback hits drop when another hit exists. Alias hosts drop when their serverinfo body equals that of a numeric-address hit.

With no hit, the route answers 502.

Error mapping ​

TvheadendError carries stage, status, and code. stage is the API path for transport errors.

Conditionstagecode
Network failureThe pathThe Node error code (for example ECONNREFUSED)
HTTP 401 or 403The pathauth
Other HTTP status of 400 or moreThe pathNone
No tvh_url settingconfigno-url
Stream refused with 401 or 403 / 503 / otherstreamauth / no-tuner / http
Connection reset before videostreamno-source
Guide load finds no channelsepgno-channels
A create call returns no uuidrecord or seriesno-uuid
No matching entry or rulecancel, series, or removenot-found

Normalised values ​

  • Series key: seriesKey returns `${channelId}|${title.trim().toLowerCase()}`. Events carry it as series_link; autorec rules carry it as seriesLinkId. An any-channel rule has an empty channel part.
  • Season and episode: parseEpisodeDisp reads episode_disp (for example Season 3.Episode 7) with the patterns Season\s+(\d+) and Episode\s+(\d+). Guide events carry seasonNumber and episodeNumber.
  • Guide text: normaliseEvent and normaliseEntry pass the subtitle and synopsis through cleanGuideText in src/consumer-advice.js. It strips Consumer Advice: ..., Audio Described (AD)., and a leading From: <country>., and returns the advice letters as a list.
  • Channels: listChannels drops disabled channels. hd follows the DVB service type (0x11, 0x19, 0x1f give HD; 0x01, 0x16 give SD), else the channel name. offAir is true when every service is disabled.

Endpoints ​

src/tvheadend.js calls these endpoints.

EndpointUse
serverinfoTest connection, discovery probe, verifyLogin
channel/gridChannel lineup, limit 1000
epg/events/grid, epg/events/loadGuide events, 2000 per page; one programme by eventId
dvr/entry/grid_upcoming, dvr/entry/grid_finishedScheduled and running entries; finished entries (every page of 5000), the import queue
dvr/entry/grid_failed, dvr/entry/grid_removedPast airings for repeat checks, cached 10 min; removed entries that each sync marks not in TVHeadend
dvr/entry/create_by_eventRecord (Single recordings)
dvr/entry/cancel, dvr/entry/stop, dvr/entry/remove, dvr/entry/prevrec/setCancel, stop, and remove entries (Removal from TVHeadend)
dvr/autorec/grid, dvr/autorec/createSeries rules (Series recordings)
idnode/save, idnode/delete, idnode/loadPadding, enable and disable, rule updates, retention; rule and child-entry deletes; one entry for in-progress playback
dvr/config/gridDefault DVR profile (empty name, else the first) and its storage path
epggrab/channel/gridChannel logo fallback
status/inputs, status/subscriptions, hardware/treeTuner readings, tuner holders, tuner count, and the multiplex of each tuner
mpegts/service/grid, service/streamsMultiplex and DVB type of each service; elementary streams of a channel
config/loadDefault language for the live audio track
/dvrfile/<uuid>A recording that TVHeadend still writes (From the start); outside /api
/stream/channel/<uuid>Live TV (TVHeadend stream request); outside /api

The setup modules use these endpoint groups:

ModuleEndpoints
src/tvheadend-bootstrap.jsaccess/entry/grid, passwd/entry/grid, access/entry/create, passwd/entry/create, idnode/load, idnode/delete, serverinfo
src/tvheadend-setup.jshardware/tree, mpegts/network/grid, mpegts/input/network_list, dvb/scanfile/list, mpegts/network/create, mpegts/network/scan, mpegts/mux/grid, mpegts/service/grid, service/mapper/save, service/mapper/status, idnode/save, config/load, config/save
src/tvheadend-guide.jsepggrab/module/list, idnode/load, idnode/save, epggrab/config/load, epggrab/config/save, epggrab/internal/rerun, epggrab/channel/grid, channel/grid, epg/events/grid
src/tv-login.jsaccess/entry/grid, passwd/entry/grid, access/entry/create, passwd/entry/create, idnode/delete
src/doctor.jsRead-only grids and config/load; status/inputs and dvr/entry/grid_upcoming as rights probes (a 403 names the missing right)

TVHeadend setup ​

The setup wizard runs three modules against TVHeadend in order: src/tvheadend-bootstrap.js (logins), src/tvheadend-setup.js (tuners and channels), and src/tvheadend-guide.js (guide). Each module takes an http object with get and post; src/server.js supplies tvhRead, tvhWrite, and verifyLogin. Each apply runs as a background job with a step list that the progress route returns.

Route groupRoutesLimiter
BootstrapGET /api/tvh-bootstrap/status, GET .../progress, POST .../apply, POST .../undobootstrapStatusLimiter (reads), bootstrapLimiter (writes)
Tuners and channelsGET /api/tvh-setup/status, GET .../progress, POST .../tuner-address, POST .../applySame
GuideGET /api/tvh-guide/status, GET .../progress, POST .../apply, GET and POST .../linksSame
TV app loginGET, POST, and DELETE /api/tv-loginbootstrapLimiter (writes)

The setup and guide apply routes answer 202. Every apply route answers 409 while a run is active.

Bootstrap ​

detectFreshInstance requests access/entry/grid and passwd/entry/grid without credentials. The result reason is secured (TVHeadend answers 401 or 403), has-users, or open-default-entry (one access entry with username * and admin: true, and no password entries; only this one is fresh).

applyBootstrap runs these steps in order: check-fresh, create-admin, create-freetvarr, verify-freetvarr, verify-admin, back-up-open-entry, save-connection, remove-open-entry, confirm-locked.

  • The user freetvarr gets a random password of 24 bytes. Each verify step signs in with 11 attempts, 1 s apart.
  • Both access entries get the comment Created by Freetvarr, admin, web UI, streaming, and DVR rights, and the network prefixes from the request.
  • back-up-open-entry saves the open entry as JSON in the setting tvh_open_entry_backup. save-connection saves tvh_url, tvh_username, and tvh_password.
  • A failure before remove-open-entry deletes the created entries. confirm-locked waits for an anonymous serverinfo to answer 401.
  • undoBootstrap posts the saved entry to access/entry/create; the undo route then deletes the setting.

Tuners and channels ​

inspectSetup reads tuners from hardware/tree, networks, the channel count, and recordings in progress. A tuner is a leaf of the hardware tree; its class suffix gives its delivery system (dvbt, dvbc, atsc_t, atsc_c, or isdb_t). src/zone-countries.js maps the time zone to a country code, and pickTransmitter ranks the dvb/scanfile/list transmitters of that country by the time-zone city.

applyChannelSetup runs these steps:

Step idAction
networkUse the chosen network, or create one with mpegts/network/create from the transmitter key
tunersTurn on each tuner and add the network to it
scanPoll every 2 s; fail with no-signal (no services) or scan-timeout (30 min)
mapMap enabled, unencrypted TV services that have no channel; fail with map-empty or map-timeout (20 min)
recordingWhen the default DVR profile has rerecord-errors of 10, set it to 0

After a successful run, the apply route calls applyDefaultFavourites (src/default-favourites.js). For time zones that map to au, with no pinned channel and the setting default_favourites_applied unset, it pins one channel each of ABC, Seven, Nine, Ten, and SBS (HD first).

tunerAddressConfig saves a manual HDHomeRun address as hdhomerun_ip through config/save. Inside a Docker VM it also saves local_ip and local_port 9983.

Guide feed ​

The mjh sources in src/guide-sources/ list the XMLTV feeds from i.mjh.nz: mjh-au has eight city feeds (MJH_AU_FEEDS) and mjh-nz has one. suggestGuide reads them through xmltvFeedsOf(country) and picks the feed whose region equals the time-zone city.

applyGuideSetup runs three steps:

  1. feed: find the module titled XMLTV URL grabber (else no-grabber), and read the feed channels (feed-unreachable, feed-empty). Then enable the grabber with priority 3 and start an import (below).
  2. download: poll epggrab/channel/grid every 3 s until every feed channel exists; download-timeout after 5 min unless some exist.
  3. link: match TV channels to guide channels by LCN, then by normalised name; save the links and return unmatched channels with a guess.

The grabber args depend on time-shifted channels:

  • readTimeshifts finds TVHeadend channels named +N (pattern \+\s*(\d+)\s*(hd)?$) that the feed does not carry, and matches each to a base channel.
  • With none, the grabber args is the source feed URL.
  • With some, pointGrabberAtShiftedFeed stores the source URL in the setting guide_source_url and sets args to the Freetvarr URL of /guide/xmltv.xml. When TVHeadend does not request that URL within 150 s, the grabber falls back to the source URL.
  • keepGuideSaved turns on epgdb_periodicsave and epgdb_saveafterimport.

GET /guide/xmltv.xml (serveGuideFeed in src/guide-feed.js) answers 404 when guide_source_url is empty and no merged file can be served. It streams, through createShiftedFeedStream:

  1. guide/merged.xml.gz, when guideMerge.servablePath() gives it: the setting guide_merged_feed is on (set by the confirm step; default unset), the file exists, and planSources gives a plan for the current time zone and guide_source_url. With the setting unset, TVHeadend never sees the merged file or its freeview.* channels.
  2. Else the source feed (gunzipped for .gz). keepLastCopy writes a gzipped copy to guide/last-source.xml.gz and renames it into place only after the source ends. A copy write that fails unpipes and deletes the copy; the response goes on.
  3. When the source fails before output, guide/last-source.xml.gz. With no copy, the route answers 502.

createShiftedFeedStream adds a <channel> per shifted channel with the id <baseId>.plus<hours>, and writes each base programme twice: the original and a copy moved by the shift hours. It also passes ratings and categories to the classification store (Classification).

After a successful apply, the server clears the guide cache now and again after 2 min (GUIDE_IMPORT_SETTLE_MS).

Merged guide ​

createGuideMerge in src/guide-merge.js builds guide/merged.xml.gz in the config folder 3 min after start, every 6 h, and after a successful POST /api/tvh-guide/apply. One build runs at a time; a request during a build runs one more build after it. firstBuild() gives a promise that settles when the first build ends or fails, at once when there is no plan, and after 20 min at most (FIRST_BUILD_CEILING_MS).

When merged.json names the regions of the current plan (matchesPlan), a build reads every window and writes the file once, so a complete file is never replaced by a partial one. Otherwise (no file yet, or a file for another region) the build writes the file in up to two passes:

  1. The near pass reads the primary windows that start in the next 2 days (NEAR_BUILD_MS) and takes each later window from memory, also when it expired (up to 3 days after its fetch). It writes the file. A later window that is missing or expired counts as pending.
  2. When the near pass has pending windows, the full pass reads them, then writes the file again. Only this pass saves the source health and the fallback items, so a near pass with a short horizon never marks a source as below. When the full pass fails, another build runs after 20 min (PARTIAL_RETRY_MS).

Before each pass, prefetch reads the windows of the pass in time order: every channel for one window, then the next window.

Source contract. Each adapter is { id, countries, regionOf(timeZone), channels(region), listings({ region, channel, from, to, fetchUntil }), hostLimits }, with an optional prefetch({ channels, from, to }). A window that starts at or after fetchUntil comes only from memory. channels gives { id, names, lcn }. listings gives programmes sorted by start as { channel, start, stop, title, subTitle, desc, categories, rating, icon, episodeNums, extras } (times in ms). regionOf gives null outside countries. test/guide-sources.test.js runs the contract against every adapter in createGuideSources().all().

AdapterCountriesRegionData
freeview-auaufreeviewRegionOf (Freeview pictures)/content/v1/channels/region/<region> (channel id is the lower-case dvb_triplet); /content/v1/epgs/<triplet> per 12 h UTC window through freeviewClient (FREEVIEW_API_PACE). Requests use the upper-case triplet (the API answers 400 to 042a). A window reads up to 6 pages of 100. A 204 (past the horizon) is an empty window. A 400 ends the reads of that channel for 15 min, so the host breaker stays closed. A 504 (with no retries) or a response over 2 MB reads the window again as two six-hour halves, and that channel starts with halves for the next 24 h. When one half fails, the window keeps the other half for 15 min and counts as failed. A failed window is empty and waits 15 min, 1 h, then 6 h. A window that starts within 2 days is kept 5.5 h; a later one is kept a random time from 11.75 h to 35.25 h (23.5 h × 0.5–1.5), so each 6-hourly build reads again about a quarter of the later windows. A later window that comes within 2 days is read again when it is older than 5.5 h. Windows that ended before the read start are dropped, and memory holds at most 4000 windows and 4000 failures; above that, the farthest windows go first (dropFarthestWindows). A window fetched more than 3 days ago is never served, also when it comes from the store. With store (createWindowStore, table guide_source_windows), each read window is saved with its fetch time and expiry, and the first read after a start loads the saved windows of the current WINDOW_FORMAT; rows of another format are deleted for every source, and each build deletes the rows of ended windows for every source. Each 12 h window goes to seedFreeviewWindow in src/epg.js as two six-hour windows (each programme in every window it overlaps) with the same expiry, so Freeview pictures reads them from memory. Both jobs share one host queue. Horizon 9 days
mjh-auauTime-zone city (cityRegionOf)https://i.mjh.nz/au/<Region>/epg.xml, one download per region kept 1 h, 120 s limit, 128 MB limit; indexFeed keeps each programme element as text by channel and parses it on listings
freeview-nznznz (freeviewNzRegionOf)As freeview-au (createFreeviewSource) on fvnz-capi-prod.switch.tv: /content/v1/channels (channel id onid::sid, lower case), then /content/v1/epgs/<ONID::SID>. Ratings G, PG, M, 16, 18. Horizon 8 days (about 7.5 measured on 2026-11-10)
mjh-nznzNew Zealandhttps://i.mjh.nz/nz/epg.xml, as mjh-au

freeviewProgrammeOf leaves out a listing titled To Be Advised, To Be Confirmed, To Be Announced, TBA, or TBC, so the secondary fills that slot. It maps any other listing:

  • The episode is the related episode whose id equals the listing episode_id, else the first one (listingEpisodeOf). Freeview NZ lists several episodes per listing, and the first one is often another episode.
  • title; start and end.
  • The episode title as subTitle, when it differs from the title, is not Episode <n>, and the episode tags (when it has tags) include onapi-subtype:episode.
  • The episode synopsis, else the show synopsis.
  • genres/* as categories; a slug (news-and-factual/news) becomes its last part in words (News).
  • classification/* as rating, from the rating labels of the source (AU: G, PG, M, MA15+, AV15+, R18+, C, P).
  • season_number/* up to 9999, episode_number up to 99999 (Freeview NZ has season numbers such as 1039546), and crid_value/*.
  • The episode picture, else the show picture, as icon.

Plan. guideSources.forCountry(country) ranks au as freeview-au, mjh-au and nz as freeview-nz, mjh-nz; every other country has none (Broadcast guide). planSources takes the source without feeds as primary and the mjh source as secondary. The secondary region is the region of guide_source_url (regionOfUrl) when that setting is set, else regionOf(timeZone). When guide_source_url is set and is not an mjh feed, or the country has no sources, there is no plan: no build runs and the route streams the source.

Channels. mapChannels keeps every secondary channel with its id. Each primary channel goes to a free secondary channel whose TVHeadend channels have its DVB triplet (readGuideChannelTriplets: guide links and listChannelTriplets), else to a free secondary channel with the same LCN. A primary channel with no match is added as freeview.<triplet> only when a TVHeadend channel with that triplet has no guide link other than freeview.* (tvChannelsByTripletOf), with that TVHeadend channel name as its display name. When TVHeadend cannot be read, only the freeview.* channels in guide/channels.json are kept. TVHeadend links a new guide channel to any channel with Auto EPG channel on whose name matches (epggrab_channel_autolink in src/epggrab/channel.c), and does not skip channels that already have a link, so a freeview.* channel for an already linked TVHeadend channel would give it two guide links. When the secondary fails, guide/channels.json from the last build gives the ids; with no saved list the build fails.

Programmes. Per channel, mergeChannelProgrammes reads the primary from now - 6 h to the primary horizon and the secondary from now - 6 h:

  • A primary programme matches the closest unused secondary programme that starts within 5 min and whose title agrees (titlesAgree on showTitleKey). The merged programme takes the primary times; the secondary categories, else the primary genres; the primary sub-title, description, rating, and icon, each else the secondary one; the secondary extra elements (such as star-rating, video, credits).
  • Title: a match with two different titles writes the secondary title and saves the pair to title_aliases (kind alias). An unmatched primary programme takes its saved alias, else its own title.
  • Episode numbers (episodeNumsOf): the secondary xmltv_ns, SxxExx, and onscreen; when the secondary has none, primary season and episode give xmltv_ns and SxxExx; else a primary episode alone gives xmltv_ns .<episode - 1>.. The primary CRID is added as system crid, and the other secondary systems (original-air-date, dd_progid, themoviedb.org) are kept.
  • An unmatched secondary programme that overlaps a primary programme by more than 1 min is dropped; any other is written unchanged. So the secondary fills gaps and the days after the primary horizon.
  • A primary title that no secondary programme of the build uses and that has no alias is saved as kind variant-candidate. A candidate is deleted when the secondary lists it, or after 30 days unseen.

Output. The build writes the XMLTV head, one <channel> per mapped channel, then the programmes channel by channel, in XMLTV DTD element order (extras included) into a gzip stream to merged.xml.gz.<pid>.tmp. It renames the file into place only when it has programmes; a build with none (every source failed) keeps the last file. A failed primary gives a secondary-only file.

Measured for Sydney on 2026-11-10 (Mac, LCN mapping only): 19,898 programmes on 189 channels (175 mjh, 14 freeview.*) against 13,800 in mjh alone; more than 1,000 programmes a day for 8 days against 5; 5,893 slots matched, 323 aliases, 120 variant candidates. One build took about 12.5 min with six-hour windows, nearly all of it the 1,558 Freeview requests at the 500 ms gap, with 7 s of CPU, a peak heap of 38 MB (RSS 174 MB), and a 1.4 MB gzip file. Every upcoming match of the series rules in the mjh feed is also in the merged file.

Adding a country ​

A country gets a merged guide when createGuideSources ranks at least one adapter for its code in src/zone-countries.js. To add one:

  1. Add the time zones of the country to COUNTRY_ZONES in src/zone-countries.js, if they are missing.
  2. Write the adapter in src/guide-sources/<id>.js to the source contract above. A Switch Media Freeview API takes createFreeviewSource with its host, regionOf, channelsPath, rating labels, and horizon (freeview-nz.js is the example). An XMLTV feed takes createMjhSource with its feeds (mjh-nz.js). The source with feeds is the secondary: its channel ids are the guide channel ids.
  3. Rank the adapter in createGuideSources (src/guide-sources/index.js): primary first, then the feed source. Add the new parameter to the createGuideSources call in src/server.js with onWindow: seedFreeviewWindow for a Freeview source, so Freeview pictures reuses its reads; add the service to FREEVIEW_SERVICES for pictures.
  4. Save trimmed API answers as fixtures in test/fixtures/<id>/ (two or three channels, one window), with no stream addresses or keys.
  5. Add a case to contractCases in test/guide-sources.test.js; the contract test fails until every adapter in all() has a case. Add the country to the routing test in the same file.
  6. List the source in the adapter table above and in Guide settings.

A source needs no API key and a licence that permits the use (Third-party feeds).

Broadcast guide ​

For a country with no ranked source, guide.sources and GET /api/guide-sources measure the TVHeadend guide with broadcastGuideHealthOf in src/broadcast-guide-health.js. It runs scoreListings on each channel of the cached guide (getGuideSnapshot, 7 days from local midnight, so the horizon reads at most about 7 days) and gives the channel count, listed (channels with listings in the next 48 h), coveredShare, horizonDays (the median of the listed channels), and describedShare. short is true when fewer than half the channels are listed or the median is under 72 h. The doctor check warns when short is true and skips when TVHeadend is not connected; it adds no outside request. UK DVB-T carries 7–8 days of EIT schedule (informitv).

Third-party feeds ​

src/data/suggested-guide-feeds.json lists XMLTV feed addresses per country: checked (the date each address last answered), countries (code to name), and feeds (country, optional region for a time-zone city, name, url, provider, source (the page that documents the address)). suggestionsOf in src/guide-sources/suggested-feeds.js gives the feeds of the country, with a region feed only for the time-zone city. GET /api/guide-sources returns them as suggestions; the Guide settings page lists them with Copy, and the fix text of guide.sources names the first one. Freetvarr never requests these addresses unless the user enters one as a guide address. They are licence-unclear (epgshare01, epg.pw, xmltv.net), so no adapter reads them. Check each address answers before a release; drop the ones that do not.

UK sources checked on 2026-11-10: the Freeview UK web guide API needs no key, but its terms allow private use of the site only; the BBC robots.txt forbids systematic extraction; the Radio Times robots.txt blocks /api; Atlas closed its free feed. So the UK has no adapter.

Source health ​

Each build scores both sources on each merged channel with scoreListings in src/guide-source-health.js, and the build writes the rows to guide_source_health (rows older than 15 days are deleted):

FieldValue
covered_hoursHours of the next 48 h that the programmes cover, overlaps counted once
horizon_hoursHours from now to the last programme stop
described_shareShare of the programmes in the next 48 h with a title and a description
agreementShare of the programmes in the next 48 h that the other source lists within 5 min with an agreeing title (titlesAgree); null when the other source has none
fetch_attempts, fetch_failuresFreeview: windows read and failed during the channel (windowsRead and failedWindows in the adapter stats); mjh: 1, and 1 failure when the read throws

A source row (channel '') adds the covered hours of its channels, keeps the longest horizon, and weighs the shares by programme count. A source whose channel list fails gets a source row of zeros with one failure. below is true when the score is under one threshold: covered_hours under half the median of the source and channel over the last 14 days, horizon_hours under 72, or agreement under 0.6. Agreement counts only when the other source is not under the coverage or horizon thresholds and its own agreement is 0.6 or more. degraded is true when below is true in this build and in the build before; the build before is the newest row from 5–13 h earlier (previousBuildOf), so builds that a mode or pin change starts minutes apart do not count twice.

Listings source ​

The settings guide_listings_source (auto, the default when unset, or a source id) and guide_listings_pins (JSON, merged channel id to source id) choose the source that leads each channel. leadOf decides per channel during the build:

  1. A channel that only one source carries uses that source.
  2. A pin, else a named source, leads, even while it is degraded.
  3. auto: the secondary leads when the primary is degraded on the channel and the secondary is not; the build lists the channel in fallbacks.
  4. Else the primary leads and the slot merge runs as above.

A channel that the secondary leads gets the secondary programmes unchanged (secondaryOnlyOf), with no aliases or candidates. Each build runs as the quiet Activity job guide-merge; each fallback is an item with state warn, and a log line when the channel did not use the secondary in the build before (led).

Confirm step ​

The merged feed reaches TVHeadend only through a one-time confirm step on the Settings Guide page. src/guide-source-routes.js mounts these routes (reads use bootstrapStatusLimiter, writes bootstrapLimiter and CSRF):

RouteAction
GET /api/guide-sourcesSources with health (sourceRowsOf), channels with lead, pin, and fallback (channelRowsOf), the choice, the confirm plan (repointPlanOf), the notice, and the running job
GET /api/guide-sources/notice{ show, added }: true when the setting guide_repoint is unset, guide_repoint_notice is not hidden, the plan has no reason, and the grabber does not read the merged feed yet; ?fresh=1 skips the 5 min cache
POST /api/guide-sources/mode{ mode }: auto or a ranked source id; then a build
POST /api/guide-sources/pins{ channel, source }: a channel of guide/channels.json and a source id, or '' to remove the pin; then a build
POST /api/guide-sources/automaticSets auto and removes each pin whose source is degraded on its channel (the Doctor Switch to Automatic action); then a build
POST /api/guide-sources/keep-grabberSets guide_repoint to kept
POST /api/guide-sources/notice/hideSets guide_repoint_notice to hidden
POST /api/guide-sources/repointAnswers 202 and runs applyGuideRepoint; 409 while it runs or when the plan has a reason
GET /api/guide-sources/unmergeThe plan to stop using the merged guide, or 400 while TVHeadend does not read it
POST /api/guide-sources/unmergeAnswers 202 and runs applyGuideUnmerge; 409 while a guide change runs
GET /api/guide-sources/repoint/progressThe step list and result (kind repoint or unmerge)

repointPlanOf gives the region the merged guide will use (the mjh region of the grabber address, else of the plan) and rebuild when guide/merged.json names another region, the current grabber address, the Freetvarr feed address, the channel count now (channels.json entries with a secondary id) and after, the names of the primary-only channels, and the days ahead of each source. Its reason stops the step: no-plan, no-tvheadend, no-grabber, custom-grabber (an enabled grabber address that is neither a Freetvarr feed nor an mjh feed of the plan), no-address, or building (no merged file or no guide/merged.json yet).

applyGuideRepoint in src/tvheadend-guide.js saves an undo journal in the setting guide_repoint_run before step 1 and after each change, and runs five steps:

  1. merged: find the XMLTV URL grabber (no-grabber, with its enabled, args, and priority). createMergedFeedSwitch stores the earlier guide_merged_feed and guide_source_url, stores the grabber address in guide_source_url when it is not a Freetvarr address, builds the merged guide again when guide/merged.json names another region (buildForPlan, build-failed), then sets guide_merged_feed to on.
  2. point: count the events of up to 8 linked channels and read the last event stop, note the module guide channels, set the grabber args to the Freetvarr feed address with priority 3, keepGuideSaved (the earlier values go to the journal), and start an import.
  3. fetch: wait up to 150 s for TVHeadend to fetch /guide/xmltv.xml (not-fetched). The route notes a fetch only after a 200 response ends (noteServedFeed).
  4. link: read the feed channels and wait for them in epggrab/channel/grid (planRepointLinks). mjh channels link by LCN, then name (matchGuideChannels). Each freeview.<triplet> guide channel gets exactly the TVHeadend channels with that triplet and no mjh link, which also removes links that TVHeadend made by name.
  5. verify: poll for up to 5 min until the last event stop moves later, a sampled channel count changes, or a linked freeview.* channel has events; else not-updated.

Any failure after step 1 runs rollbackGuideRepoint: it puts back the earlier channel lists of changed guide channels, clears the links of guide channels that the import added, puts back the save settings and the grabber enabled, args, and priority, starts an import, and always puts back guide_merged_feed and guide_source_url. A complete rollback clears the journal. At startup, recover rolls back a journal that a restart left, and the Guide page shows the result (interrupted); a rollback that fails keeps the journal for the next start, and the confirm step refuses to run until then. A success sets guide_repoint to confirmed. The step never runs by itself, and it shares a lock with POST /api/tvh-guide/apply.

A successful switch saves its undo record (the grabber enabled, args, and priority, the earlier guide_merged_feed and guide_source_url, the earlier save settings, and the earlier channel lists of the changed guide channels) in the setting guide_repoint_record (switchRecordOf), and keeps it.

Stop using the merged guide. GET /api/guide-sources/unmerge gives the plan: the grabber address now and after, and the counts of links to put back and freeview.* channels to unlink. POST /api/guide-sources/unmerge answers 202 and runs applyGuideUnmerge in src/tvheadend-guide.js under the same lock, journal, and progress route as the switch. unmergeTargetOf in src/guide-listings.js takes the target from the record. With no record, the target is the mjh source address (guide_source_url when it is an mjh feed of the plan, else the feed of the plan region): when readTimeshifts finds +N channels that the feed lacks, the grabber keeps the Freetvarr address and guide_source_url is the mjh address, so /guide/xmltv.xml streams the shifted mjh feed; else the grabber reads the mjh address and guide_source_url is cleared. It runs three steps:

  1. grabber: read the grabber (no-grabber) and a sample of event counts; set guide_merged_feed off and guide_source_url to the target (set of createMergedFeedSwitch); put back the save settings; save the grabber enabled, args, and priority; start an import.
  2. links: put back the channel list of each record link whose guide channel still exists and differs (planUnmergeLinks), and clear the channel list of each linked <prefix>.* guide channel; start an import when anything changed.
  3. verify: when the target is a Freetvarr address, wait up to 150 s for TVHeadend to fetch it (not-fetched); then poll up to 2 min for changed listings. No change gives updated: false, not a failure.

The journal has the same shape as the switch journal, with the state before the undo, so a failure or a restart runs rollbackGuideRepoint and puts the merged guide back. A success sets guide_repoint to kept and clears guide_repoint_record, so the page offers the switch again and the notice stays hidden.

GuideNotice (src/web/components/guide-notice.js) shows the notice under the Home header and at the top of Health, with Review to #/settings/guide and × to hide it. The notice needs a TVHeadend URL grabber that reads a feed Freetvarr can replace (no plan reason). The server keeps it for 5 min and src/web-assets.js writes it into the page as <meta name="freetvarr-guide-notice">, so the notice is in place when Home renders; the client later hides it but never adds it.

TV app login ​

createTvLogin (src/tv-login.js) makes a TVHeadend login for a TV app such as Kodi (TV apps). The access entry has the comment TV apps login, created by Freetvarr, streaming rights only, and the prefix list of the connected user. The password is 12 random bytes in base64url. The settings tv_login_username, tv_login_password, and tv_login_auth_code store the result. deleteTvLogin deletes only entries with the stored username and that comment. POST /api/tv-login returns 409 (code exists) while a TV login is stored, before any TVHeadend call.

Guide ​

Guide cache ​

getCachedGuide in src/epg.js returns one in-memory guide for the current local day (createGuideCache in src/guide-cache.js).

  • loadGuide runs listChannels, listEvents, loadTitleGenres, and loadSeriesEvidence in parallel. The window runs from local midnight to the end of day 7 (GUIDE_DAYS).
  • listEvents reads epg/events/grid sorted by start, 2000 events a page (EVENT_PAGE_SIZE), 4 pages at a time (EVENT_PAGE_CONCURRENCY).
  • GUIDE_TTL_MS is 60 min; an empty guide expires after 60 s. An expired guide of the same day serves while a reload runs. A failed reload serves the cached guide with stale: true. A failed load for a new day (at midnight) also serves the previous day's guide with stale: true, and that day loads again only after GUIDE_STALE_RETRY_MS. getGuideDay builds its day window from localMidnightMs(), not from the guide's startMs, so the stale guide still shows today.
  • One load runs at a time. clearGuideCache drops the cache. onGuideLoaded listeners run after each load.
  • The cron tick (cron:guide), keepGuideWarm, and guide setup trigger reloads.

getRecordingState caches the merged TVHeadend recording state for 45 s (createRecordingStateCache in src/recording-state-cache.js). After a failure it serves the last state with stale: true for 60 s. invalidateRecordingState clears it after each write, including a write that failed, and bumps a generation counter. Every read after an invalidate starts a new load; an older load that ends later does not write the cache and does not clear the newer load.

Guide history ​

saveGuidePrograms (src/guide-history.js) writes every loaded event to guide_programs in one transaction. It deletes rows that overlap the loaded span per channel, inserts the events in chunks of 500, and deletes rows that ended before the start of yesterday. The columns are channel_id and start (primary key), end, program_id, dvr_state, dvr_uuid, and program_json.

getGuideDay merges saved rows with live events. A saved row stays only when no live event overlaps it. toGuideCell adds past and recorded (past, with a dvr_uuid).

GET /api/epg/guide?day=0..6 returns one day. guideDayWindow gives dayStart, dayEnd, and spillEnd from calendar dates in the process time zone. A daylight-saving day lasts 23 or 25 hours. spillEnd is dayEnd plus 180 min (EPG_SPILL_MIN). A programme that crosses midnight appears in both days.

Series evidence ​

airingKindOf (src/display-kind.js) gives each event an airing kind, first match wins:

  1. movie when airingLooksLikeFilm holds.
  2. one-off for a sports airing whose stored databaseIds is none, or is unset and the title has a year.
  3. series when the title has a TVmaze record, or the event has a season, an episode, or an episode title.
  4. series when the title airs 3 or more times in the loaded week; otherwise one-off.

loadGuide saves the airing kinds as evidence in Title kinds, then gives each event a kind through displayKindOf: the stored title kind, with the airing kind as the hint (requestKindOf). isFilmAiring in src/genre-enrichment.js reads the same row, so the guide, For you, and the pickable shows agree.

saveGuideEvidence writes per-title facts to series_evidence. facts_json holds recurs, realSeason, sports, awardShow, and minDatedEpisode. recurs is true when at least 2 distinct episodes first air on 2 different local days. New facts merge with stored facts by logical OR. The sync and the library read the table through loadSeriesEvidence (Library kinds).

Title kinds ​

title_kinds keeps one kind per show key (showKeyOf). decideTitleKind in src/title-kinds.js reads the evidence in this order:

  1. The programme_kind_overrides row: movie, show (series), or one-off. not-movie blocks movie in every later step.
  2. One library kind: the Plex library items of the title (kindsFor in src/library-titles.js). Two kinds give no library answer. A library movie is skipped when the guide lists the title with episode details.
  3. The guide majority (guideKindEvidenceOf): movie when every airing is a film, else the commoner of series and one-off.
  4. A hint: series when a recording of the title has episode details.

A guide category of sport or news blocks movie (isSportOrNewsCategories), unless a category is also movie, movies, or film. The categories come from programme_categories for the loaded week, matched by classificationTitleKey. A blocked film airing counts as a one-off. The sport and news categories are exactly sport, sports, other sport, sports other, news, news/current affairs, news & current affairs, and current affairs, compared trimmed and in lower case, so Sport drama or Sports film is not blocked. Episode details follow hasEpisodeDetails in src/episode-details.js, so a description in the episode title (as Seven lists films) is not an episode. When no evidence is left, for example after an override is removed from a title with no library or guide evidence, the row becomes series with source hint, so request hints count again.

The table is written only when the evidence of a title changes (mergeTitleKinds):

  • loadGuide writes the guide evidence (guideKindUpdatesOf), with the override and the library kinds, before it sets the event kinds.
  • refreshLibraryTitleKinds in src/epg.js writes the library evidence (libraryKindUpdatesOf) after each sync and each Plex watch sync. A title that left the library gets an empty library list.
  • PUT and DELETE /api/programme-kind/:showKey rewrite the row of the title (rewriteTitleKind).

Evidence that a writer does not give stays as stored, so a title that leaves the guide keeps its guide evidence. A new kind for a stored row marks the art_resolutions rows of the show key due with a new stamp (markKindChangesDue) and sends art events. Rows are never deleted.

requestKindOf answers a request. An override row ignores the hint. Otherwise a hint counts when the library has that kind, or when the hint is movie and the guide listed a film airing of the title; a blocked movie never counts. So a film airing of a title that the library holds as a series (Fargo) keeps its film picture, and a sport game never shows as a film.

Channel order ​

getChannelPrefs reads the settings epg_pinned_channels and epg_hidden_channels (JSON id arrays), epg_channel_sort (default, number, or name), epg_hide_sd_simulcasts, and epg_hide_sd_channels. GET and PUT /api/epg/channel-prefs read and write them.

orderChannels (src/web/channel-order.js, re-exported by src/channel-order.js) puts pinned channels first in pin order, then sorts the rest. A channel is hidden when it is not pinned and is in the hidden list, is a hidden SD simulcast, or is SD while epg_hide_sd_channels is on.

GET /api/epg/logo/:channelId serves the channel's icon_public_url, then the epggrab/channel/grid icons, then the saved artwork. The memory cache keeps a hit for 24 h and a miss for 10 min.

Skipped episodes ​

A series-rule airing that TVHeadend has not scheduled yet cannot be cancelled. cancelProgram then stores a row in pending_skips (program_id, channel_id, title, start_ms, end_ms). On each recording-state load, withPendingSkipsApplied disables a newly scheduled entry that matches a row (idnode/save with enabled: false), then deletes the row. An entry matches when it has the same channel and event id, or else the same channel and title with a start at most SIMULCAST_START_TOLERANCE_MS (2 min) away; of several title matches, the nearest start wins. Rows whose end_ms passed are deleted. watchPendingSkips reloads the recording state every 5 min while a skip waits.

Repeats and rules ​

  • isSameIdentity (src/repeat-match.js) decides whether two airings are the same episode: equal episode URIs; else equal season and episode numbers; else equal titles with equal real subtitles and agreeing descriptions.
  • earlierAiringOfEntry finds an earlier airing of the same episode for an upcoming entry. splitRepeats marks a rule timer (autorecId set) as a repeat; a one-off the user scheduled is never a repeat, except a TVHeadend duplicate (duplicateOfStart). withRecordedRepeatsSkipped disables each enabled repeat whose original is recorded.
  • planUpcomingRecordings projects expected episodes only from enabled autorecs, so a paused series lists none. It also projects the airings of each title variant of a rule (titleVariants), by the series link of that title.
  • autorecMatchesAiring (src/autorec-match.js) tests a guide airing against an autorec rule: channel, title, serieslink, weekday, start window, and duration. A title in Freetvarr's whole-title form matches through isSameShowTitle; a plain-text title matches as a substring; any other title is a regular expression of up to 200 characters with a cost cap. A rule that sets tag, content_type, cat1–cat3, star_rating, btype, brand, or season is unsupported and never matches.
  • The whole-title form is ^Title (or ^(Title|Variant|…) with title variants) and then sameShowSuffixOf(country): an optional space, one of :, (, or -, and the rest of the title, in a form TVHeadend reads as POSIX ERE or PCRE2. The country is the install country, installCountry in src/title-countries.js: countryForTimeZone(currentTimeZone()), read again when process.env.TZ changes. The suffix refuses a rest that is only a foreign edition tag, with an optional space before it and an optional ) after it. The refused tags (excludedEditionTagsOf) are UK, US, USA, AU, AUS, and NZ, less the own words of the country (countryTitleWordsOf), in that order. An au or nz install refuses UK, US, and USA, so its suffix is the same as in 2.10.1. An unknown country refuses nothing, and its suffix is ( ?[-:(].*)?$. The suffix has no lookahead: notAnyOfPattern builds a trie of the refused rests and writes its complement as nested groups and negated bracket expressions, with both letter cases in each bracket. isSameShowTitle applies the same rule, with excludedTags (the install country's tags when not given). anchoredTitlesOf reads the titles back with the suffix of any country (knownEditionTagSets), and gives the refused tags of that suffix as excludedTags, so the read-back and the series key do not depend on the install country. It also reads the 2.9.0 suffix ( ?[:(-].*)?$ (excludedTags: []), but only with a single title: a group of titles before the 2.9.0 suffix is a hand-made pattern, so the rule keeps its raw title as its name and series key.
  • airingIdentityOf (src/airing-identity.js) groups airings of one broadcast on twin channels: the same title in one channel family (an SD and HD pair, or a channel and its +N channels) with base starts 60 s or less apart (TWIN_START_TOLERANCE_MS).

Recording rules ​

Freetvarr writes two kinds of rule to TVHeadend: single DVR entries and autorec rules (series recordings). src/tvheadend.js makes every call. src/epg.js wraps each call and clears the cached recording state after it.

Single recordings ​

POST /api/epg/record takes channel_id, program_id, and optional lead_time, lag_time, and add_to_library. When the programme has a row in pending_skips, recordProgram deletes the row and makes no TVHeadend call. Otherwise scheduleRecording runs:

  1. When an enabled entry for the same programme exists in dvr/entry/grid_upcoming, send idnode/save with the padding the request gave (if any), and stop. No second timer is made.
  2. When a disabled entry for the same programme exists, send idnode/save with enabled: true and only the padding the request gave, and stop. A skipped series episode keeps the padding it copied from its rule.
  3. Otherwise send dvr/entry/create_by_event with event_id, config_uuid (the default DVR profile), and comment.
  4. Send idnode/save with start_extra and stop_extra on the new entry. When this save fails, the result is still ok with paddingSaved: false, and the programme sheet says so.

The comment is the library tag: freetvarr: add to library, or freetvarr: not for the library when add_to_library is false. normaliseEntry reads it back as libraryChoice (include or exclude). The padding defaults are DEFAULT_LEAD_MINUTES (2) and DEFAULT_LAG_MINUTES (10), used only for a new entry. src/recording-defaults.js stores the Add to library default in the setting add_to_library_default.

POST /api/epg/cancel calls cancelRecording. A running entry stops (Stop a recording). A scheduled entry from an autorec is disabled with idnode/save. A scheduled single entry gets dvr/entry/cancel, then dvr/entry/remove.

Series recordings ​

POST /api/epg/record-series takes series_link, channel_id, program_id, and optional lead_time, lag_time, episodes_to_keep, any_channel, paused, and add_show_rule. enableSeriesTag returns an existing autorec with the same series key (existed: true). Otherwise it sends dvr/autorec/create with conf from newAutorecConfOf:

javascript
{
  enabled: !paused,
  name: title,
  title: anchorAutorecTitle(title),
  fulltext: false,
  channel: channelId,
  start: 'Any',
  start_window: 'Any',
  weekdays: [1, 2, 3, 4, 5, 6, 7],
  pri: 2,
  record: 1,
  start_extra: leadTime,
  stop_extra: lagTime,
  maxcount: episodesToKeep,
  config_name: configName,
  comment: 'freetvarr',
}
  • channel is '' when any_channel is true. maxcount defaults to 0 (keep all).
  • record: 1 (DUPLICATE_DETECTION_EPISODE_NUMBER) turns on TVHeadend duplicate detection by episode number.
  • title is ^${escapeAutorecTitle(title)}( ?[:(-].*)?$. TVHeadend reads the autorec title as a caseless regular expression that matches anywhere, so the anchors stop The Chase from recording The Chase Australia or Beat The Chase. The tail still matches The Chase (Ep 5) and The Chase: Celebrity Special. It is valid POSIX ERE and PCRE.
  • comment: 'freetvarr' (CREATOR_TAG) marks the rules that Freetvarr made. listAutorecs turns each escaped title, with or without the anchors, back into the literal title (literalTitleOf), so the series key stays channel|title.
  • Unless add_show_rule is false, the route calls ensureShowFolder with origin user (Show origin).
RouteFunctionTVHeadend call
POST /api/epg/pause-seriessetSeriesTagsEnabledidnode/save with enabled on each autorec
PATCH /api/library/shows/:key/ruleupdateSeriesTagsidnode/save with maxcount and padding on every autorec of the show key
POST /api/epg/cancel-seriescancelSeriesRulesidnode/delete on each autorec (Stop a recording)

rulePatchFrom in src/library.js limits episodes_to_keep to 0–999, and the padding to 0–240 minutes (MAX_PADDING_MINUTES).

Watchlist ​

src/watchlist.js holds the routes (GET, POST, PATCH, and DELETE /api/watchlist) and the sweeper. A watchlist row has title, title_key (unique), mode (notify or record), an optional channel_id, padding, seen_through, fulfilled_at, and series_link_id. guideMatchesFor lists up to 20 future airings on visible channels with the same show key.

The record sweeper runs every 15 minutes, at each GET /api/watchlist (which answers without waiting for it), and after each write that sets record mode. For each unfulfilled record row, it takes the first match with a series_link, calls recordSeries with anyChannel: true, and sets fulfilled_at and series_link_id. A row that fails logs a warning and stays unfulfilled; the sweep goes on with the next row. It then calls ensureShowFolder with origin user when add_to_library_default reads as true.

Sync pipeline ​

src/sync.js runs the sync. A sync imports each new finished recording into the library and refreshes Plex. It then removes imported recordings from TVHeadend where the series folder asks for it.

Triggers ​

startSync({ trigger, showId }) starts a sync:

TriggerCaller
cronsrc/scheduler.js, on each tick of the setting sync_cron
recording-finishedsrc/auto-import.js, after a recording ends
restartsrc/restart-sync.js, after a restart stopped a sync (Restart sync)
manualPOST /api/sync with no show_id
manual-singlePOST /api/sync with an integer show_id; imports only entries that match that folder
manual:importPOST /api/recordings/:recording_id/library with choice: 'include'

POST /api/sync returns 202 for a new sync and 200 when one already runs. syncLimiter allows 5 requests a minute. For cron and recording-finished, a missing TVHeadend URL gives { skipped: true } and no syncs row.

scheduleWith in src/scheduler.js validates the expression with node-cron and falls back to */30 * * * *. Each tick runs these jobs through measureJob, each independent of the others: cron:sync, cron:guide (getGuideSnapshot), cron:viewing-history (pruneUserEvents, backfillUserEvents), and cron:for-you (runForYouUpkeep). startScheduler runs again when POST /api/settings changes sync_cron or time_zone. GET /api/sync-status returns activeSyncId, cron, and nextRunAt.

Auto-import ​

watchForFinishedRecordings calls getRecordingNow (src/recording-now.js) every 60 s; the answer is cached for 4 s. When an active recording leaves the active list, it loads the entry with idnode/load and calls the onRecordingFinished listeners. The first poll also announces entries that ended in the last 60 minutes and have no recordings row.

createAutoImport in src/auto-import.js waits for quiet before it starts a sync. Each finished recording resets a 60 s timer (QUIET_MS); the timer never fires later than 5 min (MAX_WAIT_MS) after the first finish. When a sync already runs, one follow-up starts from the next onSyncFinished call. The poll and the auto-import start only when the cron expression runs on at least one day (scheduleEverRuns in src/schedule-runs.js).

Single flight ​

inFlight in src/sync.js holds { syncId, promise } of the running sync. startSync returns { syncId, alreadyRunning: true } while inFlight is set. With followUp: true (the Import route sends it), a call during a sync also starts one more sync with that trigger when the running sync ends. startSync waits while a folder rename or a library delete runs (runLibraryChange in src/library-busy.js), for up to 10 min; after that it records a sync with status error and does not run; those refuse to start while a sync starts or runs (isSyncBusy), and an ad scan refuses while they run. Each sync is a sync job in Activity, titled Sync #<id>.

Sync order ​

  1. listFinished reads every page of dvr/entry/grid_finished (5000 a page, up to 10 pages). A failure here, or in the shows read, ends the sync with status error. markRemovedByTvheadend then reads dvr/entry/grid_removed (shared with the 10 min past-airings cache) and sets deleted_from_tvh_at on each row whose entry TVHeadend removed itself (fileremoved set, for example by Keep the latest). A file that is only missing, such as on an unmounted disk, does not count.
  2. importContextOf loads the kind overrides, the series_evidence facts, the recordings rows by show key, and the autorec names.
  3. Each finished entry runs through the Import state machine.
  4. startRecordingPictures starts the recording picture saves and does not wait for them (Recording artwork).
  5. Each library kind with an import refreshes its Plex section (Plex).
  6. runAutoDelete removes the queued recordings from TVHeadend, with the earlier removals that wait for a retry (Remove after import).
  7. sweepLibraryStates checks that each imported file still exists (Library delete).
  8. finishSync writes the status and summary, then runs pruneSyncHistory, pruneTombstonedRecordings, and pruneCutOriginals.

The finally step clears inFlight, then calls each onSyncFinished listener with { syncId, trigger }, also after an error. The status is ok, partial when any item failed, or error. summary_json holds the trigger, the counts imported, skipped, and failed, errors, up to 100 items (SYNC_ITEMS_CAP), milliseconds per step, the Plex results, the delete result, and the ads counts.

Before app.listen, closeSyncsLeftByRestart (src/startup-reconcile.js) runs resetInterruptedImports, which sets each importing row back to pending, and closeInterruptedSyncs, which sets each running row to stopped and returns { id, trigger } for each. Both only read and write the database, so a sync that starts after the server listens stays running.

Restart sync ​

scheduleRestartSync (src/restart-sync.js) runs in the app.listen callback after rebaseFilePaths, recoverInterruptedCuts, resetInterruptedScans, and startScheduler. After RESTART_SYNC_DELAY_MS (30 seconds), restartSyncPlan picks one result from the stopped rows:

PlanConditionAction
noneNo row was stopped.No timer.
leave-to-scheduleThe newest stopped row has the trigger restart.No sync.
already-syncedhasSyncStartedSinceBoot() is true: beginSync created a sync row since this boot.No sync.
syncs-offscheduledSyncsOn() is false.No sync.
schedule-duegetSchedulerNextRun() is at most 2 minutes away (SCHEDULE_GRACE_MS).No sync.
run-againNone of the above.startSync({ trigger: 'restart' }).

The restart trigger is the loop guard: a restart sync that a restart stops is never run again. Older stopped rows do not count. A restart within RESTART_SYNC_DELAY_MS clears the timer, and the next boot finds no running row, so the schedule runs the next sync. shutdown calls the cancel function that scheduleRestartSync returns. startSync holds the sync lock and waits for library changes, so the restart sync never runs beside another sync. When startSync starts a new sync that did not give up (gaveUp), noteSyncRanAgain writes ranAgainAt (ISO time) and ranAgainSyncId into the summary_json of each stopped row. restart is in AUTOMATIC_TRIGGERS, so with no TVHeadend address the sync skips without a row.

The stopped status is not a failure. SYNC_OUTCOMES.fails matches only error and partial; healthLevelOf, healthSummaryOf, and the sync.health Doctor check give a stopped last sync no warning; findImportSync skips stopped rows. Earlier versions wrote a stopped sync as error with the message Freetvarr restarted before this sync finished.; syncRowOf (src/sync-history.js) reads such a row as stopped and drops that message, with no database change. GET /api/syncs, latestFinishedSync, and readLatestSync read rows through syncRowOf, and SYNC_OUTCOMES.fails leaves those rows out. In the web app, syncOutcome returns stopped (a dash in --color-text-3), syncResult returns stopped by a restart, and ranAgainText returns Ran again at <time>.

Sync history ​

src/sync-history.js serves GET /api/syncs (page, pageSize default 50 and maximum 200, show filters, trigger of manual, cron for cron and restart, or auto for recording-finished) and DELETE /api/syncs[/:id]. An empty sync has status ok and no imports, failures, or removals. A show filter always lists running and stopped rows. pruneSyncHistory keeps the newest 100 empty syncs, then the newest 500 syncs, and never deletes a running row.

Import state machine ​

Show matching ​

matchShow(shows, title, { sport }) in src/sync.js picks the series folder (a shows row) for a title. It takes the longest matching show_pattern. A row with origin user (or none) matches as whole words anywhere in the title, case-insensitive (wordBoundedPattern). A row with origin auto matches when its show key equals the title's show key, or when the title is the pattern followed by a colon, a dash, or a bracket (isSameShowTitle, the series rule title form), so the auto row Survivor does not match Australian Survivor. A row of either origin also matches each title in its title_variants, the same way: doSync adds them from series_title_variants by the show key of show_pattern (withTitleVariants). For a mostly-sport title, an auto row matches only when its show key equals the title's show key. So the auto row Rugby League World Cup 2026 does not match Women's Rugby League World Cup 2026. Sport means a DVB genre code from 0x40–0x4F.

Decision tree ​

doSync runs each finished entry through these steps. saveRecordingDetails first upserts the entry's details on its recordings row (channel, air time, synopsis, genres, tvh_filename).

  1. libraryDecision decides import or hold, first match wins:
    1. library_choice exclude on the row holds (Kept out of the library).
    2. library_choice include on the row imports. Import in the Recording log sets it.
    3. The entry's library tag exclude holds (Recorded with Add to library off).
    4. A matched folder, the setting import_unmatched not false, or the library tag include imports.
    5. Anything else holds (No series folder for this title, and Import every recording is off).
  2. holdRecording sets status not_imported, error to the reason, and file_path, purged_at, and log_cleared_at to null. So a held row cleared from the log comes back at the next sync while TVHeadend still has it. It leaves a done, partial, or importing row, or a row with deleted_from_tvh_at, unchanged.
  3. lookUpDatabaseIds runs when needsDatabaseIds is true (Sport and database ids).
  4. libraryKind gives tv, oneOff, or film from seriesKindOf (Library kinds). A film with no movies folder gives oneOff.
  5. For tv with no matched folder, folderForSeries calls ensureShowFolder. An entry from a series recording uses the autorec name and origin user; any other entry uses its title and origin auto.
  6. processItem writes skipped with the reason in error when the path does not map, the source file is missing, or the library folder for the kind is not ready (Library folder check). A partial row keeps its status and file_path; only error changes.
  7. importItem imports the file and classifies it. When the folder or the copy throws, the row becomes failed with the error and no file_path, and the next sync tries again. A copy that throws deletes its part-copied file. It runs Ad removal only for a done item with a series folder.

Each import is an import job in Activity, titled Import · <title>.

Library folder check ​

libraryRootProblemOf(root) in src/library-roots.js gives missing when readdir of the folder fails, and empty when the folder has no entry other than names that start with ., @, or # while recordings rows with status done or partial, no purged_at, no library_state, and no library_deleted_at have a file_path under it. Anything else is ready. An empty folder on a new install is ready, because no row points into it. A sync checks each folder once (createRootCheck).

  • The TV, one-off, and movies imports skip with <kind> folder <root> not found; mount it or change it in Settings or <kind> folder <root> is empty, but imported recordings point into it; check that it is mounted. No folder is created, so nothing is written to the mount point of an unmounted share, and nothing is removed from TVHeadend.
  • refreshLibraryStates keeps the stored library_state of a row whose file is missing when the row's folder is not ready, so the Library keeps its shows while the share is gone.
  • Import again (POST /api/recordings/:id/library with include) answers 409 when the row's file_path is under a folder that is not ready.
  • The Library folders health check warns for each empty folder.

In Docker, a share mounted on the host after the container started does not reach the container, so a restart is needed.

Path translation ​

localPathFor({ tvhFilename, tvhRecordingsPath, recordingsRoot }) replaces the tvh_recordings_path prefix of the TVHeadend filename with recordings_root (Full environment reference). A filename outside that prefix, or with a .. segment, gives null and the error TVHeadend file path is outside the recordings mount. Before the import, processItem resolves the real path of the source and of recordings_root; a source outside the folder is skipped with the error <path> is outside the recordings folder <root>.

Destination paths ​

KindFunctionPath
tvbuildDestPath<media_root>/<dest_folder>/<season folder>/<episodeFilename>
oneOffbuildOneOffPath<oneoff_root>/<title>/<title> - <YYYY-MM-DD HHMM>[ - <episode title>].<ext>
filmbuildFilmPath<movies_root>/<name>/<name>.<ext>; <name> is Title (Year), or Title
  • The season folder comes from shows.season_template, default Season {season}. {season} and {season_padded} pad to two digits; {season_unpadded} does not. No season gives 00.
  • episodeFilename gives <folder> - SxxEyy[ - <episode title>].<ext>, or <folder> - <YYYY-MM-DD>[ - <episode title>].<ext> without episode numbers. The date is the local air day in the server time zone. <folder> is dest_folder without a {tvdb-…}, {tmdb-…}, or {imdb-…} id hint.
  • <ext> is the extension of the TVHeadend file, or ts. createValidFilename removes \ / : * ? " < > |.
  • guardWithinRoot throws destination escapes media root when a path resolves outside its root.

ensureShowFolder in src/show-folders.js returns the enabled folder that matchShow finds. With origin user, it changes an auto row to user. With no match, it looks up the show identity with a 5 s wait (Show identity), then inserts a shows row. newShowFolderOf picks dest_folder, first match wins:

  1. An existing folder whose name holds the identity's {tvdb-<id>} or {tmdb-<id>}.
  2. An existing folder named as the identity name, or as the title (plus at most a year, country, or id suffix).
  3. The identity folder name: <name> {tvdb-<id>} or <name> {tmdb-<id>}.
  4. The title, through createValidFilename; else Recordings.

Free destination ​

freeDestination in src/sync.js tries the planned path, then - copy 2, - copy 3, and so on before the extension ((2) for a film). Only rows with no library_deleted_at and no purged_at hold a path. A candidate is free when this row already holds its file_path, or when no row holds it and the file is missing, is the same inode as the source, or has the source size (a copy left by a Reset). importItem sets file_path to null on any deleted or purged row that still names the path it takes.

importFile returns at once when the destination exists with the source size. Otherwise it deletes the destination, then calls fs.link. On any error it calls fs.copyFile, and a 1 s ticker (PROGRESS_TICK_MS) reports the copied size to the Progress registry.

A hardlink fails across filesystems and across two bind mounts (EXDEV). The example compose file mounts ${DATA_PATH} once at /data, with RECORDINGS_ROOT=/data/recordings and MEDIA_ROOT=/data/media/tv (Docker deployment). The Hardlinks health check makes a test link into each library folder.

Classify and status ​

classifyImport({ expectedSize, actualSize }) compares the source size with the imported size. A shortfall over 1,000,000 bytes (SIZE_TOLERANCE_BYTES) gives partial; the sync counts it as failed, and the next sync imports it again. Anything else gives done. Both set imported_at. When TVHeadend's status text is not Completed OK, error holds TVHeadend reported: <status>.

Recording artwork ​

src/artwork.js stores recording pictures as recordings/<uuid>.<ext> in the artwork folder (Config folder). saveArtwork shrinks a picture over 150 KB to 960 px wide. POST /api/epg/record and sync save pictures through saveRecordingPicture in src/epg.js:

  1. recordingPictureFor takes the event id (TVHeadend broadcast), the title, and the TVHeadend image of the entry. An event that is gone from the guide uses the TVHeadend image and title.
  2. It runs RECORDING_SAVE_CHAIN in the picture resolver (resolveRecordingPicture), with a 10 s budget, through the picture gate: the Freeview episode picture of the airing, the airing's own image (the TVHeadend image), the Freeview show picture, the Freeview title copy, then the title copy. Each Freeview picture is its saved copy, then its address. A saved copy holds no picture of another airing, owner choice, Plex picture, online picture, or frame; the episode chain serves those live.
  3. The bytes come from the gate, so a stand-in is never saved. A title card is saved only when no other picture loads.
  4. saveRecordingPicture answers saved, missed (the chain ended with no picture), retry (a step was pending or failed to load), or deferred (a load met the 60 s wait after a failure of that address, or a host skipped in this run). A picture from a later step is saved only when every earlier step failed for good (a 404, a stand-in, or no image address). When an earlier step failed for a time (a timeout, a skipped host, or the 60 s wait), the answer is unsettled and nothing is saved. On the last of 3 tries (ARTWORK_ATTEMPTS), a picture from an unsettled answer is saved, and no picture is missed. A first deferred is not a try; a second deferred in a row for the same recording is.

The record route saves only a settled picture. Sync never waits for a picture:

  1. saveRecordingDetails queues a row whose image_checked_at is empty.
  2. After the imports, startRecordingPictures starts one background run (createRecordingPictureRun), unless one already runs. The sync finishes without it.
  3. The run saves the queued rows, then each enabled upcoming entry (captureUpcomingArtwork), then the rows queued in the meantime. Rows and entries that did not settle in an earlier run go last. An error on one row is logged, and the run goes on.
  4. Each load has 4 s; a host that runs past it is skipped for the rest of the run. All relative TVHeadend image paths are one host.
  5. saved and missed set image_checked_at; retry and deferred leave it empty, so the next sync asks again. An upcoming entry that answers saved or missed is not asked again until a restart.

The tries and the settled entries are kept in memory per recording id; Refresh artwork clears them for the show's recordings (forgetFailedArtwork). Clearing a row that TVHeadend still has from the log deletes its picture and sets image_path and image_checked_at to null, so the picture comes back with the row.

pruneTombstonedRecordings deletes recordings rows whose deleted_from_tvh_at is more than 30 days old (RECORDING_TOMBSTONE_TTL_DAYS), only when the row is out of the library (purged_at set, or status not done or partial) and ad_backup_saved_at is empty. pruneRecordingArtwork then deletes pictures with no row that are at least 14 days old.

Library kinds ​

seriesKindOf in src/series-kind.js gives show, oneoff, or movie for a title. The import calls it through libraryKind in src/sync.js; the Library and the folder moves call it through kindOf in src/library.js. The first rule that applies gives the kind:

  1. A user choice in programme_kind_overrides: show, one-off, or movie. The choice not-movie only switches off rule 4.
  2. A user rule gives a show: a series recording for the title, or a folder with origin user.
  3. A title match (any matched folder) gives a show, or a one-off for a sport one-off (rule 5).
  4. A film by the guide's film rules (looksLikeFilm) gives a movie when a movies folder is set. At import, a title kind whose guide category is sport or news switches this rule off.
  5. A sport one-off gives a one-off (Sport and database ids).
  6. Recordings on two or more local days give a show.
  7. Series facts give a show: the title recurs, or it has a real season number (not a year).
  8. An event title (isEventTitle: for example grand final, awards, telethon, concert, election), or a TVmaze award show, gives a one-off.
  9. An episode number on a year season gives a show. For sport, only episode 2 or above counts.
  10. Anything else gives a one-off.

seriesFactsOf builds the facts from the recordings, and mergeSeriesFacts adds the facts stored in series_evidence.

Show origin ​

shows.origin is user or auto. Add title (POST /api/shows), a saved edit (PATCH /api/shows/:id), a picked identity, Record series with a show rule, the watchlist sweeper, and an import from a series recording set user. An import of a title with no series recording, and a folder move to Shows, create auto rows. Record series reuses an auto row only when it matches under the auto rule (Show matching), so Record series on Australian Survivor makes its own row and leaves the auto row Survivor as it is.

Sport and database ids ​

isMostlySport is true when more than half of a title's recordings carry a DVB sport genre. isSportOneOff is true for a mostly-sport title when series_evidence.database_ids is none, or when no fact is stored and the title holds a four-digit year. databaseIdsOf stores found when a settled identity lookup has a TheTVDB or TMDB id, else none.

needsDatabaseIds in src/database-ids.js is true for a mostly-sport title with no override and no user rule, when no fact is stored or a none fact is at least 30 days old. The import then waits up to 5 s for the lookup; a lookup still pending saves its fact later, with a 60 s wait. The folder-move pass settles up to 5 titles per pass, and retries a title after 30 min.

Show identity ​

showIdentityFor in src/show-identity.js finds the TVmaze show, and a TVDB or TMDB id, for a title. It checks, in order: a pick in show_identity_picks (state chosen); a remembered result (hits 24 h, misses 6 h, up to 500 keys); state unreachable within 10 min after a failed lookup; state off with TVmaze lookups off; then a new lookup. A lookup longer than wait (default 15 s) gives pending and keeps running.

createShowMatcher in src/show-match.js searches TVmaze (/search/shows, with and without a country tag, then AKAs). It drops shows from another country and shows that premiered after the airing, then scores the rest:

Score itemPointsCondition
airTime100/shows/<id>/episodesbydate has an episode within the airing
network40A domestic show on the network family of the channel
titleCountry30The show's country equals the country in the title
domestic20A domestic show with the network or airTime points
running5The show ran within a year of the airing

A single show wins. Otherwise the top show needs at least 10 points and a lead of at least 20. The TVDB id comes from externals.thetvdb; with none and a TMDB key set, tmdbShow finds the TMDB id. No winner gives choose with up to 6 candidates, or none.

GET, POST, and DELETE /api/shows/:id/identity show, pick (tvmaze_id), and decline an identity. The identity columns on shows are tvmaze_id, tvdb_id, tmdb_id, database_title, and identity_state.

Folder moves ​

src/library-reclassify.js moves recorded files when a title changes kind. runReclassification runs one pass at a time. It groups the done and partial rows with a file_path by show key (show_title_override, else title). planReclassification plans the moves:

  • A show group: each file in the one-off folder moves to buildDestPath under the matched or a new folder.
  • A oneoff group: each file in the TV folder moves to buildOneOffPath.

applyMove skips a move while ad removal runs, when file_path changed since the plan, when the file is missing, or when the target exists. moveFile calls fs.rename. On EXDEV it copies to <target>.part, checks the size, renames the copy into place, and deletes the source; a failed copy deletes the .part file. The .orig backup and the .edl file move with the video. After moves, the Plex TV and one-off sections refresh. planRetiredTitleMatches disables each auto folder whose title is now a one-off and that keeps no file.

The pass runs 3 min after startup when the setting library_reclassify_v1 is unset (runReclassificationOnce), after every sync, and after PUT or DELETE /api/programme-kind/:showKey. When TVHeadend's series rules cannot be read, the pass changes nothing. node scripts/reclassify-library.mjs --db <copy of state.db> --dry-run prints the planned moves.

Folder name fix ​

src/show-folder-rename.js renames a series folder to the identity folder name. GET /api/shows/:id/folder-fix returns a plan with a state: not-found, kept, no-match, done, managed (a Sonarr or Radarr file under the folder), target-exists, or ready. POST /api/shows/:id/folder-fix needs state ready. It refuses busy while a sync, a folder-move pass, or ad removal runs. In one transaction it sets dest_folder, rebases recordings.file_path and library_items.file_path, and renames the folder; a failure renames it back. POST .../folder-fix/keep sets kept_folder to dest_folder.

Merge into another show (POST /api/library/recordings/show) sets recordings.show_title_override on each row. The override sets the show key of the row for the Library, the kind rules, and the folder moves.

Ad removal ​

src/commercials.js runs Comskip (comskip) to find commercial breaks in an imported recording. In cut mode it removes the breaks with ffmpeg and ffprobe. The three binaries are in the Docker image. src/ad-original-routes.js holds the manual scan and restore routes.

Ad gates ​

The sync calls processRecordingAds only when all of these hold:

  • The setting ad_removal_enabled is 'true' (Settings → RECORDING → Ad removal).
  • shows.ad_removal is detect or cut (values off, detect, cut, default off; AD_REMOVAL_MODES in src/server.js).
  • The recording has a series folder; one-offs and films never reach ad removal.
  • The import classified done.

A failure in ad removal never fails the import or the sync. summary.ads counts scanned, detected, cut, failed, and adSeconds. The manual scan route ignores ad_removal_enabled and uses detect when the show mode is off.

Ad columns ​

Column on recordingsMeaning
ad_statusnull (not scanned), scanning, detected (breaks found, file unchanged, .edl written), no_breaks, cut, detect_failed, cut_failed
ad_breaks_jsonJSON array of { start, end } in seconds
ad_processed_atTime of the last scan result
ad_cut_atTime of the last cut
ad_backup_saved_atTime the .orig backup was made; null with no backup
ad_backup_uncuttrue when the backup is the recording as imported

Ad scan ​

scanRecordingAds sets ad_status = 'scanning' and makes the workdir <recording folder>/.freetvarr-adcut/<file name>. detectBreaks then runs:

  1. Copy the ini file to the workdir and append output_edl=1. The ini file is <config folder>/comskip.ini when it exists, else the bundled assets/comskip.ini. GET /api/settings reports comskip_ini_override.
  2. Read the duration with ffprobe.
  3. Run nice -n 10 comskip --ini=<workdir>/comskip.ini --output=<workdir> <file>.
  4. Parse the EDL file (parseEdl): rows with action 0 or 3 and end > start.

The scan timeout is clamp(round(duration) × 1500 ms, 60 min, 6 h) (COMSKIP_TIMEOUT_PER_SECOND_MS, MIN_COMSKIP_TIMEOUT_MS, MAX_COMSKIP_TIMEOUT_MS). The ffmpeg timeout is 30 min per call; the ffprobe timeout is 60 s.

In detect mode, syncSkipMarkers writes <video name>.edl beside the video, one tab-separated row per break with action 3 (the commercial break action of the Kodi EDL format). A result of cut or no_breaks deletes the file.

Ad cut ​

cutBreaks runs only in cut mode, after a scan finds breaks.

  1. computeKeepSegments clamps, sorts, and merges the breaks, and returns the gaps between them. An empty keep list fails with breaks cover the entire recording.
  2. For each keep segment, ffmpeg -ss <start> -to <end> -i <source> -map 0:v -map 0:a -map 0:s? -c copy -avoid_negative_ts make_zero writes seg-<i>.ts.
  3. ffmpeg -f concat -safe 0 -i list.txt -map 0 -c copy writes out.ts.
  4. verifyCut fails when out.ts is empty, or its duration differs from the summed keep length by more than max(5, 2 × boundaries) seconds (boundaries is twice the break count).
  5. swapInCut renames the file to <file>.orig, then renames out.ts to the file path. If the second rename fails, it renames the .orig back.
  6. The row gets size, ad_cut_at, and the backup columns. A saved playback_position_s moves back by the break seconds before it (cutTimeOf); a cut from the .orig first maps it to the original time through the breaks of the last cut (originalTimeOf). Putting the .orig back maps it to the original time.

The workdir is removed on every exit path. A cut that starts when a .orig exists runs on the .orig and leaves it in place. A failure at any step leaves the original file, logs [ads] <file>: <message>, and stores cut_failed or detect_failed.

Ad recovery ​

At startup, recoverInterruptedCuts renames <file>.orig back when the file is missing and ad_status is scanning or cut_failed, then clears the cut columns (restorePatchOf). Otherwise it reconciles the backup columns with the disk: a .orig the row does not track is adopted, and a tracked one that is gone is forgotten only while the episode file exists. resetInterruptedScans then sets every ad_status = 'scanning' to null.

Original backups ​

A .orig backup stays for ad_original_retention_days days after ad_backup_saved_at (default 7). pruneCutOriginals runs at the end of every sync: it deletes expired .orig files and clears the backup columns. It skips rows with a scan or restore in flight. GET /api/recordings and library rows carry ad_backup_kept_until.

RouteSuccessMain refusals
POST /api/recordings/:recording_id/ad-scan202 with { started: true, mode }; the scan runs in the background404 unknown row; 409 not imported, no file, file gone, or a scan already runs
POST /api/recordings/:recording_id/restore-original200 with { ok: true, uncut, size, plex }The same, plus 409 outside the library folders, busy, or .orig gone

restoreOriginal renames the .orig over the file, deletes the .edl file, and clears the ad columns. After a restore, or a manual scan that changes the file, the route refreshes the Plex section of the file's library kind.

scansInFlight is a module-level Set of recording ids. A second scan, cut, or restore for an id in the set returns busy; different recordings run at the same time. isAdJobRunning(id) and adScansRunning() read the set for the folder rename, the folder moves, and the stream benchmark.

processRecordingAds runs as an ads job titled Ad removal · <title>, or joins the running import job. For a cut folder, Remove after import queues the TVHeadend remove only when the result is cut or no_breaks (shouldQueueAutoDelete).

Removal from TVHeadend ​

removeRecordings({ recordingIds }) in src/tvheadend.js removes finished recordings. It reads every page of dvr/entry/grid_finished. An id not in that list goes to unknown. Each known id is removed on its own: a failed id goes to failed and the next id still runs. When no id is removed, it throws the first failure, or not-found when every id was unknown. For each known id, removeKeepingHistory makes these calls in order:

  1. idnode/delete on each upcoming entry whose parent is this recording.
  2. idnode/save with retention: 2147483647 (RETAIN_FOREVER).
  3. dvr/entry/prevrec/set, so duplicate detection keeps the episode as recorded.
  4. dvr/entry/remove, which deletes the file and keeps a removed entry.

POST /api/recordings/:recording_id/delete-from-tvh (src/recording-tvh-routes.js) answers 409 unless the row is done and not yet marked removed. A not-found from TVHeadend counts as removed. The Import route (POST /api/recordings/:recording_id/library with include) answers 409 for a row with deleted_from_tvh_at.

The user guide covers the switches (Remove from TVHeadend).

Remove after import ​

An item goes on the removal list of a sync when it imported done in this sync, its series folder has delete_after_import, and shouldQueueAutoDelete passes. With ad_removal_enabled off, a cut folder keeps the TVHeadend copy. runAutoDelete skips the removal when the setting delete_after_plex_refresh_only is on (the default) and the TV section refresh did not return triggered, unless Plex is not set up. It sets deleted_from_tvh_at on each removed row.

A recording that has a playback session (usePlaybackCheck, wired to the playback sessions in src/server.js) is not removed. Each row that is skipped (the Plex guard or a playback session) or that TVHeadend refused gets tvh_remove_pending_at (migration 0042). Each later sync that is not limited to one show adds the rows with tvh_remove_pending_at that are done, still in the finished list, and whose folder still has delete_after_import (in cut mode only with a stored ad_status of cut or no_breaks), and refreshes the Plex TV section before it removes them. A removal clears the marker. Rows imported before the switch was on never get the marker, so turning the switch on removes no older episodes.

Stop a recording ​

STOP_RECORDING_KEEP_MIN_MS (src/web/stop-recording.js) is 5 min. recordedMsOf counts from the later of start_real and the entry's create time. stopRecordingEntry sends dvr/entry/stop. Under 5 min of recording, it also removes the entry: steps 2–4 of removeRecordings for a series recording, dvr/entry/remove for a single entry. Otherwise the next sync imports the stopped entry.

Cancel series sends POST /api/epg/cancel-series with series_link_id or series_link_ids. cancelSeriesRules calls disableSeriesTag for each id. With stop_recording_now: true, disableSeriesTag lists the rule's recording entries, deletes the autorec, then stops each listed entry; a stop that fails goes to stopFailed instead of failing the cancel. An id with no autorec any more (not-found) counts as cancelled, so a retry works. With title_match_id, the route also deletes that shows row.

Under 5 min, the stop dialog of a series episode says that its repeats do not record, because dvr/entry/prevrec/set keeps the episode as recorded.

Series rule title change ​

runAutorecAnchorOnce (src/autorec-anchor.js) changes the title of each autorec that Freetvarr made before the current whole-title form to that form. It runs at startup, after each sync, and after a time zone save in POST /api/settings (anchorSeriesRulesQuietly), until the setting autorec_titles_anchored_for_country holds the install country. A time zone in another country makes the run happen again. A call for the country of the run in progress gets that run; a call for another country starts one more run after it. With an unknown country, the run reads nothing, changes nothing, and stores no setting; new rules still get the suffix of the unknown country. On an au or nz install with no autorec_titles_anchored_for_country and the 2.10.0 setting autorec_titles_reanchored_at, the run stores the country and changes nothing, because the 2.10.0 suffix is already current there. 2.7.0 to 2.9.0 used the setting autorec_titles_anchored_at.

  1. Read dvr/autorec/grid and dvr/entry/grid_upcoming.
  2. anchorPlanOf picks the rules with comment freetvarr, fulltext and mergetext off, a title that does not end with the suffix of the install country (isCurrentAnchor), and a title that is name itself (a rule from before titles were escaped) or reads back as name through literalTitleOf, which includes the 2.9.0 suffix. The new title is the escaped and anchored name, with the title variants the old title had and those saved in series_title_variants. User-made and hand-edited rules are left alone, with a log line each.
  3. For each rule, log the old and new title, and log each of its timers whose disp_title stops matching ([rules] timer ... stops matching).
  4. Send idnode/save with uuid and title only. TVHeadend then cancels every scheduled timer of the rule and makes the ones that still match again (dvr_autorec_changed), so a per-episode padding change goes back to the rule's padding. No rule is deleted. After the saves, one more dvr/autorec/grid read checks each title; a title TVHeadend did not apply counts as failed.
  5. A failed save logs the TVHeadend error and keeps the old title. The failed rules go into the setting autorec_anchor_failed, the tvh.rules Health check warns and names them, and the flag stays unset so the next run tries them again. An unreachable TVHeadend changes nothing.

Title variants ​

A title variant is a second guide title that a series rule records as the same series, such as Big Brother Australia for Big Brother.

The own words of a country (OWN_TITLE_WORDS in src/title-countries.js) are the words that name it in a guide title. Another known country has its English name (Intl.DisplayNames) and its two-letter code, such as Germany and DE. An unknown country has none. isVariantTitle compares a country code (two or three capital letters, such as US or DE) with the original case of the title, so Fool Us is not a variant of Fool. It compares a country name, Encore, and a year in any case.

CountryOwn words
au and nzAustralia, AU, AUS, NZ, New Zealand, Aotearoa
ukUK, Britain
usUS, USA, America
caCanada
ieIreland
  • Offer: getSeries reads the cached guide (listGuideAirings) and indexes the titles of airings that have not ended (guideTitleIndexOf). For each series, variantTitlesOf lists each title for which isVariantTitle is true: the series title plus a space and one variant word, or the reverse. The series title part is compared in any case. The variant words (variantWordOf) are the own words of the install country (countryTitleWordsOf), Encore, and a year 19xx–20xx. The own words are in the table above. A merged guide variant candidate (title_aliases kind variant-candidate, a primary title the secondary never lists) is also offered when titlesAgree matches it to the series title (isCandidateVariant). A title the rule already matches (isSameShowTitle) is left out. upcoming counts the airings on the channels of the rule's autorecs, or on all channels when one autorec has no channel. Each entry is { title, upcoming, enabled }, as titleVariants on the series. titleVariantsEditable is false when an autorec is not titleEditable (comment freetvarr, no fulltext or mergetext, and a title that anchoredTitlesOf reads).
  • On and off: POST /api/epg/series-title-variant (src/series-variant-routes.js) with series_link_ids, variant, and enabled calls setSeriesTitleVariant. It reads the series name from the matched autorecs (listSeriesRules), never from the request. The current list is the saved variants plus the rule's titleVariants. A variant that is not in that list, fails isVariantTitle, and is not a candidate variant is refused with 400 and code not-a-variant. Otherwise it adds or removes the variant (case-insensitive), sends the new title to every autorec of the series (setSeriesTitleVariants, idnode/save with uuid and title), then saves the list to series_title_variants (series_key is the show key of the series name). A failed TVHeadend save saves nothing. TVHeadend refuses with title-not-editable when an autorec is not titleEditable.
  • Read back: listAutorecs gives name and seriesLinkId from the first title only, so the series key does not change, and gives the others as titleVariants. enabled is true for a title in series_title_variants or in the rule. recordSeries adds the saved variants to a new rule.
  • Import: see Show matching.

Library delete ​

src/library-delete-routes.js mounts POST /api/library/delete/preview and POST /api/library/delete, both with epgLimiter and CSRF. The body holds recording_ids (up to 1000), or show_key with scope (watched or all); optional versions (both, recording, or other per id); and, for the delete, expected_count and optional remove_series.

The delete answers 409 while a sync runs, while a target is importing or scanning, when Sonarr or Radarr cannot be reached to check file managers, or when the planned count differs from expected_count. It then runs in this order:

  1. runForeign (src/foreign-delete.js) deletes the other copies (Plex items that are not the recording). A copy with no manager is deleted under the root rules; a managed copy goes through its app (Sonarr and Radarr).
  2. runDeletion (src/library-delete.js) handles each recording. It refuses a file that TVHeadend still writes. It keeps a file that another live row holds (kept_shared) or a library_replacement file.
  3. It deletes the library file, its .edl, and its .orig, then up to 2 empty parent folders inside the root.
  4. It removes the TVHeadend copy with removeRecordings, unless deleted_from_tvh_at is set.

Each target must be an absolute path inside the TV, one-off, or movies folder, its parent's realpath must stay in the root's realpath, and lstat must show a regular file. deletionPatch sets library_deleted_at, library_choice exclude, and, after a TVHeadend removal, deleted_from_tvh_at and purged_at. When the TVHeadend removal fails, it sets library_state not_in_library instead, so the show leaves Home and the Library at once. Import again clears library_deleted_at and library_state. bytesFreed counts a file once per inode, only when the request removed all of its hardlinks. Each kind with a change refreshes its Plex section. The status is 200, or 207 when any result is not ok.

sweepLibraryStates (src/library-files.js) runs in each sync. For each done or partial row with a missing file, library_state becomes replaced (another video with the same SxxEyy in the same or a sibling Season N folder, stored in library_replacement) or not_in_library. POST /api/recordings/:recording_id/library with choice: 'include' resets a not_in_library row to pending and starts a manual:import sync.

POST /api/reset needs the body { "confirm": "reset" } (else 400) and uses syncLimiter. It returns 409 while a sync runs. Otherwise resetFreetvarrData (src/reset.js) deletes all rows of recordings, syncs, and shows, and every setting except tv_login_username, tv_login_password, tv_login_auth_code, tvh_open_entry_backup, and allowed_hosts. The TV login and the closed open-access entry stay in TVHeadend; the allowed hostnames stay so the reset page still loads through a reverse proxy name. The sign-in file login is outside the database, so the password stays (Sign-in). The scheduler then restarts.

Live TV ​

Freetvarr plays live TV in the browser as HLS that its own ffmpeg process writes. Each session reads one TVHeadend channel stream as MPEG-TS and pipes it into ffmpeg. The server code is src/live-tv.js, src/live-encoder.js, and the /api/live routes in src/server.js. The guide page is Live TV.

Live start ​

POST /api/live takes channel_id, an optional picture_rank, and an optional client_token, and calls startLiveChannel (liveLimiter, CSRF):

  1. releaseHeld ends each held session on another channel that this client_token started, with the reason replaced. It skips a session that any other viewer ever joined, and a session that a viewer still attends (for example in Picture in Picture). The client keeps the token in localStorage (freetvarr.deviceToken), so it stays the same when a Home Screen app opens again.
  2. When a session on the channel exists (forChannel), the viewer joins it and nothing else runs.
  3. preflightChannel checks the tuners. A refusal throws a LiveTvError with status 409.
  4. planForChannel reads the first service of the channel from service/streams and the default languages from config/load, then calls pickStreams.
  5. sessions.start applies the Stream limit, spawns ffmpeg, and opens the TVHeadend stream.
CodeStatusCause
unknown-channel404The channel id is not in the guide channel list
off-air409Every service of the channel is disabled
no-tuner409No tuner is on the channel's multiplex and no tuner is idle; the body lists holders
no-service, no-video409The channel has no mapped service, or the service has no video
stream-limit409The live and playback sessions fill the stream limit

Live stream plan ​

detectLiveEncoder (src/live-encoder.js) runs once at startup. LIVE_TV_TRANSCODE selects the encoder: auto (default) or hardware give VAAPI when the device test passes, else software; software gives libx264; copy maps H.264 video with -c:v copy. The VAAPI test opens LIVE_TV_VAAPI_DEVICE (default /dev/dri/renderD128) and encodes two test frames, with a 20 s timeout.

pickStreams returns the streams, mapped by PID, and a videoMode:

VideoEncoderPlan
H.264VAAPIvaapi, 720-line cap, deinterlace
H.264Softwaretranscode, 540-line cap, deinterlace
H.264Copycopy
HEVC, MPEG-2, or VC-1 above SDVAAPIvaapi with hardware decode, 1080-line cap above 1080 lines, else 720
Other video, or no VAAPISoftwaretranscode; SD gets a 576-line cap
  • libx264 uses yadif, -preset veryfast, -tune zerolatency, -crf 23, and -g 50. VAAPI uses deinterlace_vaapi, scale_vaapi, and h264_vaapi -qp 24.
  • pickAudio takes the first normal audio track in a TVHeadend default language, else the first normal track. Audio is always stereo AAC at 128k.
  • A service with TELETEXT and TEXTSUB streams gets captions when ffmpeg has the libzvbi_teletextdec decoder (detectCaptionDecoder). The page is the TEXTSUB PID minus 0x2000; outside 100–899 it is 801.

Live HLS output ​

ffmpegArgsFor reads -f mpegts -i pipe:0 with a short probe and writes HLS into LIVE_ROOT/<session>, where LIVE_ROOT is os.tmpdir()/freetvarr-live:

Option or fileValue
-hls_time, -hls_init_time2, 1
-hls_list_sizeThe LIVE_TV_BUFFER_MINUTES buffer in 2 s segments, at least 6
-hls_flagsdelete_segments+independent_segments+omit_endlist+temp_file+program_date_time
index.m3u8, live.m3u8, seg<N>.tsMaster playlist, media playlist, video segments
live_vtt.m3u8, live<N>.vttCaption playlist and segments (WebVTT from DVB teletext)

GET /api/live/:session/:file serves these names only (LIVE_FILE_PATTERN), with Cache-Control: no-store. A playlist request waits up to 15 s for the session to go live. The server rewrites files before it sends them: caption labels and a peak BANDWIDTH in index.m3u8 (servedMasterPlaylist), the first segment out of the copy-mode playlists, program date-times into live_vtt.m3u8, and two-row roll-up cues into each live<N>.vtt (servedCaptionSegment).

When ffmpeg exits while the session is still tuning, the session restarts it once per fallback: first with the full probe (for missing codec parameters), then without teletext (for teletext errors). A stop during a restart ends it before the new ffmpeg starts.

TVHeadend stream request ​

openChannelStream in src/tvheadend.js sends GET /stream/channel/<id>?profile=pass&weight=<N> with User-Agent: Freetvarr-live/<session id>. The request goes through sendAuthenticated, has no timeout, and uses the session's AbortSignal. The credentials never appear in ffmpeg arguments. A 503 ends the session with no-tuner, a reset before data with no-source, and any other refusal with upstream.

Live session registry ​

createLiveSessions keeps one session per channel, shared by every viewer. A session has a 32-hex-character id (16 random bytes), the plan, the weight, a viewer count, lastSeenAt, lastByteAt, and heldUntil. Playlist, segment, and preflight requests refresh lastSeenAt.

  • DELETE /api/live/:session takes one viewer off; the last viewer ends the session.
  • POST /api/live/:session/hold keeps the session for LIVE_TV_BUFFER_MINUTES; with a buffer of 0 it does nothing, and the 20 s idle rule ends a session that nobody fetches.
  • POST /api/live/:session/unhold ends the hold, so the idle rule applies again. A preflight or a file request does not end the hold.
  • POST /api/live/:session/attention takes { attending, viewer } for Watch tracking. viewer is a token for each page load; a shared session is attended while any viewer attends.

A session that is ending stays in the registry until its teardown is done, but it no longer counts against the Stream limit.

The reaper runs every 5 s (LIVE_REAPER_MS). A session that is not held and has no request for 20 s ends with idle. No bytes for 10 s, or the end of the TVHeadend response, is a stall. A stall reads status/subscriptions: a newer DVR subscription gives preempted with the recording title, the session's own subscription gives no-input, and neither gives gone. Teardown aborts the request, sends SIGTERM to ffmpeg (then SIGKILL after 3 s), and deletes the session folder. Startup deletes LIVE_ROOT.

Live preflight ​

GET /api/live/preflight?channel=<id> returns the tuner verdict and the session view. tunerVerdict gives shared (a tuner is on the channel's multiplex), idle (a tuner is free), or no-tuner. findConflict checks each recording that starts in the next 60 minutes; more distinct multiplexes than tuners at that start give a conflict. The client polls the preflight every 1 s while tuning and every 10 s while playing.

Live player ​

src/web/components/live-player.js is one Vue component, mounted once in src/web/app.js and teleported to <body>, so playback continues across pages, in full screen, and in the Miniplayer. The session logic is in src/web/shared/live-session.js.

  • The client uses native HLS only when MediaSource is absent and the browser can play application/vnd.apple.mpegurl. Otherwise it imports hls.js from /vendor/hls.mjs when a stream starts.
  • The hls.js config is liveSyncDuration: 4, liveMaxLatencyDuration: Infinity, and backBufferLength: 30. Video starts when 2 s are buffered, or 4 s after metadata loads.
  • The player draws its own controls. A scrubber appears when the buffer allows at least 4 s of rewind. Double taps on the left or right third skip 10 s (src/web/double-tap.js).
  • A hidden page sends POST .../hold with keepalive, and a page that is visible again sends POST .../unhold. A pagehide that does not persist sends DELETE.
  • A fatal hls.js network error detaches the video and lets the preflight poll attach it again while the session lives, at most 2 times in a row (liveErrorActionOf). The count resets when the video starts.
  • withPeakBandwidth (src/live-tv.js) raises the BANDWIDTH of each #EXT-X-STREAM-INF line to a floor for the picture height: 5000000 up to 576 lines, 10000000 up to 720, and 16000000 for 1080 or an unknown height. A higher declared figure stays. ffmpeg writes an audio-only figure for copied video.
  • When the preflight poll finds that the server no longer knows the session, for example after a server restart, the player and each Multiview picture start the channel again once (pollOutcomeOf, LIVE_MAX_RETUNES 1, src/web/live-start.js). A second miss ends playback with Stopped: the stream is no longer available.

AirPlay ​

src/web/airplay-target.js and useAirplayTarget in src/web/shared/player-shared.js serve the live and recording players. The <video> has x-webkit-airplay="allow".

  • listenForAirplay sets airplay from webkitplaybacktargetavailabilitychanged and playingOnTv from webkitCurrentPlaybackTargetIsWireless on webkitcurrentplaybacktargetiswirelesschanged.
  • The AirPlay action (airplayActionOf, src/web/player-top-actions.js) calls webkitShowPlaybackTargetPicker.
  • airplayReachHintOf adds a hint to the Playing on your TV screen when the page address is not a home address. A ts.net name or a 100.64.0.0/10 address gets Use your home address, or add the TV to Tailscale. Any other name with a dot, outside the local suffixes, gets Use your home address.

Stream limit ​

src/live-streams.js sets how many live and playback sessions run at once. Both session registries check the sum of their sessions against liveStreams.current(). The guide page is Live streams at once.

liveStreams.measure() runs src/live-benchmark.js unless a session or an ad scan runs. The benchmark encodes an 8 s 1080i H.264 sample with the live plan for 1, 2, 3, then 4 parallel nice -n 10 ffmpeg processes. A round passes when every process runs at 1.2× real time or faster; the estimate is the last passing round. The result is stored in the setting live_benchmark. The copy encoder skips the run and stores 4.

src/live-measure-schedule.js starts the measurement from the app.listen callback, after the startup work begins:

  1. Wait 1 min, then read the idle signal every 30 s.
  2. Measure when the signal stays idle for 3 min. After 30 min, measure anyway (longer than a merged guide build, about 13 min on a DS220+), even during a recording or a heavy job. A live session, playback session, or ad scan still blocks the run.
  3. Call measure({ runs: 2 }). It runs the benchmark, pauses 20 s, and runs it again. It keeps the result with the higher estimate, then the higher speed. Before the second run, stillIdle checks sessions, ad scans, recordings, and heavy jobs again, but not the processor (the first run raised the load). A second run that fails or meets any of these keeps the first result. The copy encoder runs once.
  4. Every 10 min, measure again when the measurement is due and the idle signal is idle. It is due when none ran this start, 24 h after a measurement, and 1 h after a failed run.
  5. After each measurement, including Measure again, reset the 24 h timer and refresh the Health report (liveStreams.onMeasured).

The idle signal (liveMeasureBusyReason) is idle when all of these hold:

  • No live session, playback session, or ad scan runs.
  • No heavy job runs in activity.snapshot().running (HEAVY_JOB_KINDS: sync, import, ad removal, guide load, guide pictures, merged guide, For you rebuild, artwork warm-up, picture focus, library folders, and cache prune).
  • getRecordingNow() lists no active or finishing recording. A failed TVHeadend read counts as idle.
  • The Freetvarr process uses less than 15% of one processor over the last minute (process.cpuUsage() against performance.now(), createProcessCpuMeter). A clock that steps back reads as busy.
  • The one-minute os.loadavg() divided by the processor count is below 1.0. Other containers keep this near 0.55 on an idle DS220+, so it blocks only a saturated machine.

While a measurement runs, describe() returns measuring: 'running'. When no saved result for the current encoder exists, it returns measuring: 'waiting' until the first measurement on this start settles. A saved result shows at once after a restart. The give-up warning and a skipped due check log the busy reason. The live.streams Health check then passes with a measuring detail instead of the saved result. The stream limit still uses the saved result. Measure again runs one benchmark at once, with no idle wait.

SourceEffect
LIVE_TV_MAX_SESSIONSAn integer 1 or more; replaces the default and caps the user choice
Benchmark estimateDefault, capped at the tuner count and at 4
No benchmarkDefault 2 for VAAPI, 1 for software
Setting max_live_streamsUser choice 1–4 up to the tuner count, or empty for the default

GET and PUT /api/live-streams read and set the limit. POST /api/live/benchmark (Measure again) returns 409 with code: 'busy' while a stream plays or an ad scan runs.

Multiview ​

Multiview plays up to three companion live sessions beside the main player's session. Each companion is an ordinary live session with its own <video>, hls.js instance, and preflight. The guide page is Multiview.

  • GET /api/live/tuner-status (src/tuner-status.js) returns the tuners, their holders, the stream capacity, and a cost per channel: free-tuner, no-extra-tuner (shares a tuner with sharesWith), or unavailable. The client polls it every 5 s while Multiview is open.
  • src/web/multi-view.js holds the rules. pictureLimitOf caps a phone layout at 2 pictures and other screens at 4, never above the stream limit. Layouts are Side by side, Big and small, and Grid. One picture at most has sound.
  • A companion sends picture_rank 1, 2, or 3. liveStreamWeightOf gives the subscription weight 50 - 10 × rank, so the main player has 50 and the companions 40, 30, and 20. TVHeadend takes the lowest weight first when a recording needs a tuner.

Recording playback ​

The player plays a recording, or a Plex library item, as HLS from a per-file ffmpeg session. The server code is src/playback.js and its routes in src/server.js; the client code is src/web/shared/playback-session.js. Playback sessions count against the Stream limit. The guide page is Playback.

RoutePurpose
POST /api/recordings/:id/playStart a session; body offset, replace, player, part_id, client_token (playLimiter)
GET /api/play/:session/:fileServe index.m3u8, play.m3u8, play_vtt.m3u8, seg<N>.ts, and play<N>.vtt
POST /api/play/:session/heartbeatRefresh the session; 404 with code: 'gone' after it ends
POST /api/play/:session/attentionSet attending for watch tracking
DELETE /api/play/:sessionStop the session
POST /api/recordings/:id/positionSave the position (0–86400 seconds)

Playback start ​

  1. Load the recordings row, or the Plex item row for a Plex item id.
  2. playbackCandidates lists the library file_path (status done or partial), then the TVHeadend file through localPathFor. resolvePlaybackFile keeps the first whose real path is inside a media, one-off, movies, or recordings folder; none gives 410 with code: 'missing'.
  3. Probe the file with ffprobe (30 s timeout, cached by path, size, and time).
  4. With no offset, resumeStartFor resumes from playback_position_s unless it is within 30 s of the end (RESUME_END_MARGIN_S).
  5. planForFile maps the probe onto pickStreams, so the plan rules match Live stream plan.

playbackArgsFor puts -ss <offset> before -i <file>, maps streams by index, and writes 6 s segments (PLAY_SEGMENT_SECONDS) as an event playlist into LIVE_ROOT/play/<session>. The served playlist gains #EXT-X-ENDLIST once ffmpeg finishes: it exits with code 0 and no signal, or the offset plus the produced seconds reaches 30 s before the file length. Any other exit after the first segment ends the session with ffmpeg, so the client heartbeat gets 404 and the client starts again at its position. Before the first segment, a failed ffmpeg restarts with the full probe, then without teletext, then with the software plan for vaapi.

The client sends a heartbeat every 15 s and saves the position on each heartbeat while it plays. The reaper ends a session after 60 s with no request. seekPlan (src/web/playback.js) seeks inside the produced part, or starts a new session at the target offset with replace set.

Playback positions ​

The position route writes playback_position_s, played_at, and watched_at. watched_at is set when the position is within 30 s of the shorter of duration_s and the file length of the active playback session (playedDurationOf), so a file with cut ads can still count as watched. At the end of a recording, the client posts the offset plus the played time, not the file length. For a Plex item it calls saveItemPosition. A DVR entry that is still recording has no row yet; rememberInProgressPosition keeps its position in the setting in_progress_positions for 3 days, and applyInProgressPositions copies it onto the new row after each sync.

Watch tracking ​

src/watch-tracker.js turns sessions into user_events rows through the onStart, onAttention, and onEnd hooks of both session registries. src/web/shared/attention-session.js reports attention every 2 s: a picture is attended when the page is visible (or in Picture-in-Picture) and the video plays.

Sessionwatch_startwatch_end
LiveAt session start, with the programme on airOne row per programme that overlaps an attended span of 60 s or more
PlaybackAt session start, with the start offsetOne row per viewing, 15 s after the last session ends, with the attended seconds

From the start ​

From the start plays a programme that TVHeadend is still recording. The server code is src/in-progress-playback.js; the client calls watchFromStart and plays in the live player. The guide page is Start over.

POST /api/play/in-progress takes dvrUuid, player, replace, and client_token. Like the recording play route, it first calls releaseHeld for the client_token (Live start):

  1. Find the entry in listActiveRecordings; none gives 404 with code: 'not-recording'.
  2. growingSourceFor uses the local file when localPathFor maps the path, else GET /dvrfile/<uuid> with a Range header.
  3. Probe the source. An HTTP source copies its first 2 MB to a temporary head.ts for ffprobe.
  4. Start a playback session with a feed: ffmpeg reads pipe:0 and writes 2 s segments.

The client saves the position with keepalive when the page hides. When a heartbeat gets 404, the client starts From the start again and seeks to the played time, at most 2 times in a row (fromStartGoneAction). Try again in the player starts From the start again at the saved position (retryActionOf).

feedGrowing copies new bytes into ffmpeg every 1 s (IN_PROGRESS_POLL_MS). When a read copies nothing, it checks whether the entry still records, at most every 5 s (RECORDING_CHECK_MS). After two empty reads with the entry no longer recording, the feed ends the input. The session view adds growing, recordingStartedAt, scheduledEndAt, and liveEdgeSeconds.

Pictures and programme info ​

Pictures and programme info come from the guide, Freeview (Australia only), Plex, TVmaze, Wikidata, Wikipedia, and TMDB. Lookups for pictures, scores, reviews, and cast share one outbound client, one lookup gate, and one daily prune.

Picture routes ​

RouteParametersUsed by
GET /api/epg/image/:eventIdwGuide cells, Live TV thumbnails, the programme sheet
GET /api/epg/show-imagetitle, shape (poster or landscape), kind (movie, series, or one-off), w, cFor you, show pages, Change picture
GET /api/epg/logo/:channelIdw (96 or 192)Channel logos

w is one of 192, 384, 768, 1280, or 1920; the default is 768. A miss answers 404 with no-store and the header X-Art-State: pending while a lookup runs, final when the chain ended with no picture. The page shows its own fallback while it has no picture: the title on a gradient (.ui-art-fallback and .ui-art-title in src/web/styles/base.css). Live picture updates swap in the picture when the server finds it. TitleArt also asks again after 4 s, 12 s, and 30 s with a HEAD request, whether or not the art stream is connected, and stops at the first final. It keeps the URLs that answered final for the page session, so a list shown again starts on the fallback without a request.

AnswerStatusCache-Control
A found picture200public, max-age=86400
A lookup still running404no-store; X-Art-State: pending
No picture404no-store; X-Art-State: final

showImageUrlOf in src/web/artwork-stamps.js builds every show picture URL, on the server (src/library.js, src/art-pool.js, src/for-you.js) and in the client. artKindHintOf turns a library kind into the kind hint.

The client adds the current stamp of the title as c= to every picture URL when the page renders (stampUrl in src/web/artwork-stamps.js, stampedShowImage in src/web/shared/artwork-stamps.js): the background or poster stamp on a show picture URL, and the programme stamp on a guide airing URL (/api/epg/image/:eventId) or a recording URL (/api/recordings/:recording_id/image). A show picture URL with no stamp takes c=series-v2 (SERIES_MATCH_VERSION); an airing or recording URL with no stamp has no c=. The routes ignore c. A new stamp gives a new URL, so the browser never shows a picture from its 24 h cache after the picture changed. See Live picture updates.

Picture resolver ​

createArtResolver in src/art-resolver.js picks one picture per title key, kind, and shape. findShowThumbnail, findShowPoster, and findProgrammeThumbnail in src/epg.js call resolve, then serve the result. So a list and a show page get the same picture for the same title and kind.

The server sets the kind (canonicalKindFor in src/epg.js). The kind in the URL is a hint only. With a title kind row, storedKindOf gives the row's kind, or the hint when requestKindOf lets it count. With no row yet, canonicalKindOf decides from the library kinds, the override, and the guide kind (guideKindsOf) by the same rules, else series. isGuessedFilmKind reads the library kinds and the override from the row.

Each kind runs its own chain of steps (chainOf). A guide airing runs FREEVIEW_FIRST_GUIDE_CHAIN when findProgrammeThumbnail passes freeviewFirst (the Freeview step is on, so the install is in Australia), else GUIDE_ONLY_CHAIN. The steps are functions that src/epg.js passes in; each gives picture origins (plex:<path>, recording:<id>, upload:<id>, or a URL).

RequestChain
Filmchoice, Plex, recording, guide, online, derived shape, frame, derived shape, none
Serieschoice, Plex, recording, guide, online, derived shape, frame, derived shape, none
One-offchoice, Plex, recording, guide, frame, online, derived shape, none
Episode (recordingId)recording picture, the title chain, frame, none
Episode, frame firstrecording picture, frame, the title chain, none
Guide airing (eventId)the airing's image, then its saved copy; the title copy; other airings of the title; Freeview, then its saved copy; the title chain; none
Guide airing, Australiathe Freeview episode picture of the airing, then its Freeview show picture (each as saved copy, then address); the Freeview title copy; the airing's image, then its saved copy; the title copy; other airings of the title; the title chain; none
Recording savethe Freeview episode picture; the airing's image; the Freeview show picture; the Freeview title copy; the title copy; none (RECORDING_SAVE_CHAIN)
  • A picture fits when it has the asked shape (poster: taller than wide; landscape: at least 1.3:1) and is wide enough (MIN_WIDTHS): 300 px for a poster or a Plex picture, 640 px for any other landscape picture, the width the home hero check needs. The first picture that fits ends the chain, so a Plex or recording picture that fits makes no web request.
  • A picture that loads but does not fit is kept. When no later step finds a picture that fits, the derived step uses it: as it is when it has the asked shape, else on a blurred canvas (portraitPadOf in src/show-poster.js for 2:3 posters, landscapeOf in src/image-thumbnails.js for 16:9).
  • The frame step of a title takes up to 6 of the newest files of the title (frameFilesFor in src/library-titles.js): recordings that are imported (done or partial) and not purged, and Plex library items of the same kind, with a file_path. framePreferenceOrderOf in src/frame-grabs.js tries the files with ad data first, newest first, then files from an ad-free channel, then files that wait for an ad scan, then files with no ad data, which give no frame. The frame step of an episode takes the file of the recording. A frame that loads but does not fit (a poster) goes to the derived step after it, so a landscape frame can give a padded poster. See Frame grabs.
  • The setting episode_picture_order (off, series, the default, or frame) sets the use of frames (Settings → Film and TV info → STILLS FROM RECORDINGS → Use stills: Off, When nothing else, Before series picture). off removes the frame step from the episode chain, and the frame step of every title answers no picture. off also adds stills-off to the settings key of the resolution fingerprint, so every saved title resolution runs again. A change between off and the other values calls publishStillsChange in src/epg.js, which publishes an art event for each title with a frame resolution and each recording with no saved picture. Frame files stay until the daily prune. The title step of an episode resolves the title without the recordingId, so it uses the frame of the newest file, as the title does.
  • The online step for a one-off is the same as for a series; the TVmaze and online lookup match rules decide.
  • A film kind that comes from the guide only (isGuessedFilmKind: no Plex film of the title and no movie override) that finds no film online asks again as a series: TVmaze, then the online lookup without the film kind, which uses TMDB /search/multi (onlineArtworkOf). It asks again only after a settled film miss (a saved miss, settled: true); a refused lookup or a recent failure answers pending, so no series picture is saved for a real film. The same match rules decide. For example, a one-off 3 h contest with no episode details is a guessed film.
  • A picture that fails to load with an error (a timeout, 429, or 5xx) is not a miss. createProgrammeImages waits 60 s before it asks that source again, and keeps misses (404, not an image) for 10 min. When an earlier step failed with an error, a later picture that fits is saved for 5 min only (ERROR_RETRY_MS), and a derived shape or no picture answers pending and is not saved.
  • A Plex picture is saved as plex:<path> without the token (plexOriginOf); a Plex source from another server is skipped, and remember never saves an origin that holds X-Plex-Token. Every Plex picture loads through the photo transcoder.
  • The guide step puts the saved guide pictures of the title first (titleOriginsFor, then guideSourcesOf), then the guide images, at most 4 in all. When the title copy is a Freeview copy, the newest copy from another host comes second. A new title copy changes the guide sources, so the fingerprint changes and the saved row resolves again once. Plex pictures come through the Plex photo transcoder at most 1920 px (plexResizedSourceOf), so originals over the 4 MB image limit still load.
  • The chain has 3 s (RESOLVE_BUDGET_MS); the airing and episode steps have 1.5 s (OUTER_BUDGET_MS). A step that runs past it, a Plex list still loading, or an online lookup still running makes the answer pending; nothing is saved.
  • The resolver loads every origin through the picture gate (pictureGate.load, Stand-in pictures); a guide airing loads through loadUnlessCached, which answers from the image cache without a read. A stand-in picture loads as no picture, so every step moves on to its next source. A title card (verdict weak) is kept aside: every chain uses it only when no other step, derived shape, or frame gives a picture. The title chain then answers stage weak (padded like a derived shape when the shape is wrong). An airing or episode chain takes the first title card it saw, or the title chain's weak answer, before none.
  • findTitleImage serves a chosen picture that fails to load from the chain without the choice. A saved origin that fails to resize keeps its row and answers final for that request.

art_resolutions keeps one row per <kind>|<shape>|<title key>. The fingerprint is a hash of the version (art-v3; art-v3 resolved every title again once to drop stand-in pictures), the gate rule version (GATE_RULE_VERSION in src/picture-gate.js, gate-1; a new rule version resolves every title again once), the kind, the shape, the origins from the Plex, recording, and guide steps, show_artwork_lookup, and whether a TMDB key is set. A row is used while its fingerprint matches and next_check_at is not due:

ResultNext check
A picture that fits7 d
Derived shape, title card, no picture6 h, 24 h, 3 d, then 7 d while the fingerprint is the same
A changed fingerprintAt once

This is the only retry ladder. A due row runs its stages again with retryMissesBefore set to its resolved_at (retryContextOf). The online and frame steps then skip a saved miss that is older than that time: the Wikipedia and TMDB miss (artwork_lookups), the TVmaze miss (show_artwork), and the .none mark of a frame. A miss saved after that time, the 10 min failure skips, the host gaps and the outbound circuit breaker, the Freeview backoff, and the Wikidata stop still apply. The warmer runs the due miss rows of titles in the next 7 days of the guide (tier due-titles).

Guide airings have no row. createAiringMemory in src/airing-memory.js keeps the answer of each airing (event|<eventId>) in memory, up to 20000 airings (AIRING_MEMORY_ENTRIES); the least recently used airing goes first. It keeps two kinds of answer:

  • A picture that a step before the title step found, with no step pending before it.
  • No picture from the steps before the title step, with the first title card it saw. The title step still runs on every request, so the title row, the owner choice, and the retry ladder apply as before.

An entry holds a fingerprint: a hash of airing-v1, the gate rule version, the chain, the title key, and the origins of each step up to the step that answered. A request runs those steps again (they read memory and the saved-copy index, and load no picture) and uses the entry only when the fingerprint matches and the known verdict of its picture is still ok (weak for a kept title card). So a new airing image, saved copy, Freeview match, or rule version, and a picture that became a stand-in, run the chain again. A pending or provisional answer is not kept. An answer that passed over a source that loaded no picture or failed is kept for 10 min only (AIRING_SKIP_RETRY_MS, the miss wait of createProgrammeImages), so that source is asked again. Each art event forgets the airings of its show key, and an artFeed.reset forgets all (forgetAiringsOnArtChanges). When a kept picture no longer renders, findProgrammeThumbnail forgets the airing (forgetAiring) and resolves it again in the same request.

No code deletes a row to ask again. markResolutionsDue in src/art-resolver.js sets next_check_at and miss_step to 0 and gives the rows a new random stamp, so the URL changes at once, before the title resolves again. Refresh artwork (forgetShowArtwork), a stand-in picture, a frame in an ad break, and a pruned frame use it. The daily prune deletes rows whose resolved_at is more than 90 d past.

Frame grabs ​

createFrameGrabs in src/frame-grabs.js takes a frame from a recording file with ffmpeg and saves it as artwork/frames/<id>.jpg beside the database (ARTWORK_PATH). <id> is the first 24 hex characters of a SHA-256 hash of the file path; the origin is frame:<id>.

  1. frameFor answers with the saved frame. With no frame, it puts the file in a queue and answers pending. A <id>.none mark older than retryMissesBefore (a due title row) is deleted, and the file is grabbed again. A title pass gives retryMissesBefore only to the file with the oldest mark before the cutoff (retryFileOf), so one due retry runs ffmpeg at most once, and each file gets a turn in later passes. A file with a newer <id>.none mark, no ffmpeg (ffmpeg -version fails, as on an install outside Docker), or a file that the server cannot read answers with no frame.
  2. adPlanOf sets the ad plan of a recording from ad_status, ad_breaks_json, the ad_removal of its series folder, the ad_removal_enabled setting, and imported_at:
    • clear: ad_status is cut, no_breaks, or detected with no breaks.
    • marked: ad_status is detected with breaks.
    • waiting: a scan runs (scanning, or isAdJobRunning), or no scan result yet while ad removal is on for the folder and the recording was imported less than 8 h ago. frameFor answers pending and does not grab.
    • ad-free: no ad data, the install country is au (countryForTimeZone(currentTimeZone())), and isAdFreeChannel matches the channel_name of the recording: the first word is abc, abctv, abcnews, abckids, abcfamily, abcme, or abc1–abc3, and every other word is an ABC channel word (tv, plus, kids, family, entertains, me, news, 24, hd), a state, or a capital city. ABC TV, ABC Kids/ABC Family, ABC Entertains, and ABC NEWS match; ABC Spark and a US ABC 7 do not. The ad removal code has no list of ad-free channels.
    • ad-free also for a Plex library item with no recording_id (downloadAdPlanOf): an item with a manager (Sonarr or Radarr), or a file that is not a transport stream (.ts, .m2ts, .mts). A library item with a recording_id takes the plan of that recording (filePlanOf in src/epg.js).
    • unknown: any other recording, and a transport stream in Plex with no recording_id and no manager. frameFor answers with no frame and does not grab.
  3. The queue runs one grab at a time. ffprobe reads the length of the file. programmeWindowOf takes half of the time the file runs past duration_s as padding at each end.
  4. With a clear or marked plan, adAwareOffsetsOf removes the breaks from the programme window (programmeSegmentsOf) and moves each segment edge 20 s in (BREAK_MARGIN_S), away from breaks and padding. It seeks to the middle of the longest segment, then the middles of the next two segments, then 30% and 70% of the longest segment, up to 3 offsets. The first usable frame is saved. No segment longer than 40 s gives a .none mark.
  5. With an ad-free plan, frameOffsetsOf seeks to 25%, 40%, and 60% of the programme, inside its middle 80%. With no length, it seeks to 120 s, 300 s, and 600 s. steadyUsableOf grabs all 3 and keeps the usable ones. distinctFramesOf drops frames whose 32 × 18 grey fingerprint differs from another by less than 3% (the same ad or slate in two breaks). For each frame left, it grabs a second frame 2 s later; steadyFrameOf keeps the first frame that changed less than 10% (SCENE_DRIFT_MAX). With none, the file gets a .none mark.
  6. frameArgsOf runs nice -n 19 ffmpeg -ss <offset> -i <file> for one frame through yadif, at the display aspect, at most 1280 px wide, as a JPEG. ffmpeg gets 30 s.
  7. isUsableFrame reads sharp stats: the brightness must be from 24 to 232, and the mean standard deviation of the channels at least 18. When frames decode but none is kept, the file gets a .none mark, unless the file is smaller than the size of the recording (still copying). When ffmpeg fails every time, the file waits 1 h in memory.
  8. A saved frame writes <id>.json with offsetS, adAware, plan, and version, and calls artFeed.publish for the title, background and poster, with no stamp, so open pages ask again. The origin of version 0 is frame:<id>; a later version is frame:<id>-v<version>, so thumbnails and stamps change with the picture. frameFor serves a saved frame only when its <id>.json has adAware: true or plan: ad-free; it deletes any other frame and plans it again.

The checks of the ad-free path catch a channel promo that repeats or cuts fast. A recording from a channel with ads and no ad data gives no frame, because these checks do not catch a still ad slate or a long ad shot.

When an ad scan ends, scanRecordingAds in src/commercials.js calls the onAdScanResult listeners. refreshFrameAfterAdScan in src/epg.js calls reconsider, which deletes the .none mark of the file. A frame saved without ad data whose offset is in a break or within 20 s of one (isNearBreak), or that has no <id>.json, is deleted. Its art_resolutions rows are marked due with a new stamp, and art events with the new title and programme stamps go out for the title. A frame clear of the breaks gets adAware: true. When the frame was deleted, or a request waited for the scan, it grabs again with the new plan, unless Use stills is Off.

The daily cache prune (pruneFrameGrabs in src/epg.js) deletes frames, marks, and <id>.json files whose file is no longer a file_path of a recording that is not purged or of a Plex library item, and marks the art_resolutions rows with those origins and their versions due (deleteFrameResolutions, by resolution_key in batches of 200; a failed batch is logged).

GET /api/recordings/:recording_id/image serves the saved recording picture as before. Without one, it serves the episode chain (findEpisodeThumbnail in src/epg.js), at 1280 px when w is missing. episodeOf in src/library.js adds picture, the route URL for every recording, and keeps image for the saved picture only. The New recordings row and the episode list of a show page use picture. A guide airing or episode answer that comes after a step that is still pending is provisional (provisional: true, for example the series picture while the frame of the episode is still being grabbed with Before series picture). The route sends it with Cache-Control: no-cache, and the resolver asks again in the background and tells listeners when the preferred picture arrives. episodePictureOf in src/web/shared/artwork-stamps.js adds the programme stamp of the title, and r=<tick> after each art event of the title, to a picture URL, so a tile that shows a picture loads the new one. The Home hero uses image, and its picture pools list the route only for a saved picture, so the hero is the same.

Saved guide pictures ​

createGuidePictures in src/guide-pictures.js keeps one copy of each guide image address, so an airing keeps its picture when the guide host stops serving it. The title copy of a title is its copy from a preferred host (preferredHosts; src/epg.js passes the Freeview image host), else its copy with the newest saved_at (titleIndexOf). Outside Australia no Freeview copies exist, so the title copy is the newest copy. An airing uses its own picture first and falls to the title copy only when its own picture and the saved copy of its address both fail. In Sydney about 1,150 addresses at about 34 KB each make about 40 MB. In Australia the free-to-air guide pictures of the mjh feed come from one host, and about a third of them answer 403.

  1. watchGuidePictures in src/epg.js runs saveGuidePictures after each guide load (onGuideLoaded), one run at a time, as the quiet job guide-pictures.
  2. guidePictureCandidatesOf groups the airings by title key (showTitleKey) with up to 4 distinct image addresses, earliest airing first.
  3. saveAll sets last_seen_at for every address in the guide and for the title copy of every title in the guide. It downloads each address that has no copy and did not fail recently. A title with no copy at the end is unsaved.
  4. It downloads one picture at a time. Each host has a createHostLimiter with a 1 s gap and a createCircuitBreaker from src/outbound-http.js. A failed address waits 24 h (404, 403, not an image) or 1 h (an error) in memory.
  5. encodeGuidePicture writes WebP at quality 72, at most 1280 px wide, to artwork/guide/<id>.webp (<id>: the first 24 hex characters of a SHA-256 hash of the address), then upserts the guide_pictures row.
  6. saveAll skips an address that is a stand-in picture before and after the download, and saves no copy of it.
  7. The origin is guide-picture:<id>-v<saved_at in base 36>, so a new title copy changes the stamp. originForSource gives the copy of an address, originFor the title copy. The picture gate reads it from the file.

The daily cache prune calls pruneGuidePictures: it deletes copies not seen in the guide for 180 d, then the oldest seen while the copies are over 500 MB, then any <id>.webp or <id>.webp.tmp file in artwork/guide/ with no row. It keeps a copy whose title is a recording that is not purged or a Plex library item (show_title or title), and a copy whose origin or source_url is an owner choice.

Freeview pictures ​

createFreeviewAu in src/freeview-au.js reads the keyless Freeview API for every title in the guide, after the guide step of runGuidePictures in src/epg.js. In Australia and New Zealand, Freeview pictures come first and the guide (mjh) pictures are the fallback.

  • freeviewServiceOf picks the service from FREEVIEW_SERVICES by the country of currentTimeZone(): au reads fvau-api-prod.switch.tv and /content/v1/channels/region/<region>; nz reads fvnz-capi-prod.switch.tv and /content/v1/channels (one region, nz; /channels/region/* answers 403). Other countries turn the step off. freeviewRegionOf maps the zone to a region: Australia/Sydney to region_nsw_sydney, and likewise Melbourne, Brisbane, Adelaide, Perth, Hobart, Darwin, and Canberra, with their old aliases (Australia/NSW). Australia/Broken_Hill maps to region_nsw_broken_hill, Lindeman to Brisbane, Currie to Hobart, Eucla to Perth, and Lord_Howe to Sydney. Other zones turn the step off.
  • listChannelTriplets in src/tvheadend.js reads mpegts/service/grid (sid) and mpegts/mux/grid (onid, tsid). dvbTripletOf writes each as onid:tsid:sid in 4-digit hex, the form of dvb_triplet in Freeview AU. Each channel also gets onid::sid (serviceKeyOf), the form of Freeview NZ, whose dvb_triplet has an empty TSID (222A::0514).
  • The step waits for guideMerge.firstBuild() (holdFreeviewPicturesUntil), at most 20 min, so after a start it reads the windows that the merged guide build already read. The picture cache keeps at most 2000 windows and drops the farthest first.
  • freeviewAiringsOf takes every airing from 1 h ago on a channel with a triplet, and marks the next 2 of each title fetch. matchAirings matches the fetch airings first; a later airing matches only from a window already in memory, so it adds no request. matchAirings keeps the triplets that the region lists (/content/v1/channels/region/<region>, cached 24 h), and reads /content/v1/epgs/<triplet> for the six-hour UTC window of the start, and the next or previous window when the start is within 5 min of an edge.
  • matchListing takes the listing that starts within 5 min of the airing and whose title agrees (titlesAgree: the same key without spaces, one key a word prefix of the other, or at least 2 shared words that are 60% of the shorter title). It never takes a listing with another title.
  • listingImagesOf gives the episode picture, unless other titles in the window share it (a channel placeholder), and the show picture. listingImageOf takes the show picture, else the episode picture. Addresses on img-store-prod.switch.tv change to https.
  • The show picture (else the episode picture) of each fetch airing goes to saveAll, so the title gets a saved copy, which becomes its title copy. Each title whose title copy changed gets an art event for its background and poster with no stamp, so open pages ask again; when more than 200 titles changed, one artFeed.reset tells every page to load all stamps again instead. The warmer resolves the titles after the job and sets the stamps. When listChannelTriplets fails (for example HTTP 403 without the Admin right), the step is off: the log gets one line per new reason, and guide.pictures warns with the reason and its fix (freeviewProblemOf returns { detail, fix }; freeviewPictureProblem reads the last one). The freeview step of a guide airing serves the episode picture, then the show picture, of the match of that airing from memory (up to 20000 airings), each as its saved copy, then its address. It comes first in the guide airing chain. An airing with no match (past the windows in memory, no listing with the same title, or a window that failed or backs off) takes the Freeview title copy (freeview-title), else its own guide picture. The picture saved for a new recording takes the Freeview episode picture, then the airing's own image, then the Freeview show picture and the Freeview title copy, and never another airing (Recording artwork).
  • A window that the step reads itself is kept 6 h; a window from the merged guide build is kept until that build reads it again. Image addresses download once. Measured for Sydney on 2026-11-10: 1,121 of 1,254 guide titles match a Freeview listing; one full pass reads 533 windows in about 534 requests (6–7 min at the 500 ms gap), at most about 2,140 requests a day; the first run downloads about 1,065 pictures (about 4.5 min at the 250 ms gap), then about 150 new pictures a day.
RuleValue
ClientfreeviewClient: createOutboundClient with fvau-api-prod.switch.tv (500 ms gap) and img-store-prod.switch.tv (250 ms gap)
Window15 s timeout, up to 3 pages of 100; kept 6 h in memory (2000 windows), also when empty, as the title, start, and first show and episode images of each listing (slimListingOf)
FailureA 5xx, timeout, or open breaker waits 15 min, then 1 h, then 6 h for that window

Stand-in pictures ​

Guide and Freeview addresses often give a channel logo or a channel default image in place of a programme picture. On img-store-prod.switch.tv, the same logo comes under many addresses (611157_91.png, the 9 logo, under two paths, for at least five titles). createPlaceholderPictures in src/picture-placeholders.js marks these addresses as stand-in pictures, and every picture step treats them as no picture.

createPictureGate in src/picture-gate.js is the one place that reads a picture for a chain or a saved copy. screen(origin, { bytes }) answers { verdict, reason }, where verdict is ok, weak (title card), or stand-in:

  • A guide or Freeview address is checked by its address. A guide-picture: copy is checked by its source_url. A recording copy (recording:<id>) is checked by its own bytes under the key recording:<id>, and by the file name of its image_url for the name rule.
  • upload:, frame:, and plex: origins, Plex addresses with a token, TVmaze, Wikipedia, and TMDB addresses are not checked (ok).
  • load reads an origin and answers no picture for a stand-in, and the picture with verdict: 'weak' for a title card. The resolver, the recording save, and the art pool load through it. The readers (readers in src/epg.js) are private to the gate.
  • loadOwnerChoice reads without a check. Change picture and a chosen picture (stage choice) use it, so an owner choice is never screened.
  • servedThumbnail checks the known verdict before it reads the image cache, so a cached thumbnail of an address that became a stand-in is not served.
  • loadUnlessCached answers for an origin without a read when the thumbnail is in the image cache and the origin has a measured verdict (isMeasured): no picture for a stand-in, { verdict: 'weak' } for a title card, else a marker. upload:, frame:, plex:, and unchecked addresses count as ok. Otherwise it reads through load.
  • The recording save loads the chosen origin through load, so it saves no stand-in (Recording artwork). The recording image route checks a saved copy on read (recordingCopyVerdict): a stand-in or a title card goes to the episode chain. Its warm check uses the known verdict (knownRecordingCopyVerdict) and decodes nothing.
  • recordingArt leaves out a saved copy that is a stand-in. A title-card copy stays in the pool.
  • Change picture leaves out guide candidates that are stand-ins (isStandInOrigin). It uses the known verdict of each candidate, checks all candidates at the same time, and decodes nothing.

placeholderReasonOf checks, in order:

ReasonRule
nameThe file name holds default_program_image (or programme) or a logo word
repeatedTitles from at least 5 title families use the address, or another address with the same fingerprint; or at least 3 families when the fingerprint is within 16 bits of a channel logo. A family is the first word of the title key, without the, a, an
transparentAt least 20% of the picture is transparent (alpha below 128 on a 64 × 36 sample)
logoThe fingerprint is within 10 of 64 bits of the fingerprint of a channel logo
  • pictureTraitsOf decodes the picture once, to at most 256 px. The fingerprint (pictureHashOf) is a 64-bit difference hash of that copy: on black, with its plain border trimmed (sharp trim, threshold 20), as 9 × 8 grey pixels. A logo alone and the same logo on a wide canvas get the same hash.
  • Each guide load notes the title of every guide image address (noteTitles in announceGuideLoaded). runGuidePictures in src/epg.js notes the fingerprint and mark of each channel logo (getChannelImage, once per channel and logo list). setLogos keeps them in the setting picture_logo_traits, and load reads that setting, so after a restart the logo and title-card rules work before the first run. A logo fingerprint with fewer than 8 or more than 56 set bits is not used.
  • judge computes the fingerprint, transparent share, corner marks, and detail share of an address once, from the downloaded picture or the saved copy, and saves them with the title families in picture_checks. A row saved before 0051 has no marks, so the next check with a picture measures it again. A picture that cannot be decoded is saved with an empty hash and empty marks, so it is not decoded again; it is judged only by its name and families, never by its bytes. The verdict itself is computed in memory, so a new family or a new logo can change it.
  • Every saved copy lookup (originFor, titleOriginsFor, preferredOriginFor, originForSource, savedTitleKeys) checks each copy of the title on first sight, from the copy file, and skips stand-in copies, also a copy that a recorded title keeps. Title-card copies come after all other copies of the title.
  • At the start and the end of each run, forgetPlaceholderPictures saves new families, deletes the saved copies that are stand-in pictures (dropPlaceholders), and measures each recording copy that has no marks yet (measureRecordingCopies). It keeps a copy that is an owner choice, and a copy of a recorded or Plex library title unless the reason is name or logo. It marks due the art_resolutions rows that are not yet due and whose origin (an address, a copy, or a recording copy) is a stand-in, or a title card in a row whose stage is not weak (markResolutionsDue). It gives a new programme stamp to each of these titles, each title with a dropped copy, and each title of a guide airing whose image address became a stand-in since the last run (newStandInAiringTitlesOf; the stand-in addresses of the last run are kept in the setting stand_in_airing_sources, so a restart bumps nothing new). It sends the new stamps as art events (announcePictureChanges; one artFeed.reset past 200 titles).
  • guide.pictures counts a title as without a picture when its only guide address is a stand-in picture, and leaves out art_resolutions rows with a stand-in origin.
  • listingImagesOf in src/freeview-au.js still skips an episode picture that other titles in the same Freeview window share.

Title cards ​

A title card is a channel logo and the title on a flat or gradient background (Fetch 910 × 512 pictures). It is weak: every chain uses it only when nothing better exists. src/picture-marks.js measures a picture once, at 320 × 180 grey:

  • Corner marks (cornerMarksOf): in each of 5 windows (top-left, top-right, bottom-left, bottom-right, middle-left; 42% wide, 50% high), a plane fit of the background, the pixels that differ from it by more than 28, the first row band (last for bottom windows; tallest for middle-left), and in it the first column cluster (last for right windows). The mark is the box and a 16 × 8 coverage grid of that cluster.
  • Detail (detailOf): the share of pixels whose step to the right and down neighbours is more than 16.
  • Logo marks (logoMarkOf): the same grid from each channel logo: its opaque pixels, or for a logo on an opaque tile, its white glyphs (dark glyphs on a white tile).

isCardPicture calls a picture a title card when its detail is below 0.22 and either:

  • a corner mark correlates with a logo mark at 0.8 or more (box aspects within 1.43×), or
  • its detail is below 0.12 and a corner mark is the same mark (same window, box within 3 px, aspect within 1.25×, at most 4 of 128 bits apart, at least 12 bits set) as in pictures with detail below 0.12 from at least 2 other title families. This rule finds badges that differ from the channel logo, such as the Racing.com badge.

No size or bytes-per-pixel rule is used: real programme logo art (A Moveable Feast, Farm to Fork, House of Wellness, 9News) is often small and plain, and stays ok. Measured on 2026-11-10 on the Sydney install: of 3,733 saved guide copies, 83 are title cards (all Fetch), 4 are stand-ins, and 3,646 are ok; the 22 recording copies are ok. The logo rule finds 59 of the title cards; the badge rule finds the rest.

Measured on 2026-11-10 for Sydney: 9 and 10 logos on transparent canvases, the 7 logo on a transparent canvas, default_program_image files, and one shopping picture shared by 40 infomercial titles. The family rule keeps rage Charts and Rage New Music, or the France 24 bulletins, on their shared picture.

Live picture updates ​

A list that shows the fallback for a title gets the picture without a page change, when the server finds it.

  1. A request that answers pending starts a follow-up in createArtResolver. The follow-up resolves the title, or the guide airing or episode, again after 2 s, 15 s, and 60 s, with a 20 s budget each time, and stops at the first answer that is not pending. The first picture after a pending answer calls onResolved with no stamp, also when the picture is the saved one (for example, after a restart while the Plex list loads).
  2. A picture whose resize runs past the SHOW_IMAGE_BUDGET_MS budget answers pending; publishWhenRendered in src/epg.js calls artFeed.publish with no stamp when the resize ends.
  3. remember compares the new origin and transform with the saved row (pictureChangeOf). A new picture, a changed picture, or a picture that is gone calls onResolved with { key, kind, stamp }. key is the client show key (showKeyOf); kind is poster or background.
  4. stamp is the first 10 hex characters of a SHA-256 hash of the origin and transform (pictureStampOf). A row gets a stamp only when an earlier row had a picture or a stamp, because then the browser can hold the old picture for 24 h under the URL without a stamp. A first picture needs no stamp: a 404 is never cached. A picture that is gone gets the stamp of no picture, so its URL changes too. The row keeps its stamp while the picture stays the same.
  5. Guide airing and recording answers have no row, so each title also has one programme stamp in programme_picture_stamps (createProgrammeStamps in src/programme-stamps.js): 10 random hex characters, new on each change. announcePictureChanges in src/epg.js gives a new programme stamp on a title stamp change, a marked-due row, a dropped stand-in copy, a guide airing whose address became a stand-in, a new Freeview title copy, and a change of Use stills. A first picture after a pending answer, and a frame that arrives after a provisional answer, change no stamp: the earlier answer was a 404 or no-cache.
  6. artFeed (src/art-feed.js) keeps the last 500 changes in memory, each with a sequence number. A cursor is <boot id>.<sequence>.
  7. GET /api/activity/stream?topics=art sends an art event at once, then at most every 2 s (ART_PUSH_MS) while changes come in: { cursor, reset, stamps }. A batch keeps the newest change per title and kind. With since=<cursor>, the first event holds the changes after that cursor. A cursor from another boot, a cursor past the newest change, or a cursor older than the 500 kept changes gets reset: true.
  8. GET /api/library/artwork-stamps merges the owner choices with the saved picture stamps and the programme stamps (mergedStampsOf, resolvedArtStamps in src/epg.js): { background, poster, programme } per show key. A choice stamp wins over a picture stamp of the same kind. Titles with no stamp are left out.

src/web/shared/art-stream.js opens one EventSource for the app while the page is visible. It closes the stream when the page is hidden, and opens it again with since when the page is visible, because iOS Safari drops an EventSource in a background tab. After an error it opens again after 1 s, 3 s, 10 s, then every 30 s. The Activity page adds the topic jobs to the same stream (artStream.onJobs) instead of opening a second one.

EventClient
A change with a stampsetStamps saves the stamp (background, poster, or programme), so every URL built with stampedShowImage changes
Any changeapplyResolvedArt adds 1 to the tick of the title and kind (artResolvedTickOf)
The first batch, or resetartStreamResets goes up by 1; on reset, the client also loads GET /api/library/artwork-stamps again

TitleArt and ProgrammeImage that show the fallback load the picture in an off-page Image when the tick, the stamp, or artStreamResets changes. They show the picture only after it loads, in the same box, so the layout does not move. The Home hero, the show page hero and episode pictures, and the For you chooser posters clear their failed marks on the same tick. A ProgrammeImage that shows a picture loads the new URL when the programme stamp of its title changes. The library list cache (LIBRARY_CACHE, version 2) stores show picture URLs without c=, and the server builds airing and recording URLs without c=; stampedShowImage adds the stamp when the page renders.

Picture sources ​

A guide image with an absolute URL is fetched with at most 3 redirects (IMAGE_MAX_REDIRECTS). A redirect to another host, or from https to http, gives no image and no request to that host.

SourceCodeRule
Chosen picturechosenOriginOf in src/epg.jsReads show_artwork_choices; posters as they are, backgrounds on a 16:9 canvas when narrower
PlexplexShowSources in src/show-artwork.jsart then thumb (posters: thumb then art). Each title key keeps one entry per section, so a film and a series with the same title keep their own pictures. A film takes the movies entry; another kind takes the TV entry, else the movies entry when the guide airings have no episode details
RecordingcreateLibraryTitles in src/library-titles.jsSaved recording pictures of the title, newest first
GuideimagesByTitle of the guideImages of the title's airings, earliest first
TVmazetvmazeArtworkFor in src/show-artwork.jsThe widest background image, then the show image; not for films
Wikipedia and TMDBcreateFallbackArtwork in src/fallback-artwork.jsOnline lookup

plexShowSources lists each section with a 15 s timeout. A section that fails keeps its entries from the last good list, and a refresh where every section fails keeps the whole list for another 10 min. The setting show_artwork_lookup (default on) switches off the TVmaze and online sources.

Online lookup ​

createArtworkLookup in src/fallback-artwork.js finds a Wikidata item or a TMDB record for a title. programmeHintsOf in src/artwork-match.js gathers hints from up to 8 airings: the longest synopsis, release years, cast names, episode titles, and channel names. A title with no guide airings takes its hints from Plex library items and recordings (libraryHintsOf in src/library-titles.js); a Plex film year counts as a release year. A title with no hints and no stored external ids gets no result.

  1. With a TMDB key and stored external ids, the lookup goes straight to TMDB.
  2. Otherwise it searches Wikidata (wbsearchentities), then Wikipedia, for each title variant, and keeps items with the same title key.
  3. One SPARQL query keeps films (Q11424) and television programmes (Q15416), with the year, the English article, and the TMDB and IMDb ids.
  4. rankEntities scores the items by year fit, database ids, and search order; matchEvidenceOf must accept the article text.
  5. With a key, the TMDB id gives the pictures; else the Wikipedia article image is the result. When the TMDB call fails, the Wikipedia image is stored for 6 h only, so TMDB is asked again.
  6. With a key and no Wikidata match, a TMDB search (/search/movie, /search/tv, or /search/multi) runs for each title variant.

matchEvidenceOf compares the hints with a candidate's text. It rejects a candidate on a year mismatch or on cast names that do not appear. It accepts a candidate on a cast name, a year within one, or shared proper nouns and distinctive words; else the result is no-evidence. TMDB gives up to 8 pictures per kind (MAX_TMDB_PICTURES): backdrops at original and posters at w780, English first.

Lookup caches ​

StoreTableHitMiss
Wikipedia and TMDB picturesartwork_lookups30 d7 d while the evidence stays the same; a due title asks again
Plex and TVmaze picturesshow_artwork30 d7 d; a due title asks again
Change picture poolsart_pools7 d1 h
Ratings, creditsprogramme_ratings, programme_credits30 d7 d; 6 h for a film with no guide details (no-guide-details)
TVmaze series scoresprogramme_ratings (tvmaze:series:)7 d7 d
  • Keys start with wide-v1: and hold the mode (tmdb with a key, open without), the kind, and the title key; stored external ids end the key.
  • An expired hit stays in use while a background lookup replaces it, until the data is 180 d old. A refresh with no guide hints, no year, and no stored external ids that finds nothing counts as a failure, so it never replaces a hit.
  • A Wikipedia and TMDB miss stores an evidence fingerprint in reference (miss:guide-network-v2:<step>:<fingerprint>). The fingerprint covers the kind, the sorted years, release years, and channel names, the episode flag, library presence, external ids, and whether a TMDB key is set; it leaves out the synopsis, which changes as airings roll. A changed fingerprint retries at once. The <step> part is always 0; the retry steps are those of the picture resolver.
  • A failed lookup is not stored; the key waits 10 min in memory.
  • Routes wait for a lookup within a budget, then answer pending: 1.5 s for guide images and for ratings, 3 s for a show picture, 6 s for the Change picture list.

Image cache ​

createThumbnailStore in src/image-thumbnails.js resizes pictures to WebP at quality 72 in image-cache/ beside the database (<sha256>.webp), up to IMAGE_CACHE_MAX_MB (default 100); the oldest file goes first.

Every picture route reads the cache first and reads the original only on a miss (thumbnailFor calls loadOriginal only when no file has the key and width):

  • Channel logos (channel:<id>:<logos>), person pictures (person:<source>), and owner choices (chosen-1080:<kind>:<origin>) are keyed without a read.
  • Show pictures resolve from the saved art_resolutions row, then read the cache under art:<shape>:<transform>:<origin>.
  • A guide airing resolves through the airing memory (Picture resolver). On a miss, the airing chain loads each origin through loadUnlessCached with the asked width, so an origin whose thumbnail is cached is not read, also after a restart. A cached airing thumbnail is still served after its source fails, until the image cache drops it.
  • An art pool picture is keyed by its origin (show-1080:<origin>), so a plex: origin finds its thumbnail without the Plex token. The token is read only to load the original.
  • A recording picture is keyed by the size and time of the saved file (recording:<id>:<size>-<mtime>).

The episode chain still reads the recording copy of the episode step on each request. Recording thumbnails use image-cache/recordings/ with 20 MB. createProgrammeImages (src/programme-images.js) keeps 64 source images (32 MB) in memory. Its downloads, and those of saveAll, go to guideImageHosts.

Picture warm-up ​

createArtWarmer in src/art-warmer.js resolves pictures and renders their thumbnails before a page asks for them, as the quiet job artwork. It calls the same picture routes as the browser (createImageResolver in src/image-routes.js), at the widths each page asks for, so a page finds the thumbnail in the image cache.

createWarmUrls in src/art-warm-plan.js lists the picture URLs of each tier, in this order:

TierPicturesWidths
homeHome hero candidates; the in-progress and New recordings episodes (picture); On now airings768, 1280, 1920; 384; 384, 768
for-youFor you top pick and row items384, 768
recordingsLibrary shelf posters and cards384
guide-todayGuide cells with a picture, from now to 24 h ahead192
scheduledUpcoming recordings384
show-heroesShow page heroes of library shows768
show-postersShow page posters of library shows192
due-titlesShow pictures of titles in the next 7 days of the guide whose art_resolutions miss row is due and still has the title's kind, up to 200 (dueMissTitles)384
guide-weekGuide cells with a picture, 24 h ahead and later192
framesRecordings with no saved picture and a file, newest first, up to 500 (the episode route grabs a frame)384
  1. Each URL is checked once per run with the isWarm check of its route (createImageWarmCheck in src/image-routes.js); it renders nothing and makes no web request. A show picture is warm when the choice or the art_resolutions row is not due, the fingerprint of the local steps (Plex, recording, guide) still matches, and the thumbnail is in the cache (peek in createArtResolver, isShowArtWarm in src/epg.js), so a new recording picture after a sync or a Plex scan is warmed. A guide airing is warm when the thumbnail of its own picture, its saved copy, or a title picture is cached (isProgrammeArtWarm); in Australia, an airing with Freeview pictures is warm when the thumbnail of any picture its chain can serve is cached: the Freeview pictures, the Freeview title copy, its own picture and saved copy, the title copy, or other airings (programmeWarmOriginsOf). A recording picture is warm when its thumbnail is cached under recording:<id>:<size>-<mtime> of the saved picture file; with no saved picture, when the episode chain has a cached title picture or frame, or no picture at all (isEpisodeArtWarm). An art pool picture is warm when the thumbnail of its origin is cached. A warm URL costs no render and no lookup.
  2. A cold URL runs its route inside runAsBackgroundWork (src/background-work.js, an AsyncLocalStorage store). One URL runs at a time, so there is one render at a time.
  3. Before each URL, the warmer waits 5 s at a time while one of these runs: a live or playback session, an ad scan, a sync, import, ads, or guide-pictures job, a queued frame grab, 4 or more background lookups, or an event-loop delay p99 over 50 ms in a 10 s window (createLoopPressure).
  4. It stops rendering when the thumbnails it wrote, and no page has read since, fill 60% of the image cache (warmShare). Each such thumbnail has an empty <name>.webp.warm file beside it, so the share survives a restart; a page read deletes it.
  5. A URL that answers pending waits for the background lookups to end (up to 10 min) and runs once more at the end of the run.
  6. Each run logs one line: [art-warm] trigger … · tiers … · checked … · warm … · rendered … · pending … · missing … · failed … · paused … s, and the job outcome holds the same text. current() and onProgress give { state, trigger, done, total, counts } for a later content-prep step of the wizard.

Online lookups from the warmer are background tasks. The lookup limiter of createFallbackArtwork (2 at a time) keeps one place for a page request (reservedForUrgent in createHostLimiter), and the TVmaze lookups of createShowArtwork use a createHostLimiter with a 1 s gap. A page request for a title whose lookup waits in the background queue moves it to the front (promote). Each host keeps its gap, so the pace is the rate limit of each source; there is no daily cap. Only a title with no saved result, or whose retry is due, gets a lookup.

createVisitPattern in src/visit-pattern.js learns when the owner opens the app. A visit is a GET under /api/ after 20 min with no such request; picture, logo, art pool, stream, health, Doctor, and version requests do not count. The client sends X-Freetvarr-View: hidden with every request from a hidden tab, which never counts, and X-Freetvarr-Poll: 1 with the timed reads of /api/recording-now, /api/sync-status, and /api/activity/summary (pollApi in src/web/shared/api.js). A poll from a visible tab is not a visit, but it updates the last active time, as every counted request does. The last active time is saved at most once an hour, and it sets the backoff below. Each visit adds 1 to one of 168 hour-of-week bins; all bins halve every 14 days. The bins, the last visit, the last active time, and the visit count are saved in the setting visit_pattern. nextWindowAt gives the time 45 min before the next hour whose weight is 0.5 or more.

TriggerLast active under 3 days ago3–14 days ago14 days ago or more
For you result (new items only)The new itemsThe new itemsNothing
Guide load, sync finished, Plex watch sync doneTop and next tiersTop tiersNothing
Visit windowTop and next tiersNothingNothing
Nightly, 03:30All tiersAll tiersAll tiers, no online lookup

The top tiers are home, for-you, recordings, and guide-today; the next tiers are scheduled, show-heroes, show-posters, and due-titles. With no online lookup, the online steps answer pending without a request, so nothing is saved as a miss; a page request still looks up. The next counted request sets the first column again. Shutdown stops the warmer and its timers. Triggers that come within 30 s merge into one run; a trigger during a run waits for the run to end.

Change picture ​

src/artwork-choice-routes.js serves Change picture under /api/library/shows/:key/: artwork-candidates (the list; pending after 6 s), artwork-candidates/:id (one picture), PUT and DELETE artwork/:kind (choose, clear), and artwork/:kind/uploads (upload, delete). :kind is background or poster. Candidates come from Plex, TVmaze, TMDB, Wikipedia, the guide, and uploads, up to 12 per source and kind. The choice goes in show_artwork_choices (show_key, kind, origin, source, chosen_at).

Uploads (src/artwork-uploads.js) accept up to 20 MB and 40 megapixels in jpeg, png, webp, or heif, 12 per show and kind. They are stored as WebP at most 1920×1080 (background) or 1000×1500 (poster) in uploads/artwork/<showKey>/.

src/art-pool.js builds the picture pools behind the show and episode pages (GET /api/library/shows/:key/art-pool, GET /api/library/recordings/:recording_id/art).

Picture focus ​

Picture focus stores a face box or a focus point for each picture URL, so the client can crop heroes and posters around faces.

  • The middleware imageFocus.tap (src/image-focus.js) queues each served picture on a focus path (FOCUS_IMAGE_PATHS) that has no current image_focus row.
  • src/image-focus-worker.js runs as a child process at priority 19, 16 pictures per run. It runs assets/models/ultraface-rfb-320.onnx through onnxruntime-node (ONNX Runtime) and keeps faces with a score of 0.7 or more. With no face, the focus is the sharp attention point, else the centre.
  • The worker pauses 10 min when free memory falls below 400 MB, and 30 min after a failed run.
  • image_focus keeps the newest 20000 rows. method is faces, attention, or centre.
  • GET /api/image-focus?k=<key> takes up to 40 keys and returns { enabled, items }. The setting face_focus_enabled (default on) switches the feature.

TMDB key ​

src/tmdb-key.js serves GET, PUT, and DELETE /api/artwork/tmdb and POST /api/artwork/tmdb/test. The key lives in the setting tmdb_api_key; GET returns { key_set }, never the key. validateTmdbKey requests GET /3/configuration: 401 means invalid, other failures mean unreachable (the key is saved with checked: false). A key with a dot and more than 40 characters goes in Authorization: Bearer; any other key goes in the query parameter api_key.

Outbound HTTP ​

createOutboundClient in src/outbound-http.js sends every request for pictures, ratings, reviews, cast, and person images. The shared instance is artworkClient in src/fallback-artwork.js, which sets the host list:

HostConcurrencyGap
www.wikidata.org2200 ms
query.wikidata.org11000 ms
en.wikipedia.org2200 ms
upload.wikimedia.org2250 ms
api.themoviedb.org, image.tmdb.org450 ms
api.tvmaze.com1500 ms
static.tvmaze.com2100 ms
www.tvmaze.com, www.themoviedb.org11000 ms (HEAD / link checks only)
RuleValue
Addresshttps only, a host from the list, at most 3 redirects that stay on the list
JSON request8 s timeout (20 s for SPARQL), 2 MB limit, 2 retries
Image request10 s timeout, 4 MB limit, JPEG, PNG, WebP, or GIF, 1 retry
QueueUp to 200 waiting requests per host; more fail with queue-full
BackgroundcreateHostLimiter runs urgent tasks before background tasks; reservedForUrgent keeps that many places for urgent tasks; promote(id) moves a background task to the urgent queue
RetriesOn 408, 425, 429, 500, 502, 503, 504, a timeout, or a network error; delay 500 ms doubling up to 8 s. A 429 or 5xx also holds the whole host queue for that delay, or for Retry-After up to 5 min (hostHoldMsOf)
JitterA host with jitterMs waits its gap plus a random 0 to jitterMs between starts. FREEVIEW_API_PACE is 500 ms plus up to 500 ms, one request at a time
404, 410The call returns null
Circuit breaker5 failures in a row open the breaker for 60 s, doubling per trip up to 30 min
User-AgentFreetvarr (https://github.com/furey/freetvarr) (Wikimedia policy)

Errors name the host and the status, never the address, so a TMDB key never reaches a log. Every TVmaze API call goes through artworkClient, including genre searches, series scores, and AKA lookups (as background requests) and image lists. Wikidata calls in src/genre-enrichment.js and src/known-as.js, the Plex section lists in src/show-artwork.js, and fetchProgrammeImage call axios directly.

src/lookup-gate.js limits lookups for titles that Freetvarr does not know. A title is known when it is in the guide, guide_programs, recordings, watchlist, or library_items (show_title, and title for items that are not episodes). Unknown titles may start 60 lookups an hour (UNKNOWN_TITLE_BUDGET); a refused lookup answers none.

src/cache-prune.js runs 10 min after start, then daily. It deletes rows of the lookup tables whose expires_at (resolved_at for art_resolutions, changed_at for programme_picture_stamps) is more than 90 d past, then keeps the newest 20000 rows per table. src/link-health.js checks each link host at most every 5 min; links to a host that is down become null.

Ratings and reviews ​

GET /api/epg/programme-ratings?title=&kind=movie&year= returns { status, score, votes, source, url, reviews } (ratingsLimiter). status is ready, pending, or none. The route waits 1.5 s for a new lookup, then answers pending; the client asks again after 1, 2, 4, 8, and 15 s.

SettingDefaultEffect
ratings_lookup_enabledOnScores
reviews_lookup_enabledOnReview snippets; they need a TMDB key
tmdb_api_keyNoneFilms and reviews need it; series scores work without it

createRatingsLookup in src/programme-ratings.js matches the title:

  • A film matches TMDB by stored external ids, the stored picture reference, or /search/movie with year and evidence rules (matchedFilm).
  • A series matches TMDB first with a key, then TVmaze (pickRatedShow), with the same evidence rules.
  • Only story types score. A TMDB type outside Scripted, Documentary, and Miniseries, or a TVmaze type outside Scripted, Animation, and Documentary, ends with the miss not-story.
  • A TMDB score needs 50 votes or more (MIN_TMDB_VOTES). A TVmaze score is rating.average with votes: null.

src/review-snippet.js picks one TMDB review sentence of 50–170 characters with judgement words and no spoiler words. The ratings warm-up (warmUpcomingRatings in src/server.js) looks up the films and rated categories of the next 24 h, 2 min after start and then hourly.

Cast and crew ​

GET /api/epg/programme-credits?title=&kind=movie&year= returns { status, overview, cast, crew, details, source, url } with the same parameters, wait, and limiter as the ratings route. cast holds up to 12 entries { name, character, image, url }. Film crew is the directors, up to 2 writers, and up to 2 producers. Series crew is the creators and up to 2 executive producers, from TMDB when the TMDB match has a cast, else from TVmaze. /api/epg/person-image proxies TMDB w185 and TVmaze person images at w=192. The setting credits_lookup_enabled (default on) switches the lookup. When it is off, the answer is status: 'none' with off: true, and no request leaves the server.

details is { company, year, genres, minutes, language } or null (detailsOf in src/programme-credits.js). genres holds up to 3 names. Each source fills it:

Sourcecompanyyearminuteslanguage
TVmaze seriesnetwork.name, else webChannelpremieredaverageRuntime, runtimelanguage
TMDB seriesnetworks[0]first_air_dateepisode_run_time[0]original_language (Intl.DisplayNames)
TMDB filmproduction_companies[0]release_dateruntimeoriginal_language
Wikidata filmP272 labelearliest P577P2047 in minutes (Q7727)P364 label

A cached hit with no details key counts as outdated (lacksDetails): it answers at once and starts a background refresh.

A film with no TMDB key goes to src/wikidata-film-credits.js through artworkClient, which holds the per-host limits for www.wikidata.org and query.wikidata.org:

  1. wbsearchentities on the title, and a full-text list=search for <title> haswbstatement:P31=Q11424 sorted by incoming_links_desc. candidateIdsOf keeps items whose label or alias has the same showTitleKey.
  2. One SPARQL query (filmYearsQueryOf) keeps the items that are an instance of a WIKIDATA_FILM_KINDS class, with their earliest P577 year. The request year, else the single guide release year, must be within 1 year.
  3. For up to 3 films, wbgetentities reads the claims: P161 cast (ordered by the P1545 qualifier, character from P4633 or P453, deprecated statements skipped), P57 directors, P58 writers, P162 producers. A second wbgetentities call reads the labels (en, else mul) and enwiki sitelinks of those items.
  4. One film is the answer. With more than one, the answer is the only film whose description, cast, characters, and crew pass matchEvidenceOf against the guide hints; otherwise it is a miss.

Wikidata cast has image: null. A person url is the enwiki article, else the Wikidata page. The film url is its enwiki article. source is wikidata.

The client reads credits only in two places: the show page (useProgrammeCredits), and More info (MoreInfo in src/web/components/more-info.js). MoreInfo is a <details> with the ui-disclosure-summary style, used in the programme sheet and LibraryInfoSheet. It fetches on the first toggle to open, through loadMoreInfoCredits in src/web/more-info.js: it repeats a pending answer on each retryDelayOf step (1–15 s, about 30 s in all), and holdAtLeast keeps the skeletons for at least 900 ms. moreInfoOf builds the cast, the crew lines, and the details rows (series: Network, First aired, Genres, Episode length, Language; film: Studio, Released, Genres, Length, Language). It drops empty rows, and falls back to the guide genre (guideDetailsOf). Each sheet keys MoreInfo by programme, so it starts closed. When every retry is still pending, the section says it is still looking up cast and crew, and the next open asks again. GET /api/recordings adds kind to each row (src/recording-title-kind.js): the title_kinds kind, else movie or one-off from the folder the file sits in, else null.

The programme sheet (ProgrammeSheetHost in src/web/components/programme-sheet-host.js) has these parts, top to bottom:

  1. About: the image with the close button (.programme-sheet-close), the title, the episode line (sheetEpisodeLineOf, which drops an episode title of the form Episode N), the airing line (sheetAiringLineOf), the synopsis, and MoreInfo.
  2. Recording: one ui-group card (.programme-sheet-recording). It holds the status row, the cancel rows (cancelActions), the ui-segmented choice from sheetStrengthsFor, PaddingRows, Keep, Any channel, and Advanced. Advanced is a <details> whose summary uses the shared ui-disclosure-row style.
  3. Actions: Record (primaryActionOf), Watch from the start, and Watch live.
  4. Menu: Show in TV guide, the movie correction, and the For you hide items, as library-menu rows.

The sheet has no Close button. It closes from the X, the grab handle (tap or swipe), the backdrop, Esc, the browser back button (overlayStack), and a route change.

Classification ​

A classification is one of G, PG, M, MA15+, R18+, P, C, or AV15+ (CLASSIFICATIONS in src/classification-labels.js).

  • serveShiftedFeed records the <rating> and <category> of each XMLTV programme while TVHeadend reads /guide/xmltv.xml. It prefers an Australian rating system.
  • The labels go in programme_classifications and programme_categories (title_key, start_ms, shift_hours). A +1 copy stores its label with shift_hours 1, so it never replaces the base channel's label at the same time. Readers, including the sync and upcoming timers, take shift_hours from the channel name (timeshiftHours). Rows older than 3 d are deleted after each feed load.
  • fallbackClassification uses the TVHeadend rating label, else maps the TVHeadend age 15 to MA15+ and 18 to R18+.
  • The sync stores the label in recordings.classification and keeps the first label. Each prune copies labels into recordings with a null label.
  • Guide cells, live now and next, upcoming recordings, For you items, library rows, and episode rows carry classification. Scores and reviews are not part of list payloads.

Plex ​

src/plex.js holds the Plex connection and library helpers. The settings are plex_url, plex_token, plex_tv_section_id, plex_oneoff_section_id, and plex_movies_section_id. The user guide covers the setup (Plex).

RouteDoes
POST /api/discover-plexGDM discovery: a UDP broadcast to port 32414, replies collected for 2 s (Plex GDM); needs host networking
POST /api/plex-detect-tokenReads PlexOnlineToken from Preferences.xml, saves it as plex_token with plex_token_scope = 'this-machine', and returns plex_token_set
POST /api/plex-sectionsLists the sections (key, title, type, locations)
POST /api/plex-libraries, POST /api/plex-libraries/createPlans and creates one library each for the TV (TV Shows), one-off (One-offs), and movies (Movies) roots, and saves the section ids
POST /api/plex-refreshStarts a section refresh
  • The path of Preferences.xml is the setting plex_prefs_path, else PLEX_PREFS_PATH, else /plex/Library/Application Support/Plex Media Server/Preferences.xml. The file name must be Preferences.xml or end in -preferences.xml.
  • storedPlexTokenFor(url) gives the stored token to a URL only under the rules in Secret binding; otherwise the route answers Paste the Plex token for this server.
  • Requests to Plex use axios with a 5 s timeout; a section item list uses 15 s.
  • After a sync, each kind with an import refreshes its section with GET /library/sections/<id>/refresh: TV through notifyPlexSectionRefresh, one-offs and films through refreshSection. With no URL, token, or section, the result is { skipped: true, reason: 'plex not configured' }.

Watched sync ​

createPlexWatchSync in src/plex-watch-sync.js copies watched marks and resume points in both directions. src/plex-watch.js wires it to the database; src/plex-watch-plan.js holds the decision rules; src/plex-watch-client.js holds the Plex requests.

  • Rows that take part: imported done or partial recordings that are not deleted, and items in the three Plex sections.
  • matchPlexItem in src/library-actions.js scores a Plex item by the shared trailing path segments with the recording file. An ambiguous match takes no part.
  • Triggers: the end of a sync, a watched or position change (after 10 s), the Library opening (at most every 2 min), a settings change, and Sync watched now (POST /api/plex/watch-sync/run). One run executes at a time; requests during a run join one queued run.
  • A full pass reads every section item, 500 per page, up to 400 pages (MAX_PAGES). It runs for a manual trigger, on the first run, when the last full pass is 24 h old, or after 1 h when rows lack a snapshot. A quick pass reads items viewed since the last run less 2 min.

plex_watch_state stores one snapshot per recording: rating_key, plex_watched, plex_offset_s, ft_watched, ft_position_s, and synced_at. The plan for a row:

RuleDetail
First run (no snapshot)Watched on either side makes both watched; the side with a resume point wins
Later runsThe side that changed since the snapshot wins; when both changed, Freetvarr wins for watched and the newer wins for resume points
Resume pointsUsed only when both sides are unwatched; offsets within 15 s are equal
End marginA Plex resume point within 30 s of the end marks the recording watched
Togglesplex_watch_from_plex and plex_watch_to_plex (both on) block writes to one side

A copy from Plex updates a recording only when its watched_at and playback_position_s still match what the run read; otherwise that row waits for the next run. When /library/metadata answers 404 for a batch, the client asks for each key alone and drops the keys that answer 404. The run finishes, and fullPassDue in the status makes the next run a full pass.

Writes to Plex use /:/scrobble, /:/unscrobble, and /:/progress, 4 at a time. When Plex does not answer, automatic runs wait 5 min doubling up to 2 h. A 401 stops automatic runs until the token changes. The status is in the setting plex_watch_status; GET and PUT /api/plex/watch-sync read it and set the toggles.

Whole library ​

createLibraryScan in src/plex-library-scan.js runs at the end of each watched sync when the setting plex_whole_library is not false. The sections are in plex_library_sections (default: the TV and movies sections; never the one-off section).

  • Each Plex file part becomes a library_items row (rating_key, part_id). A full pass deletes rows that it did not see, except in a section that stopped at MAX_PAGES; that section keeps its unseen rows, and the run log warns. recording_id is set when the file is a Freetvarr recording.
  • localPathOf in src/plex-library.js maps a Plex path to a local path by the root folder names. A recording also links to a Plex file whose path ends with the recording's path below its library root (at least 2 segments).
  • Files deleted through Freetvarr stay out of library_items for 30 min, in memory, so a scan before Plex notices the delete does not save them again.
  • The scan links each row with no recording_id to its Sonarr or Radarr manager, and writes Plex and Sonarr GUIDs to external_ids.
  • src/library.js merges library_items with the recordings. A Plex copy of a recording, or a Plex episode with the same show, season, and episode, becomes another version of that recording. Only a recording with a playable file (done or partial, no library_state) takes the Plex episode; a failed or skipped recording of that episode is dropped and the Plex episode stays. Any other item becomes a row with the id plex-<ratingKey>.
  • A watched mark or resume point on a plex- row sets pending_push (scrobble, unscrobble, or progress); the next scan sends it.

GET and PUT /api/plex/whole-library read and set the switch and sections. GET /api/library/items/:ratingKey/image serves Plex artwork through /photo/:/transcode. Plex changes the path of a thumb when it refreshes the picture, so a saved thumb can answer 404 until the next scan. On a miss, createItemImage in src/plex-library-routes.js reads the item again (GET /library/metadata/<ratingKey>), at most once per item in 5 min. When thumb or art changed (itemArtOf, the same rules as the scan), it saves them in library_items, serves the new picture, and calls artFeed.publish for the show, poster and background, with no stamp. A later scan keeps a saved thumb or art whose version (the number at the end of the Plex path) is newer than the one it read (newerArtOf in src/plex-library-store.js).

Sonarr and Radarr ​

Sonarr and Radarr link to Freetvarr in three places: the settings routes, the library scan, and the delete flow. The user guide covers the setup (Sonarr and Radarr).

src/arr-client.js calls the v3 API of each app with the header X-Api-Key. Reads time out after 8 s with 1 retry and a 20 MB limit; the full series and movie lists get 60 s and 200 MB. Writes time out after 15 s with no retry. A 401 gives an ArrError of kind key, 404 gives missing, and 409 gives conflict. arrClientFor in src/arr-store.js caches one client and one circuit breaker per <url>|<apiKey>.

The settings are sonarr_url, radarr_url, sonarr_api_key, radarr_api_key, and arr_unmonitor_on_delete (Stop downloading it again, default on). Without a saved key, Freetvarr reads ApiKey, Port, and UrlBase from the app's config.xml at SONARR_CONFIG_PATH or RADARR_CONFIG_PATH. The config.xml key goes only to a URL on this machine (loopback, host.docker.internal, the app's container name, or a local interface address) at the config.xml port. A saved URL with a new origin and no key in the same request empties the saved key.

RouteDoes
GET /api/arr{ sonarr, radarr, unmonitorOnDelete } with hasKey and keySource; never the key
PUT /api/arrSaves URLs, keys (^[A-Za-z0-9]{16,64}$), and the switch; starts a full watched sync
POST /api/arr/findSends GET /ping (2 s) to the hosts of plex_url and tvh_url, localhost, host.docker.internal, sonarr, and radarr on the config.xml port, else 8989 or 7878
POST /api/arr/:app/test{ ok, version, count, recycleBin }

A full library pass lists every Sonarr episode file and Radarr movie file, and links library_items rows to their manager by exact path, else by the last 3 path segments. src/delete-manager-check.js repeats the lookup at delete time; when an app cannot be reached, the delete stops.

A delete of a managed copy (src/foreign-delete.js) runs in this order:

  1. With arr_unmonitor_on_delete on, unmonitor the episodes (PUT /api/v3/episode/monitor) or the movie (PUT /api/v3/movie/editor). A failure stops the delete.
  2. Call DELETE /api/v3/episodefile/<id> or DELETE /api/v3/moviefile/<id>. A 404 counts as done with missing.
  3. On any other failure, monitor the items again. On success, delete the library_items rows of the file.

With remove_series: true, Freetvarr also calls DELETE /api/v3/series/<id> with deleteFiles=false and addImportListExclusion=true.

For you and Home hero ​

Suggestions ​

src/for-you.js ranks the programmes in the next 7 days of the guide for one household.

StageModuleMechanism
Eventssrc/user-events.js, src/user-events-log.jsWrites rows to user_events
Profilesrc/for-you-profile.jsFolds events and recordings into one affinity per show
Scoringsrc/for-you.jsScores each airing, then groups the best airing per show into sections
Similaritysrc/for-you-similarity.js, src/for-you-engine.jsCompares programme texts by BM25 or by embedding vectors
Upkeepsrc/for-you-service.js, src/series-ratings.jsRuns the embeddings, the genre lookups, and the TVmaze series scores once a day
  • buildForYou runs categorySectionsOf on a cold start too, for taste, and drops its sections.
  • user_events kinds: watch_start, watch_end, record_request, record_cancel, series_stop, series_pause, series_resume, recording_deleted, suggestion_shown, suggestion_accepted, suggestion_dismissed, not_interested, not_interested_undo, thumb_up, thumb_down, fewer_like_this, fewer_like_this_undo, thumb_clear, programme_opened, category_muted, category_unmuted, category_boosted, category_unboosted, row_hidden, and row_hidden_undo.
  • thumb_clear empties both thumbs and fewer_like_this of a show; the client sends it when More like this turns off, and Show again writes it with not_interested_undo when the newest thumb is down. Hidden shows lists not_interested shows of the last 90 days and shows whose newest thumb is down.
  • recording_deleted meta carries watched, season, episode, and watched_at. profileOf counts a watched deletion as a finished episode with the key rec:<recording_id>.
  • Hide from Finish what you started writes row_hidden with meta { row: 'finish-started' }, and Undo and Show again write row_hidden_undo. isRowHidden in src/for-you-profile.js holds while the hide is newer than the last watched episode (lastWatchTs, episodes with a fraction of 0.25 or more; WATCHED_FRACTION). With history paused, no watch is written, so the hide stays. It changes no affinity. GET /api/for-you/hidden adds each row hide with the series key <row>:<show key>, a row, a showKey, and a showTitle.
  • Fewer like this writes fewer_like_this; turning it off and Undo write fewer_like_this_undo, which empties only the fewer marks. The client no longer writes thumb_down, and older thumb_down rows keep hiding their show. fewerWeightOf in src/for-you-profile.js is the decay of the newest fewer_like_this (half-life 60 days), or 0 when a later thumb_up or a thumb_clear exists or the decay is under 0.05 (FEWER_MIN_WEIGHT). fewerShowsOf sorts the marked shows by weight, strongest first, before the first 12 become anchors. fewerFactorOf(weight) is 0.2 + 0.8 × (1 − weight) (FEWER_FACTOR 0.2, the same as MUTE_FACTOR). scoreAiring multiplies the show's own score by that factor, and by the factor of the nearest fewer_like_this show (fewerAnchors in the similarity context, weight = similarity score × the show's weight). The nearest-show factor skips a show with an affinity of 0.25 or more (LIKED_AFFINITY) and a show with a thumb_up newer than the anchor's mark. withFewerCategories multiplies each category share by the factor of the show's tagged groups (weight = show weight × entry weight). It reads the tags of the current build, not tags saved with the mark, so a tag fix changes the cut at the next build. The show is never hidden.
  • The setting viewing_history_enabled stops writes when false, except the choices in CHOICE_KINDS (not_interested, thumb_up, thumb_down, fewer_like_this, thumb_clear, category_muted, category_unmuted, category_boosted, category_unboosted, row_hidden, row_hidden_undo). A feedback post with a choice flushes the events, forgets the cached For you result, and rebuilds the Home hero. DELETE /api/events clears the history. Rows older than 730 days, and suggestion_shown rows older than 30 days, are deleted on the cron tick.
  • profileOf decays each event with a half-life of 60 days. A show with 3 or more starts, under 15% finished, and no thumbs up is abandoned and keeps 0.3 of its affinity.
  • Fewer than 5 engaged shows (COLD_START_SHOWS) give a cold start: sections ready-to-watch, finish-started, tonight-movies, top-rated-series, premieres, top-rated, and movies. A warm response adds coming-up, new-seasons, and might-like.
  • The page order is ready-to-watch, finish-started, coming-up, the seasonal row, new-seasons, tonight-movies, might-like, the category rows, top-rated-series, top-rated, movies, premieres (SECTION_ORDER in src/web/for-you.js; see Seasonal rows and Category rows). A cold start also gets the seasonal row. Airing sections share one list of taken shows: a show goes into the first airing section that takes it, and the airing sections after it skip the show. ready-to-watch lists recordings and takes no show from the airing sections, except finish-started, which skips a show that has a ready-to-watch item. A section with no items is left out.
  • The new sections hold up to 12 items (ROW_LIMIT). GET /api/for-you returns up to 12 items per section by default and up to 20 with limit.
SectionSelectionOrder
ready-to-watchRecordings with status done or partial, no purged_at, library_state not not_in_library, no watched_at (Plex sync sets it), and no watch_end that reached 80%; the oldest episode per showShow affinity, then the newest recording
finish-startedShows with 1–3 finished episodes, not abandoned or hidden, active in the last 60 days, no series_stop in the last 90 days without a later record_request, and no row_hidden newer than the last watched episode; their next airing this week, without an airing that isBehindWatched rejectsStart time
tonight-moviesFilms that start from the later of now and 5 pm local time until 3 am local time (from now until 3 am between midnight and 3 am), with a score of 0.03 or more or a TMDB score above the prior of 6.5Score plus 0.3 times the weighted TMDB score above 6.5
top-rated-seriesSeries with a saved TVmaze score, a TVmaze rating.average of 7 or more, a weight of 50 or more, the type Scripted, Animation, or Documentary, and a guide slot of 0.8–2.2 times the TVmaze runtimeTVmaze score, then weight
  • isBehindWatched in src/for-you.js rejects an airing with a guide series_no below maxSeason (the highest recording season, from Plex parentIndex), or with an episode_no at or below the highest watched episode of that season. It applies only when the airing has both numbers and both seasons are numbered the same way (both below 1900, or both 1900 or more). finish-started skips these airings, and coming-up skips entries with behind set.
  • All sections except ready-to-watch leave out news and sport where they list episodes, and skip airings that are scheduled, recorded, covered by a series rule, or hidden. ready-to-watch items carry kind: 'ready', a recordingId, and no start time. A press plays the recording, or opens the show page when the file does not play. They do not go into the Home row or the Home hero.
  • The top-rated-series section carries credit ({ source: 'TVmaze', href: 'https://www.tvmaze.com' }); the page shows it as a link beside the heading, as the TVmaze licence (CC BY-SA) asks.
  • src/top-rated.js weights a film score as (votes / (votes + 1000)) * score + (1000 / (votes + 1000)) * 6.5, and keeps at most 10 films.
  • scoreAiring adds weighted features (affinity, interest, new-season, back, premiere, habit, hour, genre, similar, pinned, prime, image) and applies a penalty for dismissals, thumbs down, and fewer_like_this.
  • src/series-ratings.js searches TVmaze (GET /search/shows) for each title in the next 7 days that title_genres matched to TVmaze, when the settings for_you_genre_lookup and ratings_lookup_enabled are both on. It keeps a result only when the same-title show is dominant (dominantShowOf in src/top-rated.js: weight 50 or more and 3 times the next same-title show), or when it is the only same-title show from the country of the time zone. It waits 1 s before each request, uses artworkClient with an 8 s timeout and a 256 KB limit, and looks up at most 300 titles per run. It stores score, weight, type, runtime, and the TVmaze page in programme_ratings under tvmaze:series: and the title key for 7 days; no confident match stores a miss for 7 days. With ratings_lookup_enabled off, loadSeriesRatings returns no scores, so top-rated-series is empty. 60 s after startup, warmSeriesRatings runs one refresh when programme_ratings has no tvmaze:series: rows; the nightly upkeep shares the same run, so a title is asked once. A failed request stores nothing, so the last good score stays in use. A run stops after 5 failed requests in a row. Upkeep runs it after the genre lookups. The snapshot stamp seriesRatings (row count and latest expiry) makes a new score start a new build.
  • src/genre-enrichment.js stores TVmaze and Wikidata genres in title_genres when the setting for_you_genre_lookup is on. lookupOrderOf merges the entries of one title, so a title that airs as a film is looked up on Wikidata even when it is also a recording or an event. A film miss stores a miss and never falls back to a TVmaze series. A run stops after 5 failed lookups in a row.

similar uses one of three levels:

LevelMethodModel
basicBM25 vectors over titles and descriptionsNone
standardEmbeddings through @huggingface/transformers in a child process (src/for-you-embed-worker.js)Xenova/all-MiniLM-L6-v2, q8, 384 dimensions
plusEmbeddings from Ollama when it lists an embedding model, else the local modelXenova/bge-small-en-v1.5, q8, 384 dimensions

src/for-you-capability.js picks the level: plus when Ollama lists an embedding model; basic when the ONNX runtime does not load, free memory is under 400 MB, or the daily texts take over 300 s; plus when the standard time times 2.5 is under 120 s; else standard. The setting for_you_tier_override forces a level. The embeddings are cached in text_embeddings; the model files download into models/ on first use. When the level changes during an embed run, another run starts with the new model as soon as the first ends (createLatestRun, up to 3 runs).

runForYouUpkeep runs on each cron tick. It starts upkeep when none has run, the last run is over 36 h old, or the local hour is 2–5 and the last run was on another day. The service builds the For you result 3 s after startup and after each guide load.

Category rows ​

Category rows are For you sections named after a kind of programme, such as Cooking or AFL. categorySectionsOf in src/for-you.js builds them in the For you worker, in the same build as the other sections. A cold start has no category rows.

PartModuleMechanism
Cataloguesrc/for-you-category-catalogue.jsFormat and topic categories, each with facets; topic facets have 2 to 4 example sentences (prototypes)
Known showssrc/for-you-known-shows.js, src/data/known-shows.jsonLabels of about 600 free-to-air shows, keyed by show key
Label rulessrc/for-you-label-rules.jsMaps TVmaze and Wikidata genres, title words, guide genres, and genre bytes to categories
Taggingsrc/for-you-categories.jsGives each title one format, up to 2 topics, a sport code, and an origin country
Affinitysrc/for-you-categories.jsSums the household's events per category
Rowssrc/for-you.js, src/for-you-categories.jsPicks the categories with enough share and enough programmes, then ranks and dedupes the items
Vectorssrc/for-you-engine.jsEmbeds the prototype sentences with the programme texts and keeps their text_embeddings rows fresh

The catalogue (CATEGORY_CATALOGUE_VERSION 4):

  • Formats, by group (FORMAT_GROUPS): scripted holds comedy, drama, crime-drama, soaps, and sci-fi-fantasy; unscripted holds reality, quiz, documentaries, lifestyle, talk-shows, and panel-shows; other holds news and kids. kids and news are formats that are never rows. Format facets have no prototypes.
  • Topics: cooking, home, gardening, politics, true-crime, police-rescue, medical, health-and-lifestyle (shown as Health), dating, science-and-technology, nature, travel, history, military-and-war, local-life, music-arts, entertainment-news, mystery-and-paranormal, engineering-and-machines, and business-and-money.
  • Hobbies (hobbies) holds motoring, fishing, and antiques. Each one is its own row, named after the facet.
  • Sport holds one facet per sport: afl, rugby-league, rugby-union, soccer, american-football, cricket, tennis, motorsport, horse-racing (with harness racing), greyhound-racing, rodeo (with bull riding and campdrafting), golf, netball, basketball, baseball, ice-hockey, cycling, combat-sports, surfing, swimming (with diving), and other-sport. other-sport is never a row. Sport facets have no prototypes.
  • shopping and religion take titles but are never rows.
  • createCategoryIndex sorts the groups with compareCategoryInfos: formats in catalogue order, then topics and sports by their shown label (localeCompare), with other-sport last. Settings, the Change categories sheet, and the hidden categories use this order. occasionsInYearOrderOf sorts the occasions by their date in the current year.

The country comes from the time zone (countryForTimeZone in src/zone-countries.js):

  • The local-life row is Life in <country>, with the English region name from Intl.DisplayNames and the before names such as United Kingdom. Its prototypes fill {in} with in <country>. With no known country, the row is Local life and {in} is empty.
  • sportLabelOf names each sport row by the sport: afl is Australian rules, rugby-league is Rugby league, rugby-union is Rugby union. soccer is Football (soccer) in au, Soccer in us and ca, else Football; american-football is Football in us and ca, else American football.

Title facts (titleFactsOf, recordFactsOf):

  • A title is a film only when one airing in the week is a film, no airing has a season, episode number, or episode title, and TVmaze found no show for it.
  • isFilmAiring in src/genre-enrichment.js returns false for a title with a live event word (isLiveEventTitle: awards, song contest, ceremony, telethon, festival, concert, gala, parade, new year's eve). A Wikidata film record makes an airing a film only when the airing has no episode details.
  • From the title_genres record: type:<TVmaze type>, the plain TVmaze genres (only for a tvmaze: source), wd:<Wikidata genre> tokens, and country:<code> as the origin. A lookup writes lookup:2 when TVmaze and Wikidata both answered, or lookup:partial with a 7-day expiry when Wikidata failed or was skipped; records with neither token are looked up again. After 5 Wikidata failures in a row, a run uses TVmaze only. rememberTvmazeShow keeps the wd:, country:, and lookup: tokens of the record. An episode title that reads like a description (isDescriptionLike) is not an episode detail (hasEpisodeDetails in src/episode-details.js). A film record wins over the live event words. Runtime origin is the TVmaze country, then Wikidata, then the known-shows list.

Tagging (tagTitle):

  1. titleKindOf sorts each title into film, kids, sport, fiction, factual, or unknown. kids is an OP-39 genre code in group 0x5, a kids genre tag, a kids guide genre (such as children's), or airings in kids slots only. A channel whose name says kids is a kids slot; when its name also says family, only airings before 19:00 local time (FAMILY_EVENING_HOUR) are. sport is a TVmaze type Sports, a sport genre tag, or a sport guide genre (SPORT_GUIDE). A live event title is factual. TVmaze Scripted is fiction; other TVmaze types are factual. Films take no category.
  2. An owner override (programme_category_overrides, read by loadTitleGenres as categoryOverride on the record) comes first. It sets the format and topics, and the origin still comes from the record or the list. The format sport-format with a code sets that sport code above the keywords; any other format removes the automatic sport code and makes the title factual. The tags carry custom: true.
  3. The known-shows list (knownShowOf) matches the exact show key of the title, after title aliases, and never a prefix, so Shark Tank never matches Shark Tank Australia. An entry is { format, topics, origin }. An array entry holds versions of one title; the version is picked by TVmaze country, then by a word of its channels in a channel name, then by the install country, else none. A list entry sets all the labels of the title. A list format of kids makes the title kids; a fiction format makes it fiction.
  4. A sport title takes its code from the title and channel names first (sportCodeOf). League, competition, and show names map to the sport, such as NRLW, State of Origin, and NRL 360 to rugby-league. The order is rugby-league, afl, rugby-union, american-football, cricket, soccer, then the other sports. A plain football is soccer, or american-football in us and ca, and no code in au. When no keyword matches, a guide genre that names the sport gives the code (GUIDE_SPORT_CODES). A sport title with fishing words is fishing. With no code, the list labels the title; with no list entry, the title is other-sport. A sport code never comes from TVmaze, the list, or embeddings.
  5. Without a list entry, evidenceLabelsOf reads the label rules. The format is the first of: a title pattern (titleFormatOf: named soap operas, panel shows, and lifestyle magazines), the exact genres (genreLabelsOf), the rules (ruleLabelsOf), and documentaries when hasStrongDocumentaryEvidence is true. The topics are the title-word topics, then the exact-genre topics, then the guide-genre and genre-byte topics, at most 2. A fiction title takes no topic.
  6. Exact genres: a TVmaze Panel Show type or a Wikidata panel game genre gives panel-shows. A TVmaze Comedy genre or a Wikidata sitcom or comedy genre gives comedy, before the TVmaze type. Then the type: Reality is reality, Game Show is quiz, Talk Show is talk-shows, and News is news. A fiction title with a TVmaze Crime, Legal, or Espionage genre is crime-drama, else soaps with Soap or a Wikidata soap opera or telenovela, else comedy with Comedy, else sci-fi-fantasy with Science-Fiction, Fantasy, or Supernatural, else drama. A factual TVmaze Reality show with Romance gets the topic dating; Romance alone gives nothing. TVmaze genres give topics: Supernatural, Food, DIY, Nature, Travel, Medical, Music, and History. A TVmaze type Documentary alone gives no format.
  7. documentaries needs a Wikidata genre with documentary, a guide genre such as documentary or documentary series, the ETSI byte 0x23, or the AU nibble 0xE. The guide genre documentary & factual is not enough.
  8. Guide genres are folded to lower case, with &amp; decoded and split on / (guideGenreKeysOf). special interest and entertainment give nothing.
  9. Genre bytes: the ETSI table, plus in au the nibbles 0xC (comedy), 0xD (drama), and 0xE (documentaries), which are reserved in ETSI. Free-to-air channels in Australia send ETSI bytes such as 0x14 for sitcoms, so the full Freeview AU table is not used. The nibble 0x8 gives politics.
  10. Embeddings run only when steps 3 to 9 give no topic and the format is not quiz, panel-shows, news, or kids. The title vector is the mean of up to 6 of its text vectors. A topic facet scores the highest dot product with its prototypes. A topic needs a score of 0.42 (TOPIC_FLOOR) or more, and a second topic must be within 0.08. Embeddings never give a format, a sport, fishing, or shopping.
  11. Weights: with a format and topics, the format weighs 0.4 and the topics share 0.6 (embedding topics by the ramp from 0.30 to 0.45). A format alone or topics alone weigh 1. A title is a row member only at a score of 0.42 or more; rule and list labels score 1.
  12. A news format with no topic makes the title a bulletin. mostSpecificCategoryOf gives the sport code, else the heaviest topic, else the format.

The audit test (test/for-you-category-audit.test.js) tags the 835 titles of test/fixtures/category-audit.json at the basic level and checks the most specific category against the owner's labels. scripts/build-known-shows.mjs builds the known-shows list and the fixture from one audit export.

The prototype sentences go into the embed run with the programme texts, so they share the model and the text_embeddings table. keepCategoryVectors sets their created_at after each run, so the 60-day prune keeps them. A catalogue change or a new country changes the sentences, so the next embed run embeds them. The worker keeps the tags per vector map and country, so a build with the same guide reuses them.

Affinity (householdEpisodesOf, householdCategoriesOf):

EventWeight
A recording, or record_request3
watch_start or watch_end2
suggestion_accepted1
programme_opened0.5
  • Each event kind counts once per episode. The episode is the season and episode number, else the episode title, else the start minute. An event with a recording_id uses the episode of that recording.
  • Each count decays with the 60-day half-life of profileOf.
  • A category sums the weight of each title times the title's tag weight. One title gives at most 30% of the category's uncapped sum. Sports have no cap.
  • The share is the category sum divided by the weight of all tagged titles. News bulletins are not in the divisor.

Rows (selectCategoryGroups, selectSportCodes):

  • A category row needs a share of 4% or more (ROW_SHARE), 3 or more titles with weight, and 4 or more upcoming members. At most 3 category rows show, highest share first.
  • The sport row needs codes with a share of 4% or more (ROW_SHARE), 1 or more titles, and 4 or more upcoming airings. One code gives a row named after the code; more codes give one row named Sport this week.
  • Candidates are upcoming members that are not films, not excluded like the other sections, and not shows the household already likes. A show with any hidden or switched-off category is in no category row. A card in a category row offers Hide for that row's category. A category row ranks the facets that hold 25% or more of the category weight first, leaves out the other facets, then ranks by the airing score. The sport row lists each airing: sportAiringKindOf ranks matches first, other shows about the sport next, and replays last, then by start time. It keeps at most 3 airings of one title.
  • A category row takes no show that an earlier section took. A row is left out when more than half of its first 12 items show in earlier sections, or when fewer than 4 items are left.
  • The section key is category-<key> (or sport for Sport this week); the title is the category name. Each item carries category (key, title, phrase) and a reason with its facet name. Why this? names the category share and the closest facet.

Taste (tasteOf): each title has categories (topics by weight, then the format, each { key, title, phrase, sport? }), hideCategory (the most specific one), and origin. The Home hero skips a show when any of its categories is hidden, and takes the highest category share for its order. The Hide item of the hero and the programme sheet names hideCategory.

Choices:

  • Each category row and the sport row has a ⋯ button in its header. It opens a sheet with More <category> and Hide <category>.
  • More (boost-category) sends category_boosted with the series key category-<key>; Undo sends category_unboosted. A boost multiplies the category share by 1.5 once; more boosts do not add to it. A mute clears the boost.
  • Hide <category> (hide-category), in the row menu and in the card menu of a category row, sends category_muted. Undo and Show again send category_unmuted. An unmute restores a boost that the mute cleared, and a newer boost cancels a mute.
  • A mute hides the row and multiplies the category share by 0.2 for 90 days, or until an unmute. After 90 days the share is back to normal. A mute or boost of sport covers every sport.
  • The setting for_you_categories_off holds a JSON list of the categories turned off in Settings. An off category has no row. Its tags do not count towards any share, and the tag weight of its titles leaves the divisor. The snapshot stamp categoriesOff starts a new build when the list changes.
  • GET /api/for-you/categories lists every category and sport (categorySettingsOf) with on and, for a format, format: true: off when in the list or muted in the last 90 days. The client groups them into Formats, Topics, Sport, and Seasonal. PUT /api/for-you/categories/:key with { on } updates the list; turning a category on also sends category_unmuted, and for a sport also unmutes sport.
  • GET /api/for-you/hidden lists the muted categories of the last 90 days (hiddenCategoriesOf) with the hidden shows; a category entry has the series key category:<key> and a categoryKey. DELETE /api/for-you/categories/:key/mute unmutes a category in the catalogue, or sport; any other key returns 404. DELETE /api/for-you/hidden/:seriesKey only handles shows.
  • The client hides the cards of a muted row at once (forYouMutedCategories in src/web/shared/for-you-session.js).
  • Migration 0052 deletes the theme_* rows of user_events and the setting for_you_themes_off, and creates programme_category_overrides (show_key, format, topics_json, updated_at).
  • GET /api/for-you/categories/show/:showKey (src/for-you-category-overrides.js) returns { showKey, custom, format, topics, origin, choices }. Without an override, the labels come from the last For you taste, else from tagging the title_genres record. origin is { code, name, source }, with source TVmaze, Wikidata, or built-in list. choices lists every format and the topics that can be rows.
  • PUT /api/for-you/categories/show/:showKey with { format, topics } saves an override. The format is a format key or null, the topics are at most 2 topic keys, and one of them must be set; anything else returns 400. { format: "sport-format", sport } saves a sport code instead; the code must be a sport facet, and topics cannot come with it. The row then holds format sport-format and topics_json { "sport": "<code>" }. DELETE removes the override. Both clear the For you cache. A title with a sport code has the format sport-format (formatOfTags), shown as Sport; it is a format with no row and no tag entry, so the code keeps its own row and switch. The Change categories sheet (src/web/components/categories-sheet.js) calls these routes from the show menu, the For you card menu, and the Home hero menu.

Seasonal rows ​

A seasonal row is a For you section for an occasion, such as Christmas or Anzac Day. seasonalSectionOf in src/for-you.js builds it in the For you worker, in the same build as the other sections. The household share does not count. One build has at most 1 seasonal row.

PartModuleMechanism
Occasionssrc/for-you-occasions.jsThe occasions, with countries, dates, windows, words, and prototype sentences
Datessrc/for-you-occasions.js, src/data/occasion-dates.jsonCode rules for fixed dates, nth weekdays, and Easter; a table for the lunar dates
TaggingoccasionMatchOf in src/for-you-occasions.jsChecks each airing against the words of one occasion
RowseasonalSectionOf in src/for-you.jsPicks the occasion, collects and ranks the airings, and checks the row size
VectorscategoryTextItems in src/for-you-engine.jsEmbeds the occasion prototype sentences with the category prototypes

Dates:

  • easterOf uses the anonymous Gregorian algorithm (Computus). nthWeekdayOf gives days such as the second Sunday in May.
  • src/data/occasion-dates.json holds the dates of Lunar New Year, Eid al-Fitr, Hanukkah, Diwali, and Matariki for 2026–2040. scripts/build-occasion-dates.mjs writes it. The script takes the path of a folder with date-holidays installed (npm install --no-save date-holidays). It gives the calendar code of date-holidays (ISC licence) its own rules for Lunar New Year (chinese 01-0-01), Eid al-Fitr (1 Shawwal), and Hanukkah (25 Kislev), and uses no date-holidays data. The Matariki dates are the list in Schedule 1 of the Te Kāhui o Matariki Public Holiday Act 2022 (MATARIKI_OBSERVANCE_DAYS, 2022–2052). It calculates Diwali from the new moon (Meeus, Astronomical Algorithms, chapter 49) in India Standard Time. Settings → Licences credits date-holidays and the Act. Freetvarr has no runtime date dependency. A test fails when the current year is within 3 years of the last year of the table.
  • The days are calendar days in the install time zone (localDayOf). A window runs from before days before the occasion day to after days after it. The first day of a day that starts with a daylight saving jump is its first real instant (localMidnightMsOf).
OccasionKeyCountriesDayWindow
Lunar New Yearlunar-new-yearAllTable5 before, 1 after
Waitangi Daywaitangi-daynz6 February3 before
Eid al-Fitreid-al-fitrAllTable5 before, 1 after
EastereasterAllEaster Sunday7 before, 1 after
Anzac Dayanzac-dayau, nz25 April3 before
Mother's Daymothers-dayau, nz, uk, usSecond Sunday in May; in uk, 21 days before Easter Sunday3 before
Father's Dayfathers-dayau, nz, uk, usFirst Sunday in September; in uk and us, third Sunday in June3 before
Fourth of Julyfourth-of-julyus4 July3 before
NAIDOC Weeknaidoc-weekauFirst Sunday in July7 after
MatarikimatarikinzTable7 before
Halloweenhalloweenau, nz, uk, us31 October7 before
DiwalidiwaliAllTable5 before, 1 after
Bonfire Nightbonfire-nightuk5 November4 before
Remembrance Dayremembrance-dayau, nz, uk11 November; in uk, the second Sunday in November3 before
ThanksgivingthanksgivingusFourth Thursday in November7 before
HanukkahhanukkahAllTable (25 Kislev)1 before, 7 after
ChristmaschristmasAll25 December24 before, 1 after
New Year's Evenew-years-eveAll31 December4 before, 1 after
  • The country comes from countryForTimeZone. With no known country, only the occasions for all countries show.
  • Anzac Day, NAIDOC Week, and Remembrance Day are commemorations (commemoration: true).

Tagging (occasionMatchOf), for each airing:

  1. An airing on a channel whose name matches SHOPPING_CHANNEL (such as shop, TVSN, QVC, Gemporia, or jewellery) never matches. A sport title never matches. A kids title never matches a commemoration. titleKindOf gives the kind.
  2. The occasion negatives are removed from the texts first: Easter Island, Christmas in June, Christmas in July, and Christmas Island.
  3. A word of the occasion in the title gives title. A word in the episode title gives episode. An episode title over 80 characters, or with a sentence break, counts as description text.
  4. Else the description needs 2 different words of the occasion (SYNOPSIS_TERMS) and gives synopsis. The supporting words (festival of lights for Diwali and Hanukkah) count as the second word only, and never in a title or episode title. An airing with a news category never matches by description.
  5. When the prototypes and the airing text have vectors, a synopsis match also needs a dot product of 0.35 or more with a prototype (OCCASION_PROTOTYPE_FLOOR).

Row (seasonalSectionOf):

  1. activeOccasionsOf lists the occasions whose window holds today, nearest occasion day first. An occasion turned off or muted is left out.
  2. For each occasion in that order, the row takes the allowed airings that match and start before the end of the last day of the window.
  3. The items skip the shows in ready-to-watch, finish-started, and coming-up. They rank title matches first, then episode, then synopsis, then by score, picture, and start time. One episode (title and episode title, else description) shows once. A title has at most 2 airings (SEASONAL_PER_TITLE). The row has up to 12 items.
  4. The first occasion with 4 or more items (SEASONAL_MIN_ITEMS) from 3 or more titles (SEASONAL_MIN_TITLES) gives the row. Else there is no seasonal row.
  5. The row goes after the last of ready-to-watch, finish-started, and coming-up. The sections after it drop the shows in the row. Category rows treat the row as an earlier section.
  6. The section key is seasonal-<occasion> and the title is the occasion title. Each item carries category (key, title, phrase, seasonal: true, and commemoration: true for a commemoration). Why this? gives the reason About <occasion>, the field that matched, and the occasion date (the first and last day of the window when it runs 2 or more days after the occasion day). The client keeps every airing in the row (perAiring, as for the sport row).

Choices:

  • The row menu has Hide <occasion> only. It sends category_muted with the series key category-seasonal-<occasion>. Undo and Show again send category_unmuted.
  • A mute lasts until the start of the next window of the occasion after the mute day (mutedUntilOf). When the table has no later date, the mute lasts 365 days.
  • GET /api/for-you/categories adds one entry per occasion of the install country (seasonalSettingsOf) with seasonal: true. The client lists them in the Seasonal group. PUT /api/for-you/categories/seasonal-<occasion> with { on } updates for_you_categories_off. An occasion of another country returns 404.
  • GET /api/for-you/hidden lists a muted occasion (hiddenOccasionsOf) with seasonal: true and until.

Home hero ​

src/home-hero-service.js builds a snapshot of hero slides for the Home page. GET /api/home/hero returns it with Cache-Control: no-store.

  1. readFeedWith reads the in-progress episode, new episodes, unwatched films, on-now entries, recordings, the watchlist, and the For you payload (waiting up to 5 s).
  2. rankedSlidesOf ranks candidates with heroCandidatesOf in src/web/home-hero.js. The For you payload carries taste (tasteOf in src/for-you.js): hidden show keys, show affinities, hidden and switched-off category groups, category shares, and the kind, sport code, categories, Hide category, and origin of each title. getCurrentTaste in src/for-you-service.js gives the last taste kept in memory (or the saved result's), merged with the hidden show keys, hidden category groups, and switched-off categories read from user_events and the settings at that moment, so a hide applies at the next build even when the For you rebuild takes longer than 5 s. GET /api/for-you/taste answers from the same function and never waits for a build.
  3. onNowPickOf picks the Live news or Live sport candidate: a programme on now on a pinned channel that is on air, with ETSI genre group 2 (news) or 4 (sport), not on the channel that records now. With taste, it drops hidden shows and shows with any hidden category (a sport category also when the sport group is hidden), counts genre group 4 only when the title kind is sport with a sport code (when taste has no titles, genre group 4 alone counts), and orders by 2 for a show affinity above 0 plus 1 when one of its categories has a share above 0, then by channel order. The candidate carries the title's Hide category in source.category.
  4. proofHeroPicture (src/hero-picture-proof.js) tests up to 6 pictures per slide at 1920 px and keeps up to 3. A picture passes at 640 px wide or more once its picture focus has settled.
  5. The snapshot keeps at most 10 candidates (HERO_CANDIDATE_LIMIT), one per show, and drops a slide with no proven picture. It is saved in the setting home_hero_snapshot.

The build runs 20 s after start, then every 5 min, and 3 s after invalidate(). A follow-up build runs at the next candidate end or recording start. invalidate() runs after a write request on a path in HOME_HERO_WRITE_PATHS, after each sync, and after each For you result. When a source read fails and the previous snapshot is under 2 h old, the build keeps it and sets stale.

The client (heroSlidesOf in src/web/home-hero.js) drops ended candidates and an on-now candidate whose show or category the browser has hidden, orders them by the hourly remix (src/web/hero-remix.js), and shows 5 slides (HERO_SLIDE_LIMIT). The on-now slide menu adds Hide this show (not_interested) and Hide with the category (category_muted), worded by dislikeLabelsOf in src/web/for-you.js; the programme sheet shows the same two items from GET /api/for-you/taste?title=.

Two indexes share one matching module, src/web/search-index.js.

IndexBuiltEntriesUsed by
Overlay indexIn the browser (buildShowSearch in src/web/search-results.js)Shows from GET /api/search/catalogue and series rules from GET /api/seriessrc/web/components/search-overlay.js (up to 8 show results)
Guide indexOn the server (buildGuideSearch in src/guide-search.js)One entry per show key in the guideGET /api/epg/search

An entry matches on its title and on extra names: curated nicknames (src/data/show-aliases.json), user names (show_nicknames, routes under /api/show-nicknames/:key), and learned names (title_known_as, from TVmaze AKAs and Wikidata aliases).

normaliseSearchText folds case and accents, removes apostrophes, and turns & and + into and. A query under 2 characters returns nothing. When the query starts with the and 2 or more characters follow, searchIndex also matches the rest of the query. Those extra hits score 20 below their normal score, so a full-query hit ranks first.

ReasonScoreRule
title100The query starts a word of the title
contains90The query without region words (au, australia, nz) occurs inside the title
alias, yours85The query starts a word of a nickname; an exact nickname scores 101
known-as80The query starts a word of a learned name
initials70A one-word query of 3 or more letters equals the title initials; only when direct matches are fewer than 3
fuzzy60 × containmentTrigram match with a typo allowance; only when nothing else matches; at most 3

Ties sort by the next air time, then recording count. searchGuideListings adds episode-title matches (score 50) for airings that have not ended, and stops at 100 results (GUIDE_RESULT_CAP).

Search: Result groups ​

guideGroupOf in src/guide-search.js tags each guide result with one group, using the first rule that fits:

GroupRule
scheduledThe program_id is in futureRecordings or activeRecordingIds of the live recording state (scheduledIdsOf in src/epg.js)
seriesseries_link matches a series rule from the recording state (seriesLinkOfProgramme)
for-youThe airing program_id is in the cached For you result (cachedForYouIds in src/for-you-service.js)
guideAny other airing

searchGuideListings sorts by group (GUIDE_GROUP_RANK), then score, then start, and applies the cap after the sort. GET /api/epg/search returns each result with its group. The For you ids come from the cache only; the search never computes For you.

The overlay (searchGroupsOf in src/web/search-results.js) adds a recordings group from the overlay index. It shows the groups in this order: scheduled, series, recordings, for-you, guide. Each group shows 5 rows (GROUP_ROW_LIMIT) until its Show all row expands it and moves focus to the sixth row. A new query collapses every group. The row shows the group total only when the source list is under its cap (MAX_SHOW_RESULTS 8, MAX_GUIDE_RESULTS 30). Enter opens the first result only when no search is running. On a touch screen ((hover: none) and (pointer: coarse)) with the on-screen keyboard showing (--keyboard-inset of 80 px or more), installTypeAheadEnter in src/web/shared/type-ahead-enter.js turns Enter in every [data-type-ahead] field into blur(), so the keyboard closes and nothing opens. While a text field has focus, installVisibleViewport sets --keyboard-inset, the height of the layout viewport that the on-screen keyboard covers. It keeps the inset after a blur until the keyboard has closed, so a tap does not move the list. The overlay keeps the previous results until new ones arrive, and shows the Searching state for at least 800 ms (remainingBusyMs). The guide view lists the server order, so scheduled results come first there too.

Jobs and health ​

Background work reports to the job registry in src/activity.js. The progress registry in src/progress.js holds the live numbers of one recording. The health checks in src/doctor.js read the state of the whole installation.

Activity ​

createActivity makes the in-memory registry; src/activity.js exports one instance as activity, and the functions trackJob, joinJob, and currentJob.

  • track(options, fn) starts a job, runs fn(handle), and finishes the job as done, or failed when fn throws. join({ kinds }) reuses the current job when its kind is in kinds.
  • A job started inside another job's async context gets that job as parentId. The context is an AsyncLocalStorage store.
  • A handle has step, update, total, advance, fact, item, log, outcome, fail, and finish. A job keeps up to 200 items and 100 log lines.
  • A job that works on one recording (import and ads) has a subject: { recordingId, title, season, episode, episodeTitle, channelName, airedAt, year, film, file }. src/activity-subject.js builds it from the import item (importSubjectOf) or from the recordings row (loadRecordingSubject); title is the show title the library groups the recording under, and film is true for a film import, a file inside the movies folder, or a show marked as a movie in programme_kind_overrides. Every list entry, detail, and job_runs row carries it; other jobs have subject: null.
  • plan and planEvery register scheduled jobs for UP NEXT: the sync, the health checks, the cache prune, and the ratings warm-up.

JOB_KINDS keys are sync, import, ads, guide, guide-pictures, guide-merge, history, for-you, hero, artwork, focus, ratings, prune, health, reclassify, and plex-watch. The kinds guide, guide-pictures, guide-merge, history, for-you, hero, artwork, focus, ratings, and plex-watch are quiet: a finished run replaces the earlier run of the same kind and state.

The recent list keeps finished jobs for 24 h and failed jobs for 7 days, in a ring of 200. A failed job is saved to job_runs, and startup loads the rows of the last 7 days.

Route (src/activity-routes.js)Returns
GET /api/activity{ running, upNext, recent, runningCount, recordings, sessions, server }
GET /api/activity/summary{ running }, the count of running jobs that are not quiet
GET /api/activity/streamA server-sent event stream with a ping every 15 s. topics lists jobs (the default) and art: jobs events at most every 500 ms, art events at most every 2 s from the cursor since (Live picture updates)
GET /api/activity/:idOne job with steps, facts, items, and log

measureJob(label, fn, job) in src/event-loop-lag.js times fn for the loop monitor, and runs it as a job when job is set. The monitor checks every 500 ms and records a stall at 100 ms or more. GET /api/health/loop returns the stalls, delay percentiles, and per-label job times.

Progress registry ​

src/progress.js holds an in-memory Map keyed by recording id. An entry exists while an import copy, an ad scan, or an ad cut runs: { phase, percent, etaSeconds, etaLabel, detail, startedAt, updatedAt }. phase is importing, scanning, cutting, or verifying. getProgress drops an entry not updated for 30 s. setProgress also updates the current Activity job.

  • The import copy reports percent from the copied size and an ETA from the copy rate.
  • The ad scan estimates its time as duration × 0.5 (SCAN_REALTIME_FACTOR in src/commercials.js) and caps percent at 99.
  • GET /api/recordings returns progress per row, and library rows return ad_progress. The recordings list polls every 2 s while any row has progress, else every 60 s.

Health checks ​

src/doctor.js holds the checks, the runner, the report cache, and the schedule. src/path-check.js holds the folder and hardlink probes. src/docker-host.js detects a Docker VM from the kernel release (OrbStack, Docker Desktop, or Docker on Windows).

runDoctor runs tvh.reach, then tvh.auth, then the other checks in parallel. A check that needs TVHeadend gets skip unless both first checks pass or warn. Each check returns status (pass, warn, fail, or skip), detail, fix, and an optional action, with an 8 s timeout (DEFAULT_TIMEOUT_MS).

IdChecks
tvh.reach, tvh.auth, tvh.rights, tvh.openTVHeadend answers (warn below API version 19); the login works; the rights probes answer without 403; no open admin entry
tvh.tuners, tvh.channelsAt least one tuner turned on; at least one channel
tvh.ruleswarn when the series rule title change failed for a rule (read from the setting autorec_anchor_failed, no TVHeadend call)
guide.depth, guide.logosfail when the guide ends within 12 h, warn within 48 h; share of channels with an icon
guide.picturesReads the guide, the per-host results that guideImageHosts (src/programme-images.js) keeps of the last 200 picture downloads per host, the title keys with a saved guide picture, and the title keys with a landscape art_resolutions row that has an origin, with no request. Takes each title key airing in the next 48 h. A title has a picture when it has a saved copy or a resolved origin, or an airing names a picture on a host that is not failing (a host fails with at least 10 downloads and half or more failed). pass at 80% or more, with each failing host and the share of its titles that other sources cover; warn below 80% (fix: internet access and Missing pictures, action opens Film and TV info); warn when Freeview pictures are off (freeviewPictureProblem). Skips when no programme airs in the next 48 h
guide.sourcesReads the guide source overview, and the XMLTV URL grabber when guide_repoint is confirmed and TVHeadend answers. Skips with no plan. The detail gives each source score (the share of channels not degraded), days ahead, and last build with coverage. warn when guide_merged_feed is on and merged.xml.gz is missing or older than 12 h, the primary source is degraded, a named or pinned source is degraded (action Switch to Automatic, POST /api/guide-sources/automatic), or the grabber is not enabled with a Freetvarr feed address after the confirm step
paths.recordings, paths.match, paths.media, paths.write, paths.mounted, paths.hardlinkReadable recordings folder; DVR profile path equals tvh_recordings_path; writable media folder; writable recordings and one-off folders (warns only); no library folder empty while imported rows point into it; imports hardlink
disk.freefail under 10 GB free; warn under 20 GB or 10%
plex.reach, plex.oneoffsThe TV section exists and reads the media folder; warn when the Plex one-off library has items and the one-off folder has none
sync.healthThe cron schedule runs; the last sync is not error or partial
live.encoder, live.streamsffmpeg on the PATH; the stream limit is not above the benchmark
ads.comskipcomskip, ffmpeg, and ffprobe on the PATH when ad removal is on
host.envA known time zone and a LAN address
host.nameswarn when Freetvarr was opened in the last 14 days by a name the Host check does not allow, with Allow <name> for the most used name with page_load that parseAllowedHosts accepts (else Open setup), or when the list holds *; skip outside the running server

Each id links to its guide section, for example /guide/doctor#tvh-reach. getDoctorReport caches the report for 15 s. scheduleDoctorChecks runs a fresh report 2 min after startup and every 3 h, with the same live encoder and stream readings as GET /api/doctor. guide.depth also warns when the enabled XMLTV URL grabber reads a Freetvarr feed address with another host or port than Freetvarr now has, and names both. GET /api/doctor returns the report (?fresh=1 skips the cache), and npm run doctor (scripts/doctor.mjs) prints it and exits 1 when a check fails.

A check can return summary, a sentence for the health summary (guide.pictures: Guide pictures from <host> fail to load.). getHealthSummary (src/health-summary.js) builds one level (ok, warn, or fail) from the TVHeadend connection, failed recordings in the last day, the last sync, and the doctor checks of the last 6 h. It is cached for 10 s and served at GET /api/health-summary. src/web-assets.js inlines it into index.html as <meta name="freetvarr-health">; the client then polls every 60 s.

Web client ​

The client is native ES modules served as static files. Vue 3 compiles the in-browser templates at run time from /vendor/vue.esm-browser.prod.js. There is no bundler.

PathContent
src/web/index.htmlShell with the module preloads, fonts, and stylesheets
src/web/app.jsCreates the Vue app, registers global components, and mounts it
src/web/route-table.js, src/web/shared/router.jsHash routes, aliases, nav entries, and the reactive route
src/web/view-modules.jsVIEW_ENTRIES: the lazy-loaded views
src/web/views/, src/web/components/, src/web/shared/Pages, shared components, and state, API client, and session modules
src/web/styles/, src/web/styles.cssPlain stylesheets
src/web/tailwind.cssGenerated by npm run build:css (Tailwind CSS v4); test/tailwind-css.test.js checks it
src/web/view-preloads.jsGenerated by node scripts/generate-view-preloads.mjs; test/view-preloads.test.js checks it

Both generated files are committed. src/web/styles.css has no cascade layer, so its rules override Tailwind utilities in @layer utilities.

Assets and build id ​

  • src/build-id.js hashes (SHA-256) the version and every .html, .js, .css, and .woff2 file under src/web. The first 12 hex characters are the build id.
  • src/web-assets.js rewrites each asset URL to ?v=<build>. A request with the current build gets Cache-Control: public, max-age=31536000, immutable; any other request, and index.html, gets no-cache.
  • index.html gets a modulepreload link for each module in the static import graph of /app.js, and the meta tags freetvarr-build, freetvarr-health, and freetvarr-time-zone.
  • /vendor serves vue.esm-browser.prod.js, hls.mjs, and hls.worker.js out of node_modules.
  • Every /api response carries X-Freetvarr-Build. src/web/shared/api.js compares it with the loaded build; a mismatch shows the update card (src/web/components/stale-build-banner.js).

Routing and layout ​

  • Routes use the URL hash. The views are home, for-you, live, guide, recordings, settings, and welcome; any other hash resolves to home.
  • src/web/app.js loads each view except home through defineAsyncComponent and prefetches them at idle time.
  • The phone layout (PHONE_LAYOUT_QUERY: (max-width: 767px), (max-height: 500px)) has a bottom tab bar and a 16 px gutter. Larger screens have a left rail and a 32 px gutter, or 40 px from 1280px.
  • Lists show tables on wide screens and article.list-row cards inside .list-rows on narrow screens.
  • src/web/manifest.webmanifest sets display: standalone. src/web has no service worker.

Security model ​

SECURITY.md holds the reporting route and the accepted residual risks. Sign-in is off by default (Sign-in). Every protection below assumes a trusted LAN.

Response headers ​

Helmet sets the headers in src/server.js, with useDefaults: false on the Content Security Policy:

DirectiveValue
default-src'self'
script-src'self' 'unsafe-eval' (Vue compiles templates with Function)
style-src'self' 'unsafe-inline'
img-src'self' data:
media-src, worker-src'self' blob:
connect-src'self' https://api.github.com
object-src, frame-ancestors'none'
base-uri, form-action'self'
  • crossOriginEmbedderPolicy is false. hsts is false; the service uses plain HTTP.
  • X-Powered-By is disabled. trust proxy is loopback plus the addresses in FREETVARR_TRUSTED_PROXIES (trustProxyOf), so req.ip and the rate limits use the client address behind a trusted proxy. case sensitive routing is on, for the app and for the router in src/web-assets.js, so /INDEX.HTML and /API/... match no route.
  • Every response carries X-Robots-Tag: noindex, nofollow.

Host check ​

A DNS-rebinding page in a LAN browser shares one origin with Freetvarr after the rebind, so CSRF does not stop it. The Host header of each of its requests carries the attacker's name. src/host-gate.js checks that name and refuses an unknown name with 403.

app.use(hostGate) runs directly after the X-Robots-Tag middleware, before the /api build header, trackRequests, compression, the body parsers, cookieParser, and every route. GET and HEAD requests to /healthz and /guide/xmltv.xml skip the check; both return no settings. Every other path and method is checked.

A hostname here is the name part of the Host header, without the port. normaliseHostname lowercases it and removes the port, the IPv6 brackets, and one trailing dot. The gate checks the raw Host header. When X-Forwarded-Host comes from a peer that trust proxy trusts (loopback, or an address in FREETVARR_TRUSTED_PROXIES), the gate also checks req.hostname, which is then the first X-Forwarded-Host value. Both names must pass, so a rebinding page cannot hide its Host behind a forged X-Forwarded-Host: localhost. A forwarded value with no name, such as :3733, is refused. The 403 page leaves out the IP link when the local address is loopback or in 172.16.0.0/12 (a Docker bridge network). isAllowedHost accepts a name when any rule matches:

RuleExamplesWhy a rebinding attacker cannot use it
Empty HostHTTP/1.0 clientsBrowsers always send one
IP literal (net.isIP)192.168.1.10, [fe80::1], ::ffff:192.168.1.10No DNS answer to rebind
One labelnas, freetvarr, diskstationNo public DNS name has one label
Private-use suffix.localhost, .local, .lan, .home, .home.arpa, .internal, .localdomain, .corpNot delegated in the public root zone
Machine nameos.hostname() and its first labelThe host's own name under network_mode: host
Extra namesThe setting allowed_hosts joined with FREETVARR_ALLOWED_HOSTSThe user lists them

parseAllowedHosts splits on commas, spaces, and new lines. An entry is a hostname (labels of letters, digits, -, and _, up to 253 characters) or *. plus a hostname of at least two labels, which matches subdomains only (*.com is invalid). A scheme, port, path, or address range is invalid. One * entry accepts any name, and host.names warns. createAllowedHosts keeps both lists in memory, so a request never reads the database; PUT /api/allowed-hosts saves the setting as newline-joined text and updates the memory copy at once. Invalid entries in FREETVARR_ALLOWED_HOSTS log a warning and are ignored.

A refused request gets Cache-Control: no-store. When req.accepts(['json', 'html']) picks html (a page load), the body is a static page with no scripts from src/host-refused-page.js. It shows the refused name (HTML-escaped), a link to http://<req.socket.localAddress>:<localPort>/ (left out when that address is loopback, as behind a same-host proxy), the path to Allowed hostnames, and a note for Home Screen apps. Every other request gets { error, code: 'host-not-allowed' }. The gate records the name before it answers, so Health opened by IP address can offer Allow <name>. When apiCall or the CSRF token fetch in src/web/shared/api.js gets 403 with that code (isHostRefusal), the page calls location.reload(), which shows the refused page in a tab left open across the update.

createSeenHosts records each refused name with its request count, first and last time, the client address, and page_load. page_load is true once a request for the name had Sec-Fetch-Mode: navigate, Sec-Fetch-Dest: document, and Sec-Fetch-Site: none (isUserPageLoad): the user opened the page from the address bar, a bookmark, or the Home Screen. A rebinding page reaches Freetvarr with fetch, sub-resources, or navigations it starts itself, which carry another Sec-Fetch-Site. A browser without Fetch Metadata never sets the flag. The tracker keeps the newest 50 names. It saves them as JSON in the setting host_check_seen at once for a new name (at most once a minute), otherwise at most once an hour, and at shutdown, and reads them back at startup. It logs [host-check] refused <name> from <ip>; add it to Allowed hostnames if you use it once per name per day, and at most 10 such lines an hour across all names; the next line is [host-check] more refused names this hour; see Health, then nothing until the hour ends. Names are cut to 253 characters. Reset awaits seenHosts.forget() (cancel the pending save, wait for one in flight, empty the list) before it deletes the settings.

RouteBodyResult
GET /api/allowed-hostsNone{ hosts, env_hosts, any_host, seen }; seen holds the names of the last 14 days that the list does not allow
PUT /api/allowed-hosts{ hosts }Saves the list; 400 with { error } naming each invalid entry, or past 100 names
POST /api/allowed-hosts/allow/:nameNoneAdds one hostname (the Health action); 400 for * or an invalid name

The two write routes use epgLimiter and doubleCsrfProtection. The gate runs first, so a rebinding page cannot add its own name. Settings → SYSTEM → Setup → Allowed hostnames (src/web/components/allowed-hosts-setting.js) lists the saved names, then the .env names marked from the .env file, which the page cannot remove.

Sign-in ​

src/sign-in-store.js keeps the sign-in state in the file login in the config folder (the folder of DB_PATH), written with mode 0600 through a temporary file and a rename. Reset does not touch it. The file is JSON:

FieldValue
passwordscrypt$32768$8$1$<salt>$<hash>: a 16-byte random salt and a 64-byte scrypt hash, base64url
sessionKey32 random bytes, base64url; the HMAC-SHA256 key of the session cookie
apiKeyThe SHA-256 digest of the API key, base64url, or null
trustedHeadertailscale-user-login, remote-user, or null

Sign-in is on when the file holds a password and FREETVARR_LOGIN is not off, 0, false, or no. A file that cannot be read or parsed stops the server with a message that names the file. A new password and Sign out other devices replace sessionKey, which ends every session.

createSignInGate (src/sign-in-routes.js) runs directly after cookieParser and before observeUserEvents and every route. With sign-in off it passes every request. Otherwise it first deletes the tailscale-user-login and remote-user headers from a request whose socket address is not trusted, so no route sees them. It then signs a request in by the first of these that matches, sets req.signedInVia, and passes it:

  1. Authorization: Bearer <key> whose digest equals apiKey (via: 'key').
  2. The trustedHeader header, not empty, when req.socket.remoteAddress is loopback or in FREETVARR_TRUSTED_PROXIES (via: 'header'; req.signedInAs holds the value). The check uses the socket address, not req.ip, so X-Forwarded-For cannot change it.
  3. The cookie freetvarr.session, <issuedAt>.<HMAC of issuedAt>, younger than 180 days (via: 'cookie'). A cookie older than 24 h gets a fresh one, so a device stays signed in for 180 days after its last visit.

A request that is not signed in passes only on a canonical path: one that path.posix.normalize leaves the same, in lowercase, with no % or \. The open paths are GET or HEAD of /healthz, /guide/xmltv.xml, /login, /api/live/<32 hex>/<file>, /api/play/<32 hex>/<file>, and any path outside /api/ with a file extension other than .html; and POST /login. A page load of any other path gets 302 to /login, so / and /index.html (the page shell, with its health and time-zone metas) are never sent before sign-in. Every other request gets 401 with { error, code: 'sign-in-required' }. apiCall and the CSRF token fetch in src/web/shared/api.js send the page to /login on that code.

GET /login sends a page with no scripts from src/sign-in-page.js, built from the app style sheets. POST /login takes the form field password, refuses Sec-Fetch-Site other than same-origin or none with 403, and allows 5 tries a minute per client. A right password sets the session cookie (HttpOnly, SameSite=Lax, Secure when req.secure, Max-Age 180 days) and redirects to / with 303. A wrong one sends the page again with 401.

doubleCsrfProtection is skipCsrfForApiKey(doubleCsrfCheck): a request signed in with the API key skips the CSRF check.

RouteBodyResult
GET /api/sign-inNone{ on, password_set, turned_off_by_env, api_key_set, trusted_header, trusted_headers, signed_in_via, signed_in_as, proxy_identity }
PUT /api/sign-in/password{ password }Sets the password (8–256 characters, else 400), replaces sessionKey, and signs this browser in
DELETE /api/sign-inNoneDeletes the file and the cookie
POST /api/sign-in/sign-out-othersNoneReplaces sessionKey and signs this browser in again
POST /api/sign-in/api-keyNoneMakes a 32-byte key and returns it once as api_key
DELETE /api/sign-in/api-keyNoneDeletes the key
PUT /api/sign-in/trusted-header{ header }Saves tailscale-user-login, remote-user, or an empty value; 400 for any other
POST /api/sign-outNoneDeletes the cookie and returns { path: '/login' }

The write routes use epgLimiter and doubleCsrfProtection, and refuse a request signed in with the API key with 403. The routes that need a password answer 409 without one. While a password is set and FREETVARR_LOGIN is not off, PUT /api/sign-in/password, DELETE /api/sign-in, POST /api/sign-in/api-key, and PUT /api/sign-in/trusted-header also need the body field current_password; a missing or wrong one gets 403 with code: 'current-password-wrong', and these checks allow 5 tries a minute per client. Settings → SYSTEM → Sign-in (src/web/views/sign-in-settings-view.js) shows them. The guide page is Sign-in.

CSRF ​

  • csrf-csrf protects the state-changing routes with doubleCsrfProtection (double-submit cookie).
  • GET /api/csrf-token returns { token }. The browser sends it in the x-csrf-token header, and retries once with a fresh token after a 403 whose message matches /csrf/i.
  • The cookie is freetvarr.x-csrf with httpOnly: true, sameSite: 'strict', and secure: false. getSessionIdentifier returns the constant 'freetvarr'.

The secret comes from CSRF_SECRET when set; a value under 32 characters logs a warning. Otherwise src/csrf-secret.js reads the file csrf-secret in the folder of DB_PATH. When the file is missing, it writes 32 random bytes as hex with mode 0600. When the folder is not writable, the server exits with code 1.

Rate limits ​

express-rate-limit runs each limiter per client address with a window of 60 s. createRateLimiter in src/rate-limits.js builds every limiter; a refused request gets 429 with the JSON body { error, code: 'rate-limited' }. In the web client, src/web/shared/request-errors.js turns a 429 with no JSON into the same plain message, and a request that cannot reach the server into an error with status 0 and code offline.

LimiterLimitRoutes
syncLimiter5POST /api/sync, POST /api/reset
rowActionLimiter30Recording library (import) and TVHeadend-delete routes, ad-scan and restore
setupCheckLimiter20TVHeadend test, detect, shows list, and path check, Plex discovery and library create
epgLimiter60Record and cancel routes, library rule and delete routes, Plex, Sonarr, and Radarr settings, watchlist, artwork-choice writes, TMDB key, allowed hostnames, nicknames, programme kind, For you
liveLimiter20POST /api/live, the stream limit routes, POST /api/live/benchmark
playLimiter30Playback start and From the start
playPingLimiter120Position, heartbeat, attention, watched marks, viewing history
doctorLimiter10GET /api/doctor, POST /api/doctor/one-off-placeholder
bootstrapLimiter, bootstrapStatusLimiter10, 30TVHeadend setup writes and reads
guideFeedLimiter10GET /guide/xmltv.xml
ratingsLimiter240Ratings, credits, artwork-choice reads
showImageLimiter1200GET /api/epg/show-image
Sign-in tries5POST /login; a refused try gets the sign-in page with 429

Errors and paths ​

  • The terminal error handler responds with err.statusCode, err.status, or 500 and { "error": <message> }. It never sends a stack trace.
  • A process.on('unhandledRejection') handler logs the reason and does not exit.
  • POST /api/shows and PATCH /api/shows/:id reject dest_folder and season_template values that start with / or \ or contain .., and an empty, blank, or . show_pattern or dest_folder (showFieldErrorOf in src/show-fields.js). Import paths go through guardWithinRoot.
  • Live and playback file routes accept only a 32-hex session id and the HLS file names.
  • Library delete checks each target against the library roots with realpath and lstat (Library delete).
  • POST /api/settings checks each root it changes (rootSettingsProblem in src/path-check.js). media_root, oneoff_root, movies_root, and recordings_root must be absolute, existing folders, and not /, /etc, /proc, /sys, /dev, /app, the config folder, a folder inside it, or a parent of it. tvh_recordings_path must be absolute and not /. A failure gives 400 with { field, error } and saves nothing.
  • Image routes send only JPEG, PNG, WebP, or GIF, with the type read from the image bytes, never from the upstream header, and add Content-Security-Policy: default-src 'none'; sandbox. Anything else answers 404. TVHeadend images and channel logos may be SVG (up to 1 MB); createThumbnailStore renders an SVG with sharp to WebP at the requested width, with the density capped between 1 and 2400 dpi, so only raster pixels leave Freetvarr. An SVG with a filter (a <filter> element, or a filter attribute or style) is refused unrendered. SVG renders run one at a time (createRenderQueue), with up to 20 waiting; a request past that answers 404 and is not marked as failed. Any other body that holds an <svg> tag never reaches sharp. A thumbnail that cannot be resized gives no image, and the store skips that thumbnail for 10 min.

Credential storage ​

The TVHeadend password (tvh_password), the Plex token (plex_token), the Sonarr and Radarr keys, and the TMDB key are plain text in the settings table. The read routes return booleans (tvh_password_set, plex_token_set, hasKey, key_set), never the values. At startup the server sets mode 0600 on state.db, state.db-wal, and state.db-shm.

Secret binding ​

src/url-binding.js holds sameOrigin(a, b) (scheme, lowercase host, and port; the path and a trailing slash do not count) and isThisMachineHost(host) (loopback, host.docker.internal, or an address from os.networkInterfaces()). Each stored secret goes only to the URL it was saved with:

SecretSent toAddress change with no secret in the request
tvh_passwordA URL with the origin of tvh_urlPOST /api/settings and a passing POST /api/tvh-test delete it and return cleared: ['tvh_password']
plex_tokenNo plex_token_scope: a URL with the origin of plex_url. Scope this-machine (a detected token): a URL on this machinePOST /api/settings keeps it when the new URL passes the rule and then clears the scope; else deletes it and returns cleared: ['plex_token']
sonarr_api_key, radarr_api_keyThe saved URL; the config.xml key only to a URL on this machine at the config.xml portPUT /api/arr empties the saved key and returns cleared: ['sonarr_api_key'] or ['radarr_api_key']

A secret typed in the same request is always used as sent. A move between two addresses that are both on this machine keeps an unscoped Plex token and a saved Sonarr or Radarr key (keepsSecretBinding). GET /api/settings reports plex_token_set from the bound token (storedPlexToken), so a detected token that no saved URL can use shows as not set. After a save that returns cleared, Settings shows Saved. Enter the <secret> again for the new address. in a toast that stays until the user closes it (clearedSecretToastOf in src/web/save-notice.js), and the wizard Plex step stays open with that line under the token field. A refused root folder marks its field in Settings with the error (rootFieldErrorOf).

Supply chain ​

ControlSetting
.npmrcignore-scripts=true, engine-strict=true, audit-level=high, save-exact=true, package-lock=true, min-release-age=3
Installnpm ci from the committed package-lock.json
Native buildsnpm run rebuild:natives rebuilds only better-sqlite3 with --ignore-scripts=false
Signaturesnpm run setup ends with npm audit signatures
ActionsEvery uses: names a full commit SHA with the tag in a comment; test/workflow-pins.test.js fails on a tag-only line
Updates.github/dependabot.yml opens weekly pull requests for the github-actions ecosystem

Full environment reference ​

Runtime variables ​

Process code reads these variables. For path variables, a stored setting wins, then the variable, then the default.

VariableDefaultMeaning
PORT3733HTTP port
DB_PATH<repo>/config/state.db (/config/state.db in the image)SQLite file; its folder is the config folder (Config folder)
ARTWORK_PATH<config folder>/artworkFolder for saved artwork
TZUnsetTime zone fallback (Time zone)
CSRF_SECRETUnsetReplaces the generated secret file (CSRF)
TVH_URLUnsetdetectServers returns this address and probes nothing
MEDIA_ROOT/media/tvDefault for the setting media_root (TV library)
ONEOFF_ROOT/media/one-offsDefault for the setting oneoff_root
MOVIES_ROOTEmptyDefault for the setting movies_root; empty sends films to the one-off folder. Saving an empty movies_root deletes the setting and sets last_movies_root to this value (or deletes it when this is empty), so rebaseFilePaths leaves filed films alone
RECORDINGS_ROOT/recordingsDefault for the setting recordings_root (TVHeadend files as Freetvarr sees them)
TVH_RECORDINGS_PATH/recordingsDefault for the setting tvh_recordings_path (the prefix TVHeadend reports)
PLEX_PREFS_PATH/plex/Library/Application Support/Plex Media Server/Preferences.xmlPlex Preferences.xml for token detection
SONARR_CONFIG_PATH, RADARR_CONFIG_PATH/sonarr-config.xml, /radarr-config.xmlThe app config.xml for the API key, port, and URL base
LIVE_TV_BUFFER_MINUTES30Minutes of live TV kept for pause and rewind; clamped to 0–120
LIVE_TV_TRANSCODEautoauto, hardware, software, or copy
LIVE_TV_VAAPI_DEVICE/dev/dri/renderD128VAAPI render device
LIVE_TV_MAX_SESSIONSUnsetCap on live streams and recording playbacks (Stream limit)
IMAGE_CACHE_MAX_MB100Megabytes of resized images in image-cache/
FREETVARR_ALLOWED_HOSTSUnsetExtra names Freetvarr answers to, joined with the setting allowed_hosts (Host check)
FREETVARR_LOGINUnsetoff, 0, false, or no turns sign-in off and keeps the password (Sign-in)
FREETVARR_TRUSTED_PROXIESUnsetAddresses, separated by commas or spaces, whose sign-in proxy header Freetvarr reads, with loopback (Sign-in)
PATHSystemThe health checks search it for comskip, ffmpeg, and ffprobe

NODE_ENV is production in the image and in compose; Express reads it, src/ does not.

Time zone ​

resolveTimeZone in src/time-zone.js takes the stored setting time_zone when it names a known zone, else TZ, else the system zone. At startup and on each save, a stored zone is copied to process.env.TZ. GET /api/settings returns tz, time_zone, tz_source, and tz_env. The browser reads the zone from the freetvarr-time-zone meta tag.

Compose variables ​

Compose reads these variables from .env; the container does not see them.

VariableDefaultMeaning
PUID, PGID1000Owner of the files; user: of Freetvarr and the PUID and PGID of TVHeadend and Plex
CONFIG_PATH./configHost root of the config folders
DATA_PATH./dataHost root of recordings/ and media/
FREETVARR_PORT3733Becomes PORT in the container
PLEX_PREFS_PATHUnsetHost path of Preferences.xml; mounted at /plex-preferences.xml, or /dev/null
SONARR_CONFIG_PATH, RADARR_CONFIG_PATHUnsetHost paths of config.xml; mounted read-only, or /dev/null
COMPOSE_PROFILESUnsetplex adds the plex service
PLEX_CLAIMUnsetClaim token for the plex service
RENDER_GIDNoneGroup id of /dev/dri/renderD128; required by docker-compose.hwaccel.example.yml

Compose passes TZ, CSRF_SECRET, TVH_URL, MOVIES_ROOT, IMAGE_CACHE_MAX_MB, FREETVARR_ALLOWED_HOSTS, and the LIVE_TV_* variables from .env to the container. It sets NODE_ENV, DB_PATH=/config/state.db, MEDIA_ROOT, ONEOFF_ROOT, RECORDINGS_ROOT, and TVH_RECORDINGS_PATH itself.

Docker deployment ​

Image ​

Dockerfile builds FROM node:24-bookworm-slim, pinned to the multi-arch index digest. Dependabot (.github/dependabot.yml, docker entry, weekly, 7 days cooldown) opens a pull request when the digest changes:

  1. Install tini, tzdata, wget, comskip, and ffmpeg, plus mesa-va-drivers and, on amd64 only, intel-media-va-driver-non-free (VAAPI drivers).
  2. Run npm install -g npm@11.15.0, npm ci --omit=dev --ignore-scripts, and npm run rebuild:natives.
  3. Remove the onnxruntime-node binaries of other platforms, onnxruntime-web, and the unused @huggingface/transformers builds.
  4. Copy the repository, set NODE_ENV=production and DB_PATH=/config/state.db, and EXPOSE 3733.
  5. Create /config, owned by node, and switch to USER node (uid 1000). The compose user: line overrides the user.
ItemValue
HEALTHCHECK--interval=30s --timeout=5s --start-period=20s --retries=3, wget -q --spider http://127.0.0.1:${PORT:-3733}/healthz
ENTRYPOINT/usr/bin/tini -- /app/docker-entrypoint.sh (tini forwards SIGTERM)
docker-entrypoint.shConfig folder checks, node node_modules/.bin/knex migrate:latest, then exec node src/server.js

Before the migration, docker-entrypoint.sh exits with code 1 in these cases:

  • /app/config/state.db exists and DB_PATH points elsewhere: the message says to move the database to the folder of DB_PATH.
  • The config folder, or an existing state.db, state.db-wal, state.db-shm, or csrf-secret in it, is not writable: the message gives the user id, the owner of the folder, the user: line to set when that owner is not root, and sudo chown -R <uid>:<gid> <the folder mounted at /config>.

.github/workflows/image.yml builds natively on ubuntu-24.04 (amd64) and ubuntu-24.04-arm (arm64). It tests that better-sqlite3 loads, that ffmpeg and comskip exist, and that /healthz answers in three runs: the image defaults (with no DB_PATH), --user 1026:100 --cap-drop ALL --security-opt no-new-privileges with a writable /config, and a root-owned /config that must exit 1 with the chown message. A tag X.Y.Z (no v) publishes X.Y.Z and latest to ghcr.io/furey/freetvarr (GitHub Container Registry). A push to develop that changes an image input, a pull request that changes the Dockerfile, and a manual run build and test without a publish.

Compose services ​

install.sh downloads docker-compose.example.yml as docker-compose.yml, writes .env, creates CONFIG_PATH and DATA_PATH, and starts the services.

ServiceImageNetworkStarts after
initbusybox:stablenoneNone
tvheadendlscr.io/linuxserver/tvheadend:latesthostinit
freetvarrghcr.io/furey/freetvarr:latesthostinit and tvheadend
plex (profile plex)lscr.io/linuxserver/plex:latesthostinit
  • The services publish no ports:. Freetvarr binds ${FREETVARR_PORT} on the host; TVHeadend uses 9981 (HTTP) and 9982 (HTSP); Plex uses 32400. Host networking lets TVHeadend find a network tuner by UDP broadcast.
  • init creates /config/tvheadend, /config/freetvarr, /config/plex, /data/recordings, /data/media/tv, and /data/media/one-offs, owned by PUID:PGID.
  • freetvarr runs as PUID:PGID (user:), drops every Linux capability (cap_drop: [ALL]), and sets no-new-privileges. init runs chown as root, and the linuxserver images start as root, so they keep the Docker defaults.
  • docker-compose.dev.yml builds freetvarr:dev from the checkout. docker-compose.hwaccel.example.yml, saved as docker-compose.override.yml, maps /dev/dri and adds the group ${RENDER_GID}.
ServiceContainer pathHost pathContent
tvheadend/config, /recordings${CONFIG_PATH}/tvheadend, ${DATA_PATH}/recordingsTVHeadend settings and DVR entries; .ts recordings
freetvarr/config${CONFIG_PATH}/freetvarrThe config folder
freetvarr/data${DATA_PATH}/data/recordings and /data/media/*
freetvarr/plex, /plex-preferences.xml, /sonarr-config.xml, /radarr-config.xml (read-only)${CONFIG_PATH}/plex and the compose path variablesPlex token and app API keys
plex/config, /data/media${CONFIG_PATH}/plex, ${DATA_PATH}/mediaPlex settings; the library at the paths Freetvarr uses

IMPORTANT

Freetvarr mounts ${DATA_PATH} once at /data. Linux refuses a hardlink between two bind mounts, so an import across two mounts is a copy.

Build and test ​

Local development ​

sh
git clone https://github.com/furey/freetvarr
cd freetvarr
cp .env.example .env
npm run setup
npm start
  • cp .env.example .env is optional. npm start and npm run dev load ./.env with Node --env-file-if-exists.
  • npm run setup installs from the lockfile, rebuilds better-sqlite3, and verifies signatures.
  • npm start runs npm run migrate (creates ./config and applies the migrations), then listens on http://localhost:3733.
  • package.json sets engines to Node >=24.0.0 and npm >=11.10.0. The volta block (Volta) pins Node 24.21.0 and npm 11.15.0. better-sqlite3 is pinned to 12.11.1, which has prebuilt binaries for Node 24.
  • The TVHeadend address is a runtime setting (tvh_url), set in the wizard.

Scripts ​

CommandRuns
npm run setupnpm ci --ignore-scripts && npm run rebuild:natives && npm audit signatures
npm run migratemkdir -p config && knex migrate:latest
npm run migrate:refreshDeletes ./config/state.db, then migrates
npm startnpm run migrate && node --env-file-if-exists=.env src/server.js
npm run devThe same with --watch
npm run build:csstailwindcss -i src/tailwind.css -o src/web/tailwind.css --minify
npm testnode --test --import ./test/setup/no-outbound-network.js 'test/*.test.js'
npm run test:integrationnode --test --import ./test/setup/no-outbound-network.js --test-concurrency=1 'test/integration/*.test.js'
npm run doctorThe health checks against the configured database (Health checks)

Tests ​

The runner is the Node test runner; there are no test dependencies.

  • test/*.test.js holds the unit tests, named after the module they cover (for example test/sync.test.js, test/live-*.test.js).
  • test/setup/no-outbound-network.js loads before every test file. It throws ENETBLOCKED for any connection to a non-loopback host and fails the run when one was blocked.
  • test/fixtures/ holds recorded TVHeadend, Plex, and TVmaze responses.
  • test/integration/ tests bootstrap, guide, and channel setup against a real lscr.io/linuxserver/tvheadend:latest container that tvheadend-container.js starts with docker run. These tests need Docker.

Layout check ​

scripts/check-layout-shift.mjs opens each main screen and sheet in headless Chromium from the screen a person opens it from. It needs a browser, so npm test does not run it. Start the demo pack server first (scripts/demo-pack/pack-server.sh), then run:

sh
FREETVARR_URL=http://127.0.0.1:3801 CAPTURE_CLOCK_OFFSET_MS=<offset the server prints> \
  node scripts/check-layout-shift.mjs
  • The check sets 4x CPU throttling and widths of 390 and 1280 px.
  • On a loopback address, it answers the credits and ratings lookups with a fixture after 250 ms. movie-page-cold-lookups answers pending first, like a lookup that is not cached yet.
  • It taps the first matching element whose centre is not covered by another element, as a person would. If no match is on screen, it scrolls the first match into view and then picks again.
  • After each frame is painted, it records the visible headings, text, buttons, list rows, pictures, and skeletons, with their layout boxes.
  • From the tap until the watch ends, it compares the box of each guide cell (by data-key) with its box at the tap. A move of more than 0.5 px fails the screen and shows in the guide column, whether or not the move comes before the first new frame.
  • It fails a screen for a layout shift above 0.02, a blank gap between two screens, an item that moves after the first frame while no ancestor runs an animation or changes its transform, a skeleton that appears and then shows for less than 700 ms (one already showing when the watch starts is not timed), content that arrives more than 1500 ms after the first frame, or a page error. Pictures that finish loading are reported in the art column and do not fail the check.
  • A screen can name the items that wait on a slow answer (slowItems): About and Cast on the film page with cold lookups, the hide rows and score in the programme sheet, the channel list on Live TV, and the details in More info. Those items appear in the slow column and fail only after 2500 ms; every other item keeps the 1500 ms limit.
  • On more-info, moves in the first 500 ms after the tap count as the response to the tap, as the browser's layout shift score does. A screen with nothing to open in the demo pack (the one-off page) is skipped.
  • The demo pack films are empty files, so the player screen measures the player error screen. Replace the film file in the capture folder with a short video to measure playback.
  • On a loopback address, writes go to the demo server. On any other address, the check answers every write itself, so a real server only gets reads.
  • The check uses Playwright 1.49.0 from scripts/.cache/playwright-1.49.0 (the capture scripts install it there). PLAYWRIGHT_DIR points it somewhere else.
  • LAYOUT_SCREENS limits the run to named screens, LAYOUT_VIEWPORTS sets the widths, LAYOUT_FRAMES_DIR saves a screencast of each screen, and LAYOUT_REPORT writes the full results as JSON.

Docs site ​

The documentation site is a VitePress project under docs/ with its own package.json. docs/.vitepress/config.mjs sets base to /freetvarr/ and rewrites DEEP_DIVE.md to deep-dive.md. npm run build in docs/ first runs scripts/fetch-docs-media.sh. .github/workflows/docs.yml builds on pushes to main that change docs/** and deploys to GitHub Pages.

  • Videos, posters, and screenshots are assets of the docs-media GitHub release, not files in git. scripts/docs-media.txt lists them; scripts/fetch-docs-media.sh downloads them; scripts/upload-docs-media.sh uploads them and starts the docs workflow.
  • The scripts/capture-*.sh scripts record the screenshots and videos with Playwright against a throwaway server (scripts/capture-local-server.sh, port 3801). The server reads only the demo pack in scripts/demo-pack/: a fake TVHeadend serves its 7-day schedule, its pictures come from a hash-checked cache, its clock is fixed, and a network guard refuses every connection that is not to the local machine. Each one ends with the upload script, unless DOCS_MEDIA_UPLOAD=0 is set.

GPL-3.0-or-later. Not affiliated with or endorsed by SiliconDust, TVHeadend, or Plex.Titles and artwork in screenshots and videos belong to their owners and appear for demonstration only. Not affiliated with any broadcaster, studio, or Fetch TV. This product uses the TMDB API but is not endorsed or certified by TMDB. TMDB