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
- Architecture
- Startup order
- Storage
- TVHeadend client
- TVHeadend setup
- Guide
- Recording rules
- Sync pipeline
- Import state machine
- Library kinds
- Ad removal
- Removal from TVHeadend
- Live TV
- Recording playback
- Pictures and programme info
- Plex
- Sonarr and Radarr
- For you and Home hero
- Search
- Jobs and health
- Web client
- Security model
- Full environment reference
- Docker deployment
- Build and test
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
| Modules | Job | Talks to |
|---|---|---|
src/server.js | Builds the Express app: security middleware, /api routes, /healthz, the guide feed at /guide/xmltv.xml, the static SPA, the startup sequence | Every module below |
src/scheduler.js, src/schedule-runs.js | Runs one node-cron task from the setting sync_cron; each tick starts a sync, a guide refresh, viewing-history upkeep, and For you upkeep | src/sync.js, src/epg.js, src/user-events-log.js, src/for-you-service.js |
src/sync.js | Lists finished TVHeadend recordings, matches them to show rules, imports them, refreshes Plex, removes imported recordings from TVHeadend | src/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.js | Name a new show folder; find the TVmaze, TVDB, and TMDB ids of a show | TVmaze, TMDB, shows, show_identity_picks |
src/auto-import.js, src/recording-now.js | Poll the running recordings, then start a sync after a recording ends | src/tvheadend.js, src/sync.js |
src/tvheadend.js, src/http-auth.js | HTTP client for the TVHeadend API with Digest or Basic auth | TVHeadend |
src/tvheadend-bootstrap.js, src/tvheadend-setup.js, src/tvheadend-guide.js, src/tv-login.js | Wizard steps: lock an open TVHeadend, set up tuners and channels, set up the guide, create a watch-only TV app login | TVHeadend 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.js | Build the merged XMLTV guide file from ranked guide sources, score each source, and serve it (or the source feed) with time-shifted copies of programmes | Freeview API, mjh XMLTV feeds |
src/epg.js, src/guide-cache.js, src/guide-history.js, src/guide-search.js | Cache the TVHeadend guide and recording state; save airings; search the guide | src/tvheadend.js, src/db.js |
src/pending-skips.js, src/watchlist.js, src/repeat-match.js, src/autorec-match.js, src/title-countries.js | Single-episode skips, watchlist titles, matching of airings to rules and repeats, and the country words of series rule titles | src/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.js | Pipe a TVHeadend channel stream through FFmpeg into HLS files; pick the encoder; set the stream limit; read tuner use | TVHeadend, ffmpeg |
src/playback.js, src/in-progress-playback.js, src/in-progress-positions.js | Play library files and running recordings as HLS sessions | ffmpeg, ffprobe, media library, TVHeadend /dvrfile |
src/commercials.js, src/ad-original-routes.js | Detect and cut ad breaks with Comskip and ffmpeg | comskip, ffmpeg, ffprobe, media library |
src/plex*.js, src/external-ids*.js | Plex discovery and section refresh; watched-state sync; whole-library listing | Plex, plex_watch_state, library_items, external_ids |
src/arr-*.js, src/foreign-delete.js, src/delete-manager-check.js | Optional Sonarr and Radarr client for file lists, unmonitor, and delete | Sonarr, Radarr |
src/for-you*.js, src/top-rated.js, src/user-events*.js, src/watch-tracker.js | Record viewing events; score the guide against them; run the heavy work in a child process | user_events, text_embeddings, Hugging Face models, optional Ollama |
src/home-hero-service.js, src/hero-picture-proof.js, src/art-pool.js | Build the Home hero snapshot | src/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*.js | Find, store, resize, crop, and warm pictures | Freeview, 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.js | Look up ratings, cast, classifications, genres, series scores, and alternative titles | src/outbound-http.js, lookup tables |
src/outbound-http.js, src/lookup-gate.js, src/cache-prune.js | Shared client for third-party requests; hourly lookup limit; daily deletion of expired lookup rows | Third-party hosts, lookup tables |
src/library*.js, src/show-folder-rename.js | Library listing, watched marks, folder moves, deletes, and folder renames | recordings, shows, media library |
src/doctor.js, src/health-summary.js, src/path-check.js, src/docker-host.js | Health checks and the health level in the navigation | TVHeadend, Plex, media library |
src/host-gate.js | The Host check, the allowed hostnames, and the names seen | settings |
src/activity*.js, src/progress.js, src/event-loop-lag.js | Job registry, live progress, job-run storage, and event-loop monitoring | job_runs |
src/web/, src/web-assets.js, src/build-id.js | Vue 3 client files, asset caching, and the build id | Browser |
src/db.js, knexfile.js, migrations/ | Knex connection, settings helpers, and schema | state.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
| Timer | Started by | First run | Repeat | Effect |
|---|---|---|---|---|
| Cron tick | startScheduler | Next match of sync_cron | Cron (default */30 * * * *) | Sync, guide refresh, viewing-history upkeep, For you upkeep |
| Recording poll | watchForFinishedRecordings | 60 s | 60 s | Detects a finished recording (Auto-import) |
| Reapers | Module load | 5 s | 5 s | End idle or stalled live and playback sessions |
| Doctor checks | scheduleDoctorChecks | 2 min | 3 h | Refresh the health report |
| Ratings warm-up | Module load | 2 min | 1 h | Look up ratings for upcoming programmes |
| Cache prune | startCachePruning | 10 min | 24 h | Delete expired lookup rows |
| Home hero build | homeHero.start | 20 s | 5 min | Rebuild the hero snapshot |
| Library folder sort | Listen callback | 3 min | None | runReclassificationOnce (Folder moves) |
| Guide merge | guideMerge.start | 3 min | 6 h | Build guide/merged.xml.gz (Merged guide) |
| Guide warm-up | keepGuideWarm | Immediate | 5 s after each local midnight | Reload the guide and recording state |
| Pending skips | watchPendingSkips | After each guide load | 5 min | Reload the recording state while a skip or a repeat waits |
| Watchlist sweep | mountWatchlist | None | 15 min | Create a series rule for a title in mode record |
| Artwork nightly | startWarmSchedule | Next 03:30 local | 24 h | Warm every picture tier (Picture warm-up) |
| Visit window | startWarmSchedule | 45 min before a likely visit | Checked every 1 h | Warm 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
| Table | Migrations | Holds | Main writer |
|---|---|---|---|
settings | 0001 | Key and text value of every setting | src/db.js |
shows | 0001, 0037, 0038, 0039 | Series 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 |
recordings | 0001 and later, 0040, 0042 | One 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 |
syncs | 0001 | One row per sync: start, finish, status, summary_json | src/sync.js |
guide_programs | 0002 | Saved guide airings keyed by channel_id and start, with program_json | src/guide-history.js |
show_artwork | 0005 | Cached picture sources per title_key | src/show-artwork.js |
watchlist | 0008, 0014 | Titles to notify or record, with optional channel and padding | src/watchlist.js |
user_events | 0010 | Viewing-history events | src/user-events-log.js |
text_embeddings | 0011 | Embedding vectors per text_hash and model_id | src/for-you-engine.js |
title_genres | 0011 | Cached genres per title_key | src/genre-enrichment.js |
show_nicknames | 0012 | User-added search names per show_key | src/search-aliases.js |
title_known_as | 0012 | Cached alternative titles per title_key | src/known-as.js |
artwork_lookups | 0013 | Cached Wikipedia and TMDB picture lookups | src/fallback-artwork.js |
programme_ratings | 0015, 0020 | Cached rating lookups, with miss_reason; TVmaze series scores under keys that start with tvmaze:series: | src/programme-ratings.js |
programme_classifications | 0016, 0041 | Classification label per title_key, start_ms, and shift_hours | src/classification-labels.js |
programme_credits | 0017, 0020 | Cached cast and crew lookups, with miss_reason | src/programme-credits.js |
programme_categories | 0019, 0041 | XMLTV category per title_key, start_ms, and shift_hours | src/classification-labels.js |
art_pools | 0021 | Cached picture pools per pool_key | src/art-pool.js |
show_artwork_choices | 0022 | The chosen picture per show_key and kind | src/artwork-choices.js |
image_focus | 0024, 0027 | Focus point and face box per picture URL | src/image-focus-service.js |
pending_skips | 0025, 0031 | Skipped single airings by program_id | src/pending-skips.js |
programme_kind_overrides | 0028, 0029 | User-set kind per show_key | src/programme-kind.js |
job_runs | 0032 | Finished job runs as run_json | src/activity-store.js |
series_evidence | 0033, 0039 | Series facts per show_key; database_ids and database_ids_at | src/series-evidence.js |
plex_watch_state | 0034 | Watched snapshot of both sides per recording_id | src/plex-watch.js |
library_items | 0035 | Plex library items keyed by rating_key and part_id | src/plex-library-store.js |
external_ids | 0036 | TVDB, TMDB, and IMDb ids per title_key, kind, and source | src/external-ids-store.js |
show_identity_picks | 0037 | The picked or declined identity per title_key and network_family | src/show-identity-store.js |
art_resolutions | 0044, 0045 | The 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 again | src/art-resolver.js |
title_kinds | 0053 | One 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 kinds | src/title-kinds.js |
programme_picture_stamps | 0050 | One stamp per show_key for guide airing and recording picture URLs, and changed_at. See Live picture updates | src/programme-stamps.js |
title_aliases | 0047 | Per 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_windows | 0055 | One 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 build | src/guide-sources/window-store.js |
guide_source_health | 0048 | One 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_checks | 0049, 0051 | One 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 pictures | src/picture-placeholders.js |
guide_pictures | 0046 | One saved guide picture per image address (source_url), with its title_key, host, w, h, bytes, saved_at, last_seen_at | src/guide-pictures.js |
Config folder
| Path | Holds | Set by |
|---|---|---|
state.db, state.db-wal, state.db-shm | The database and its WAL files; back them up together | DB_PATH |
csrf-secret | The 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 uploads | src/artwork-uploads.js |
image-cache/ | Resized WebP pictures, IMAGE_CACHE_MAX_MB limit | src/image-thumbnails.js |
models/ | Downloaded For you models | src/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.ini | Optional Comskip settings; replaces the bundled assets/comskip.ini | src/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 aGETwith the parameters in the query string.apiPost(path, form, conn)sends a form-encodedPOST; object fields travel as JSON strings in one field (nodeorconf).tvhReadandtvhWriteexportapiGetandapiPost. The setup, guide, bootstrap, and doctor modules build their own paths and call TVHeadend through these two functions.resolveConnectionreads the settingstvh_url,tvh_username, andtvh_password. A caller URL gets the stored password only when it has the origin (scheme, host, and port) oftvh_url(Secret binding).sendAuthenticatedsends every request. With a username set, it sends the cachedAuthorizationheader. On a401it stores thewww-authenticatechallenge, signs the request, and sends it once more.authorizationForinsrc/http-auth.jsgives 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 for90 s.
| Request or cache | Value |
|---|---|
Default API call (REQUEST_TIMEOUT_MS) | 15 s timeout; also /dvrfile/<uuid> and channel icons |
| Discovery probe | 1.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 cache | 10 min; apiPost clears it before and after every write |
| Tuner count and service multiplex caches | 10 min |
| Default DVR profile and default languages | Process lifetime |
Auto-discovery
detectServers serves POST /api/tvh-detect:
- When
TVH_URLis set, it returns that URL withsource: 'env'and probes nothing. rankCandidateslists URLs on port9981: the request hostname and local socket address, then the host IPv4 addresses (private first;172.17.0.0–172.31.255.255and169.254.x.xexcluded), thentvheadend,host.docker.internal, and127.0.0.1.probeServerrequests/api/serverinfoon every candidate in parallel. A hit is a200withsw_version, or a401whosewww-authenticatecontainstvheadend.- Loopback hits drop when another hit exists. Alias hosts drop when their
serverinfobody 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.
| Condition | stage | code |
|---|---|---|
| Network failure | The path | The Node error code (for example ECONNREFUSED) |
HTTP 401 or 403 | The path | auth |
Other HTTP status of 400 or more | The path | None |
No tvh_url setting | config | no-url |
Stream refused with 401 or 403 / 503 / other | stream | auth / no-tuner / http |
| Connection reset before video | stream | no-source |
| Guide load finds no channels | epg | no-channels |
A create call returns no uuid | record or series | no-uuid |
| No matching entry or rule | cancel, series, or remove | not-found |
Normalised values
- Series key:
seriesKeyreturns`${channelId}|${title.trim().toLowerCase()}`. Events carry it asseries_link; autorec rules carry it asseriesLinkId. An any-channel rule has an empty channel part. - Season and episode:
parseEpisodeDispreadsepisode_disp(for exampleSeason 3.Episode 7) with the patternsSeason\s+(\d+)andEpisode\s+(\d+). Guide events carryseasonNumberandepisodeNumber. - Guide text:
normaliseEventandnormaliseEntrypass the subtitle and synopsis throughcleanGuideTextinsrc/consumer-advice.js. It stripsConsumer Advice: ...,Audio Described (AD)., and a leadingFrom: <country>., and returns the advice letters as a list. - Channels:
listChannelsdrops disabled channels.hdfollows the DVB service type (0x11,0x19,0x1fgive HD;0x01,0x16give SD), else the channel name.offAiris true when every service is disabled.
Endpoints
src/tvheadend.js calls these endpoints.
| Endpoint | Use |
|---|---|
serverinfo | Test connection, discovery probe, verifyLogin |
channel/grid | Channel lineup, limit 1000 |
epg/events/grid, epg/events/load | Guide events, 2000 per page; one programme by eventId |
dvr/entry/grid_upcoming, dvr/entry/grid_finished | Scheduled and running entries; finished entries (every page of 5000), the import queue |
dvr/entry/grid_failed, dvr/entry/grid_removed | Past airings for repeat checks, cached 10 min; removed entries that each sync marks not in TVHeadend |
dvr/entry/create_by_event | Record (Single recordings) |
dvr/entry/cancel, dvr/entry/stop, dvr/entry/remove, dvr/entry/prevrec/set | Cancel, stop, and remove entries (Removal from TVHeadend) |
dvr/autorec/grid, dvr/autorec/create | Series rules (Series recordings) |
idnode/save, idnode/delete, idnode/load | Padding, enable and disable, rule updates, retention; rule and child-entry deletes; one entry for in-progress playback |
dvr/config/grid | Default DVR profile (empty name, else the first) and its storage path |
epggrab/channel/grid | Channel logo fallback |
status/inputs, status/subscriptions, hardware/tree | Tuner readings, tuner holders, tuner count, and the multiplex of each tuner |
mpegts/service/grid, service/streams | Multiplex and DVB type of each service; elementary streams of a channel |
config/load | Default 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:
| Module | Endpoints |
|---|---|
src/tvheadend-bootstrap.js | access/entry/grid, passwd/entry/grid, access/entry/create, passwd/entry/create, idnode/load, idnode/delete, serverinfo |
src/tvheadend-setup.js | hardware/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.js | epggrab/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.js | access/entry/grid, passwd/entry/grid, access/entry/create, passwd/entry/create, idnode/delete |
src/doctor.js | Read-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 group | Routes | Limiter |
|---|---|---|
| Bootstrap | GET /api/tvh-bootstrap/status, GET .../progress, POST .../apply, POST .../undo | bootstrapStatusLimiter (reads), bootstrapLimiter (writes) |
| Tuners and channels | GET /api/tvh-setup/status, GET .../progress, POST .../tuner-address, POST .../apply | Same |
| Guide | GET /api/tvh-guide/status, GET .../progress, POST .../apply, GET and POST .../links | Same |
| TV app login | GET, POST, and DELETE /api/tv-login | bootstrapLimiter (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
freetvarrgets a random password of24bytes. Each verify step signs in with11attempts,1 sapart. - 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-entrysaves the open entry as JSON in the settingtvh_open_entry_backup.save-connectionsavestvh_url,tvh_username, andtvh_password.- A failure before
remove-open-entrydeletes the created entries.confirm-lockedwaits for an anonymousserverinfoto answer401. undoBootstrapposts the saved entry toaccess/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 id | Action |
|---|---|
network | Use the chosen network, or create one with mpegts/network/create from the transmitter key |
tuners | Turn on each tuner and add the network to it |
scan | Poll every 2 s; fail with no-signal (no services) or scan-timeout (30 min) |
map | Map enabled, unencrypted TV services that have no channel; fail with map-empty or map-timeout (20 min) |
recording | When 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:
feed: find the module titledXMLTV URL grabber(elseno-grabber), and read the feed channels (feed-unreachable,feed-empty). Then enable the grabber withpriority3and start an import (below).download: pollepggrab/channel/gridevery3 suntil every feed channel exists;download-timeoutafter5min unless some exist.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:
readTimeshiftsfinds 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
argsis the source feed URL. - With some,
pointGrabberAtShiftedFeedstores the source URL in the settingguide_source_urland setsargsto the Freetvarr URL of/guide/xmltv.xml. When TVHeadend does not request that URL within150 s, the grabber falls back to the source URL. keepGuideSavedturns onepgdb_periodicsaveandepgdb_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:
guide/merged.xml.gz, whenguideMerge.servablePath()gives it: the settingguide_merged_feedison(set by the confirm step; default unset), the file exists, andplanSourcesgives a plan for the current time zone andguide_source_url. With the setting unset, TVHeadend never sees the merged file or itsfreeview.*channels.- Else the source feed (gunzipped for
.gz).keepLastCopywrites a gzipped copy toguide/last-source.xml.gzand renames it into place only after the source ends. A copy write that fails unpipes and deletes the copy; the response goes on. - When the source fails before output,
guide/last-source.xml.gz. With no copy, the route answers502.
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:
- The near pass reads the primary windows that start in the next
2days (NEAR_BUILD_MS) and takes each later window from memory, also when it expired (up to3days after its fetch). It writes the file. A later window that is missing or expired counts as pending. - 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
20min (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().
| Adapter | Countries | Region | Data |
|---|---|---|---|
freeview-au | au | freeviewRegionOf (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-au | au | Time-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-nz | nz | nz (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-nz | nz | New Zealand | https://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
idequals the listingepisode_id, else the first one (listingEpisodeOf). Freeview NZ lists several episodes per listing, and the first one is often another episode. title;startandend.- The episode title as
subTitle, when it differs from the title, is notEpisode <n>, and the episode tags (when it has tags) includeonapi-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/*asrating, from the rating labels of the source (AU:G,PG,M,MA15+,AV15+,R18+,C,P).season_number/*up to9999,episode_numberup to99999(Freeview NZ has season numbers such as1039546), andcrid_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
5min and whose title agrees (titlesAgreeonshowTitleKey). 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 asstar-rating,video,credits). - Title: a match with two different titles writes the secondary title and saves the pair to
title_aliases(kindalias). An unmatched primary programme takes its saved alias, else its own title. - Episode numbers (
episodeNumsOf): the secondaryxmltv_ns,SxxExx, andonscreen; when the secondary has none, primary season and episode givexmltv_nsandSxxExx; else a primary episode alone givesxmltv_ns.<episode - 1>.. The primary CRID is added as systemcrid, 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
1min 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
kindvariant-candidate. A candidate is deleted when the secondary lists it, or after30days 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:
- Add the time zones of the country to
COUNTRY_ZONESinsrc/zone-countries.js, if they are missing. - Write the adapter in
src/guide-sources/<id>.jsto the source contract above. A Switch Media Freeview API takescreateFreeviewSourcewith its host,regionOf,channelsPath, rating labels, and horizon (freeview-nz.jsis the example). An XMLTV feed takescreateMjhSourcewith itsfeeds(mjh-nz.js). The source withfeedsis the secondary: its channel ids are the guide channel ids. - Rank the adapter in
createGuideSources(src/guide-sources/index.js): primary first, then the feed source. Add the new parameter to thecreateGuideSourcescall insrc/server.jswithonWindow: seedFreeviewWindowfor a Freeview source, so Freeview pictures reuses its reads; add the service toFREEVIEW_SERVICESfor pictures. - Save trimmed API answers as fixtures in
test/fixtures/<id>/(two or three channels, one window), with no stream addresses or keys. - Add a case to
contractCasesintest/guide-sources.test.js; the contract test fails until every adapter inall()has a case. Add the country to the routing test in the same file. - 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):
| Field | Value |
|---|---|
covered_hours | Hours of the next 48 h that the programmes cover, overlaps counted once |
horizon_hours | Hours from now to the last programme stop |
described_share | Share of the programmes in the next 48 h with a title and a description |
agreement | Share 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_failures | Freeview: 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:
- A channel that only one source carries uses that source.
- A pin, else a named source, leads, even while it is degraded.
auto: the secondary leads when the primary is degraded on the channel and the secondary is not; the build lists the channel infallbacks.- 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):
| Route | Action |
|---|---|
GET /api/guide-sources | Sources 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/automatic | Sets 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-grabber | Sets guide_repoint to kept |
POST /api/guide-sources/notice/hide | Sets guide_repoint_notice to hidden |
POST /api/guide-sources/repoint | Answers 202 and runs applyGuideRepoint; 409 while it runs or when the plan has a reason |
GET /api/guide-sources/unmerge | The plan to stop using the merged guide, or 400 while TVHeadend does not read it |
POST /api/guide-sources/unmerge | Answers 202 and runs applyGuideUnmerge; 409 while a guide change runs |
GET /api/guide-sources/repoint/progress | The 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:
merged: find the XMLTV URL grabber (no-grabber, with itsenabled,args, andpriority).createMergedFeedSwitchstores the earlierguide_merged_feedandguide_source_url, stores the grabber address inguide_source_urlwhen it is not a Freetvarr address, builds the merged guide again whenguide/merged.jsonnames another region (buildForPlan,build-failed), then setsguide_merged_feedtoon.point: count the events of up to8linked channels and read the last event stop, note the module guide channels, set the grabberargsto the Freetvarr feed address withpriority3,keepGuideSaved(the earlier values go to the journal), and start an import.fetch: wait up to150 sfor TVHeadend to fetch/guide/xmltv.xml(not-fetched). The route notes a fetch only after a200response ends (noteServedFeed).link: read the feed channels and wait for them inepggrab/channel/grid(planRepointLinks). mjh channels link by LCN, then name (matchGuideChannels). Eachfreeview.<triplet>guide channel gets exactly the TVHeadend channels with that triplet and no mjh link, which also removes links that TVHeadend made by name.verify: poll for up to5min until the last event stop moves later, a sampled channel count changes, or a linkedfreeview.*channel has events; elsenot-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:
grabber: read the grabber (no-grabber) and a sample of event counts; setguide_merged_feedoff andguide_source_urlto the target (setofcreateMergedFeedSwitch); put back the save settings; save the grabberenabled,args, andpriority; start an import.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.verify: when the target is a Freetvarr address, wait up to150 sfor TVHeadend to fetch it (not-fetched); then poll up to2min for changed listings. No change givesupdated: 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).
loadGuiderunslistChannels,listEvents,loadTitleGenres, andloadSeriesEvidencein parallel. The window runs from local midnight to the end of day7(GUIDE_DAYS).listEventsreadsepg/events/gridsorted by start,2000events a page (EVENT_PAGE_SIZE),4pages at a time (EVENT_PAGE_CONCURRENCY).GUIDE_TTL_MSis60min; an empty guide expires after60 s. An expired guide of the same day serves while a reload runs. A failed reload serves the cached guide withstale: true. A failed load for a new day (at midnight) also serves the previous day's guide withstale: true, and that day loads again only afterGUIDE_STALE_RETRY_MS.getGuideDaybuilds its day window fromlocalMidnightMs(), not from the guide'sstartMs, so the stale guide still shows today.- One load runs at a time.
clearGuideCachedrops the cache.onGuideLoadedlisteners 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:
moviewhenairingLooksLikeFilmholds.one-offfor a sports airing whose storeddatabaseIdsisnone, or is unset and the title has a year.serieswhen the title has a TVmaze record, or the event has a season, an episode, or an episode title.serieswhen the title airs3or more times in the loaded week; otherwiseone-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:
- The
programme_kind_overridesrow:movie,show(series), orone-off.not-movieblocksmoviein every later step. - One library kind: the Plex library items of the title (
kindsForinsrc/library-titles.js). Two kinds give no library answer. A librarymovieis skipped when the guide lists the title with episode details. - The guide majority (
guideKindEvidenceOf):moviewhen every airing is a film, else the commoner ofseriesandone-off. - A hint:
serieswhen 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):
loadGuidewrites the guide evidence (guideKindUpdatesOf), with the override and the library kinds, before it sets the event kinds.refreshLibraryTitleKindsinsrc/epg.jswrites the library evidence (libraryKindUpdatesOf) after each sync and each Plex watch sync. A title that left the library gets an empty library list.PUTandDELETE /api/programme-kind/:showKeyrewrite 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.earlierAiringOfEntryfinds an earlier airing of the same episode for an upcoming entry.splitRepeatsmarks a rule timer (autorecIdset) as a repeat; a one-off the user scheduled is never a repeat, except a TVHeadend duplicate (duplicateOfStart).withRecordedRepeatsSkippeddisables each enabled repeat whose original is recorded.planUpcomingRecordingsprojects 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 throughisSameShowTitle; a plain-text title matches as a substring; any other title is a regular expression of up to200characters with a cost cap. A rule that setstag,content_type,cat1–cat3,star_rating,btype,brand, orseasonis unsupported and never matches.- The whole-title form is
^Title(or^(Title|Variant|…)with title variants) and thensameShowSuffixOf(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,installCountryinsrc/title-countries.js:countryForTimeZone(currentTimeZone()), read again whenprocess.env.TZchanges. 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) areUK,US,USA,AU,AUS, andNZ, less the own words of the country (countryTitleWordsOf), in that order. Anauornzinstall refusesUK,US, andUSA, 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:notAnyOfPatternbuilds a trie of the refused rests and writes its complement as nested groups and negated bracket expressions, with both letter cases in each bracket.isSameShowTitleapplies the same rule, withexcludedTags(the install country's tags when not given).anchoredTitlesOfreads the titles back with the suffix of any country (knownEditionTagSets), and gives the refused tags of that suffix asexcludedTags, 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+Nchannels) with base starts60 sor 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:
- When an enabled entry for the same programme exists in
dvr/entry/grid_upcoming, sendidnode/savewith the padding the request gave (if any), and stop. No second timer is made. - When a disabled entry for the same programme exists, send
idnode/savewithenabled: trueand only the padding the request gave, and stop. A skipped series episode keeps the padding it copied from its rule. - Otherwise send
dvr/entry/create_by_eventwithevent_id,config_uuid(the default DVR profile), andcomment. - Send
idnode/savewithstart_extraandstop_extraon the new entry. When this save fails, the result is stillokwithpaddingSaved: 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:
{
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',
}channelis''whenany_channelistrue.maxcountdefaults to0(keep all).record: 1(DUPLICATE_DETECTION_EPISODE_NUMBER) turns on TVHeadend duplicate detection by episode number.titleis^${escapeAutorecTitle(title)}( ?[:(-].*)?$. TVHeadend reads the autorec title as a caseless regular expression that matches anywhere, so the anchors stopThe Chasefrom recordingThe Chase AustraliaorBeat The Chase. The tail still matchesThe Chase (Ep 5)andThe Chase: Celebrity Special. It is valid POSIX ERE and PCRE.comment: 'freetvarr'(CREATOR_TAG) marks the rules that Freetvarr made.listAutorecsturns each escaped title, with or without the anchors, back into the literal title (literalTitleOf), so the series key stayschannel|title.- Unless
add_show_ruleisfalse, the route callsensureShowFolderwith originuser(Show origin).
| Route | Function | TVHeadend call |
|---|---|---|
POST /api/epg/pause-series | setSeriesTagsEnabled | idnode/save with enabled on each autorec |
PATCH /api/library/shows/:key/rule | updateSeriesTags | idnode/save with maxcount and padding on every autorec of the show key |
POST /api/epg/cancel-series | cancelSeriesRules | idnode/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:
| Trigger | Caller |
|---|---|
cron | src/scheduler.js, on each tick of the setting sync_cron |
recording-finished | src/auto-import.js, after a recording ends |
restart | src/restart-sync.js, after a restart stopped a sync (Restart sync) |
manual | POST /api/sync with no show_id |
manual-single | POST /api/sync with an integer show_id; imports only entries that match that folder |
manual:import | POST /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
listFinishedreads every page ofdvr/entry/grid_finished(5000a page, up to10pages). A failure here, or in theshowsread, ends the sync with statuserror.markRemovedByTvheadendthen readsdvr/entry/grid_removed(shared with the10min past-airings cache) and setsdeleted_from_tvh_aton each row whose entry TVHeadend removed itself (fileremovedset, for example by Keep the latest). A file that is only missing, such as on an unmounted disk, does not count.importContextOfloads the kind overrides, theseries_evidencefacts, therecordingsrows by show key, and the autorec names.- Each finished entry runs through the Import state machine.
startRecordingPicturesstarts the recording picture saves and does not wait for them (Recording artwork).- Each library kind with an import refreshes its Plex section (Plex).
runAutoDeleteremoves the queued recordings from TVHeadend, with the earlier removals that wait for a retry (Remove after import).sweepLibraryStateschecks that each imported file still exists (Library delete).finishSyncwrites the status and summary, then runspruneSyncHistory,pruneTombstonedRecordings, andpruneCutOriginals.
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:
| Plan | Condition | Action |
|---|---|---|
none | No row was stopped. | No timer. |
leave-to-schedule | The newest stopped row has the trigger restart. | No sync. |
already-synced | hasSyncStartedSinceBoot() is true: beginSync created a sync row since this boot. | No sync. |
syncs-off | scheduledSyncsOn() is false. | No sync. |
schedule-due | getSchedulerNextRun() is at most 2 minutes away (SCHEDULE_GRACE_MS). | No sync. |
run-again | None 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).
libraryDecisiondecides import or hold, first match wins:library_choiceexcludeon the row holds (Kept out of the library).library_choiceincludeon the row imports. Import in the Recording log sets it.- The entry's library tag
excludeholds (Recorded with Add to library off). - A matched folder, the setting
import_unmatchednotfalse, or the library tagincludeimports. - Anything else holds (
No series folder for this title, and Import every recording is off).
holdRecordingsetsstatusnot_imported,errorto the reason, andfile_path,purged_at, andlog_cleared_attonull. So a held row cleared from the log comes back at the next sync while TVHeadend still has it. It leaves adone,partial, orimportingrow, or a row withdeleted_from_tvh_at, unchanged.lookUpDatabaseIdsruns whenneedsDatabaseIdsis true (Sport and database ids).libraryKindgivestv,oneOff, orfilmfromseriesKindOf(Library kinds). A film with no movies folder givesoneOff.- For
tvwith no matched folder,folderForSeriescallsensureShowFolder. An entry from a series recording uses the autorec name and originuser; any other entry uses its title and originauto. processItemwritesskippedwith the reason inerrorwhen the path does not map, the source file is missing, or the library folder for the kind is not ready (Library folder check). Apartialrow keeps itsstatusandfile_path; onlyerrorchanges.importItemimports the file and classifies it. When the folder or the copy throws, the row becomesfailedwith the error and nofile_path, and the next sync tries again. A copy that throws deletes its part-copied file. It runs Ad removal only for adoneitem 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 Settingsor<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. refreshLibraryStateskeeps the storedlibrary_stateof 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/librarywithinclude) answers409when the row'sfile_pathis 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
| Kind | Function | Path |
|---|---|---|
tv | buildDestPath | <media_root>/<dest_folder>/<season folder>/<episodeFilename> |
oneOff | buildOneOffPath | <oneoff_root>/<title>/<title> - <YYYY-MM-DD HHMM>[ - <episode title>].<ext> |
film | buildFilmPath | <movies_root>/<name>/<name>.<ext>; <name> is Title (Year), or Title |
- The season folder comes from
shows.season_template, defaultSeason {season}.{season}and{season_padded}pad to two digits;{season_unpadded}does not. No season gives00. episodeFilenamegives<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>isdest_folderwithout a{tvdb-…},{tmdb-…}, or{imdb-…}id hint.<ext>is the extension of the TVHeadend file, orts.createValidFilenameremoves\ / : * ? " < > |.guardWithinRootthrowsdestination escapes media rootwhen 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:
- An existing folder whose name holds the identity's
{tvdb-<id>}or{tmdb-<id>}. - An existing folder named as the identity name, or as the title (plus at most a year, country, or id suffix).
- The identity folder name:
<name> {tvdb-<id>}or<name> {tmdb-<id>}. - The title, through
createValidFilename; elseRecordings.
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.
Hardlink or copy
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:
recordingPictureFortakes the event id (TVHeadendbroadcast), the title, and the TVHeadend image of the entry. An event that is gone from the guide uses the TVHeadend image and title.- It runs
RECORDING_SAVE_CHAINin the picture resolver (resolveRecordingPicture), with a10 sbudget, 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. - The bytes come from the gate, so a stand-in is never saved. A title card is saved only when no other picture loads.
saveRecordingPictureanswerssaved,missed(the chain ended with no picture),retry(a step was pending or failed to load), ordeferred(a load met the60 swait 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 (a404, a stand-in, or no image address). When an earlier step failed for a time (a timeout, a skipped host, or the60 swait), the answer is unsettled and nothing is saved. On the last of3tries (ARTWORK_ATTEMPTS), a picture from an unsettled answer is saved, and no picture ismissed. A firstdeferredis not a try; a seconddeferredin a row for the same recording is.
The record route saves only a settled picture. Sync never waits for a picture:
saveRecordingDetailsqueues a row whoseimage_checked_atis empty.- After the imports,
startRecordingPicturesstarts one background run (createRecordingPictureRun), unless one already runs. The sync finishes without it. - 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. - 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. savedandmissedsetimage_checked_at;retryanddeferredleave it empty, so the next sync asks again. An upcoming entry that answerssavedormissedis 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:
- A user choice in
programme_kind_overrides:show,one-off, ormovie. The choicenot-movieonly switches off rule 4. - A user rule gives a show: a series recording for the title, or a folder with origin
user. - A title match (any matched folder) gives a show, or a one-off for a sport one-off (rule 5).
- 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. - A sport one-off gives a one-off (Sport and database ids).
- Recordings on two or more local days give a show.
- Series facts give a show: the title recurs, or it has a real season number (not a year).
- An event title (
isEventTitle: for examplegrand final,awards,telethon,concert,election), or a TVmaze award show, gives a one-off. - An episode number on a year season gives a show. For sport, only episode
2or above counts. - 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 item | Points | Condition |
|---|---|---|
airTime | 100 | /shows/<id>/episodesbydate has an episode within the airing |
network | 40 | A domestic show on the network family of the channel |
titleCountry | 30 | The show's country equals the country in the title |
domestic | 20 | A domestic show with the network or airTime points |
running | 5 | The 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
showgroup: each file in the one-off folder moves tobuildDestPathunder the matched or a new folder. - A
oneoffgroup: each file in the TV folder moves tobuildOneOffPath.
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_enabledis'true'(Settings → RECORDING → Ad removal). shows.ad_removalisdetectorcut(valuesoff,detect,cut, defaultoff;AD_REMOVAL_MODESinsrc/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 recordings | Meaning |
|---|---|
ad_status | null (not scanned), scanning, detected (breaks found, file unchanged, .edl written), no_breaks, cut, detect_failed, cut_failed |
ad_breaks_json | JSON array of { start, end } in seconds |
ad_processed_at | Time of the last scan result |
ad_cut_at | Time of the last cut |
ad_backup_saved_at | Time the .orig backup was made; null with no backup |
ad_backup_uncut | true 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:
- Copy the ini file to the workdir and append
output_edl=1. The ini file is<config folder>/comskip.iniwhen it exists, else the bundledassets/comskip.ini.GET /api/settingsreportscomskip_ini_override. - Read the duration with
ffprobe. - Run
nice -n 10 comskip --ini=<workdir>/comskip.ini --output=<workdir> <file>. - Parse the EDL file (
parseEdl): rows with action0or3andend > 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.
computeKeepSegmentsclamps, sorts, and merges the breaks, and returns the gaps between them. An empty keep list fails withbreaks cover the entire recording.- 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_zerowritesseg-<i>.ts. ffmpeg -f concat -safe 0 -i list.txt -map 0 -c copywritesout.ts.verifyCutfails whenout.tsis empty, or its duration differs from the summed keep length by more thanmax(5, 2 × boundaries)seconds (boundariesis twice the break count).swapInCutrenames the file to<file>.orig, then renamesout.tsto the file path. If the second rename fails, it renames the.origback.- The row gets
size,ad_cut_at, and the backup columns. A savedplayback_position_smoves back by the break seconds before it (cutTimeOf); a cut from the.origfirst maps it to the original time through the breaks of the last cut (originalTimeOf). Putting the.origback 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.
| Route | Success | Main refusals |
|---|---|---|
POST /api/recordings/:recording_id/ad-scan | 202 with { started: true, mode }; the scan runs in the background | 404 unknown row; 409 not imported, no file, file gone, or a scan already runs |
POST /api/recordings/:recording_id/restore-original | 200 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:
idnode/deleteon each upcoming entry whoseparentis this recording.idnode/savewithretention: 2147483647(RETAIN_FOREVER).dvr/entry/prevrec/set, so duplicate detection keeps the episode as recorded.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.
- Read
dvr/autorec/gridanddvr/entry/grid_upcoming. anchorPlanOfpicks the rules withcommentfreetvarr,fulltextandmergetextoff, a title that does not end with the suffix of the install country (isCurrentAnchor), and a title that isnameitself (a rule from before titles were escaped) or reads back asnamethroughliteralTitleOf, which includes the 2.9.0 suffix. The new title is the escaped and anchoredname, with the title variants the old title had and those saved inseries_title_variants. User-made and hand-edited rules are left alone, with a log line each.- For each rule, log the old and new title, and log each of its timers whose
disp_titlestops matching ([rules] timer ... stops matching). - Send
idnode/savewithuuidandtitleonly. 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 moredvr/autorec/gridread checks each title; a title TVHeadend did not apply counts as failed. - A failed save logs the TVHeadend error and keeps the old title. The failed rules go into the setting
autorec_anchor_failed, thetvh.rulesHealth 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.
| Country | Own words |
|---|---|
au and nz | Australia, AU, AUS, NZ, New Zealand, Aotearoa |
uk | UK, Britain |
us | US, USA, America |
ca | Canada |
ie | Ireland |
- Offer:
getSeriesreads the cached guide (listGuideAirings) and indexes the titles of airings that have not ended (guideTitleIndexOf). For each series,variantTitlesOflists each title for whichisVariantTitleis 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 year19xx–20xx. The own words are in the table above. A merged guide variant candidate (title_aliaseskindvariant-candidate, a primary title the secondary never lists) is also offered whentitlesAgreematches it to the series title (isCandidateVariant). A title the rule already matches (isSameShowTitle) is left out.upcomingcounts 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 }, astitleVariantson the series.titleVariantsEditableis false when an autorec is nottitleEditable(commentfreetvarr, nofulltextormergetext, and a title thatanchoredTitlesOfreads). - On and off:
POST /api/epg/series-title-variant(src/series-variant-routes.js) withseries_link_ids,variant, andenabledcallssetSeriesTitleVariant. It reads the series name from the matched autorecs (listSeriesRules), never from the request. The current list is the saved variants plus the rule'stitleVariants. A variant that is not in that list, failsisVariantTitle, and is not a candidate variant is refused with400andcodenot-a-variant. Otherwise it adds or removes the variant (case-insensitive), sends the new title to every autorec of the series (setSeriesTitleVariants,idnode/savewithuuidandtitle), then saves the list toseries_title_variants(series_keyis the show key of the series name). A failed TVHeadend save saves nothing. TVHeadend refuses withtitle-not-editablewhen an autorec is nottitleEditable. - Read back:
listAutorecsgivesnameandseriesLinkIdfrom the first title only, so the series key does not change, and gives the others astitleVariants.enabledis true for a title inseries_title_variantsor in the rule.recordSeriesadds 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:
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).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 alibrary_replacementfile.- It deletes the library file, its
.edl, and its.orig, then up to2empty parent folders inside the root. - It removes the TVHeadend copy with
removeRecordings, unlessdeleted_from_tvh_atis 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):
releaseHeldends each held session on another channel that thisclient_tokenstarted, with the reasonreplaced. 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 inlocalStorage(freetvarr.deviceToken), so it stays the same when a Home Screen app opens again.- When a session on the channel exists (
forChannel), the viewer joins it and nothing else runs. preflightChannelchecks the tuners. A refusal throws aLiveTvErrorwith status409.planForChannelreads the first service of the channel fromservice/streamsand the default languages fromconfig/load, then callspickStreams.sessions.startapplies the Stream limit, spawnsffmpeg, and opens the TVHeadend stream.
| Code | Status | Cause |
|---|---|---|
unknown-channel | 404 | The channel id is not in the guide channel list |
off-air | 409 | Every service of the channel is disabled |
no-tuner | 409 | No tuner is on the channel's multiplex and no tuner is idle; the body lists holders |
no-service, no-video | 409 | The channel has no mapped service, or the service has no video |
stream-limit | 409 | The 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:
| Video | Encoder | Plan |
|---|---|---|
| H.264 | VAAPI | vaapi, 720-line cap, deinterlace |
| H.264 | Software | transcode, 540-line cap, deinterlace |
| H.264 | Copy | copy |
| HEVC, MPEG-2, or VC-1 above SD | VAAPI | vaapi with hardware decode, 1080-line cap above 1080 lines, else 720 |
| Other video, or no VAAPI | Software | transcode; SD gets a 576-line cap |
- libx264 uses yadif,
-preset veryfast,-tune zerolatency,-crf 23, and-g 50. VAAPI usesdeinterlace_vaapi,scale_vaapi, andh264_vaapi -qp 24. pickAudiotakes the first normal audio track in a TVHeadend default language, else the first normal track. Audio is always stereo AAC at128k.- A service with
TELETEXTandTEXTSUBstreams gets captions whenffmpeghas thelibzvbi_teletextdecdecoder (detectCaptionDecoder). The page is theTEXTSUBPID minus0x2000; outside100–899it is801.
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 file | Value |
|---|---|
-hls_time, -hls_init_time | 2, 1 |
-hls_list_size | The LIVE_TV_BUFFER_MINUTES buffer in 2 s segments, at least 6 |
-hls_flags | delete_segments+independent_segments+omit_endlist+temp_file+program_date_time |
index.m3u8, live.m3u8, seg<N>.ts | Master playlist, media playlist, video segments |
live_vtt.m3u8, live<N>.vtt | Caption 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/:sessiontakes one viewer off; the last viewer ends the session.POST /api/live/:session/holdkeeps the session forLIVE_TV_BUFFER_MINUTES; with a buffer of0it does nothing, and the20 sidle rule ends a session that nobody fetches.POST /api/live/:session/unholdends the hold, so the idle rule applies again. A preflight or a file request does not end the hold.POST /api/live/:session/attentiontakes{ attending, viewer }for Watch tracking.vieweris 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
MediaSourceis absent and the browser can playapplication/vnd.apple.mpegurl. Otherwise it imports hls.js from/vendor/hls.mjswhen a stream starts. - The hls.js config is
liveSyncDuration: 4,liveMaxLatencyDuration: Infinity, andbackBufferLength: 30. Video starts when2 sare buffered, or4 safter metadata loads. - The player draws its own controls. A scrubber appears when the buffer allows at least
4 sof rewind. Double taps on the left or right third skip10 s(src/web/double-tap.js). - A hidden page sends
POST .../holdwithkeepalive, and a page that is visible again sendsPOST .../unhold. Apagehidethat does not persist sendsDELETE. - A fatal hls.js network error detaches the video and lets the preflight poll attach it again while the session lives, at most
2times in a row (liveErrorActionOf). The count resets when the video starts. withPeakBandwidth(src/live-tv.js) raises theBANDWIDTHof each#EXT-X-STREAM-INFline to a floor for the picture height:5000000up to576lines,10000000up to720, and16000000for1080or 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_RETUNES1,src/web/live-start.js). A second miss ends playback withStopped: 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".
listenForAirplaysetsairplayfromwebkitplaybacktargetavailabilitychangedandplayingOnTvfromwebkitCurrentPlaybackTargetIsWirelessonwebkitcurrentplaybacktargetiswirelesschanged.- The AirPlay action (
airplayActionOf,src/web/player-top-actions.js) callswebkitShowPlaybackTargetPicker. airplayReachHintOfadds a hint to thePlaying on your TVscreen when the page address is not a home address. Ats.netname or a100.64.0.0/10address getsUse your home address, or add the TV to Tailscale.Any other name with a dot, outside the local suffixes, getsUse 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:
- Wait
1 min, then read the idle signal every30 s. - Measure when the signal stays idle for
3 min. After30 min, measure anyway (longer than a merged guide build, about13 minon a DS220+), even during a recording or a heavy job. A live session, playback session, or ad scan still blocks the run. - Call
measure({ runs: 2 }). It runs the benchmark, pauses20 s, and runs it again. It keeps the result with the higher estimate, then the higher speed. Before the second run,stillIdlechecks 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. - 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 hafter a measurement, and1 hafter a failed run. - After each measurement, including Measure again, reset the
24 htimer 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()againstperformance.now(),createProcessCpuMeter). A clock that steps back reads as busy. - The one-minute
os.loadavg()divided by the processor count is below1.0. Other containers keep this near0.55on 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.
| Source | Effect |
|---|---|
LIVE_TV_MAX_SESSIONS | An integer 1 or more; replaces the default and caps the user choice |
| Benchmark estimate | Default, capped at the tuner count and at 4 |
| No benchmark | Default 2 for VAAPI, 1 for software |
Setting max_live_streams | User 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 withsharesWith), orunavailable. The client polls it every5 swhile Multiview is open.src/web/multi-view.jsholds the rules.pictureLimitOfcaps a phone layout at2pictures and other screens at4, 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_rank1,2, or3.liveStreamWeightOfgives the subscription weight50 - 10 × rank, so the main player has50and the companions40,30, and20. 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.
| Route | Purpose |
|---|---|
POST /api/recordings/:id/play | Start a session; body offset, replace, player, part_id, client_token (playLimiter) |
GET /api/play/:session/:file | Serve index.m3u8, play.m3u8, play_vtt.m3u8, seg<N>.ts, and play<N>.vtt |
POST /api/play/:session/heartbeat | Refresh the session; 404 with code: 'gone' after it ends |
POST /api/play/:session/attention | Set attending for watch tracking |
DELETE /api/play/:session | Stop the session |
POST /api/recordings/:id/position | Save the position (0–86400 seconds) |
Playback start
- Load the
recordingsrow, or the Plex item row for a Plex item id. playbackCandidateslists the libraryfile_path(statusdoneorpartial), then the TVHeadend file throughlocalPathFor.resolvePlaybackFilekeeps the first whose real path is inside a media, one-off, movies, or recordings folder; none gives410withcode: 'missing'.- Probe the file with
ffprobe(30 stimeout, cached by path, size, and time). - With no
offset,resumeStartForresumes fromplayback_position_sunless it is within30 sof the end (RESUME_END_MARGIN_S). planForFilemaps the probe ontopickStreams, 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.
| Session | watch_start | watch_end |
|---|---|---|
| Live | At session start, with the programme on air | One row per programme that overlaps an attended span of 60 s or more |
| Playback | At session start, with the start offset | One 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):
- Find the entry in
listActiveRecordings; none gives404withcode: 'not-recording'. growingSourceForuses the local file whenlocalPathFormaps the path, elseGET /dvrfile/<uuid>with aRangeheader.- Probe the source. An HTTP source copies its first
2 MBto a temporaryhead.tsforffprobe. - Start a playback session with a feed:
ffmpegreadspipe:0and writes2 ssegments.
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
| Route | Parameters | Used by |
|---|---|---|
GET /api/epg/image/:eventId | w | Guide cells, Live TV thumbnails, the programme sheet |
GET /api/epg/show-image | title, shape (poster or landscape), kind (movie, series, or one-off), w, c | For you, show pages, Change picture |
GET /api/epg/logo/:channelId | w (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.
| Answer | Status | Cache-Control |
|---|---|---|
| A found picture | 200 | public, max-age=86400 |
| A lookup still running | 404 | no-store; X-Art-State: pending |
| No picture | 404 | no-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).
| Request | Chain |
|---|---|
| Film | choice, Plex, recording, guide, online, derived shape, frame, derived shape, none |
| Series | choice, Plex, recording, guide, online, derived shape, frame, derived shape, none |
| One-off | choice, Plex, recording, guide, frame, online, derived shape, none |
Episode (recordingId) | recording picture, the title chain, frame, none |
| Episode, frame first | recording 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, Australia | the 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 save | the 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 least1.3:1) and is wide enough (MIN_WIDTHS):300px for a poster or a Plex picture,640px 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 (
portraitPadOfinsrc/show-poster.jsfor2:3posters,landscapeOfinsrc/image-thumbnails.jsfor16:9). - The frame step of a title takes up to
6of the newest files of the title (frameFilesForinsrc/library-titles.js): recordings that are imported (doneorpartial) and not purged, and Plex library items of the same kind, with afile_path.framePreferenceOrderOfinsrc/frame-grabs.jstries 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, orframe) sets the use of frames (Settings → Film and TV info → STILLS FROM RECORDINGS → Use stills: Off, When nothing else, Before series picture).offremoves the frame step from the episode chain, and the frame step of every title answers no picture.offalso addsstills-offto the settings key of the resolution fingerprint, so every saved title resolution runs again. A change betweenoffand the other values callspublishStillsChangeinsrc/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 therecordingId, 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 nomovieoverride) 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-off3 hcontest with no episode details is a guessed film. - A picture that fails to load with an error (a timeout,
429, or5xx) is not a miss.createProgrammeImageswaits60 sbefore it asks that source again, and keeps misses (404, not an image) for10min. When an earlier step failed with an error, a later picture that fits is saved for5min 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, andremembernever saves an origin that holdsX-Plex-Token. Every Plex picture loads through the photo transcoder. - The guide step puts the saved guide pictures of the title first (
titleOriginsFor, thenguideSourcesOf), then the guide images, at most4in 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 most1920px (plexResizedSourceOf), so originals over the4 MBimage limit still load. - The chain has
3 s(RESOLVE_BUDGET_MS); the airing and episode steps have1.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 throughloadUnlessCached, 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 (verdictweak) is kept aside: every chain uses it only when no other step, derived shape, or frame gives a picture. The title chain then answers stageweak(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'sweakanswer, before none. findTitleImageserves a chosen picture that fails to load from the chain without the choice. A saved origin that fails to resize keeps its row and answersfinalfor 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:
| Result | Next check |
|---|---|
| A picture that fits | 7 d |
| Derived shape, title card, no picture | 6 h, 24 h, 3 d, then 7 d while the fingerprint is the same |
| A changed fingerprint | At 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>.
frameForanswers with the saved frame. With no frame, it puts the file in a queue and answers pending. A<id>.nonemark older thanretryMissesBefore(a due title row) is deleted, and the file is grabbed again. A title pass givesretryMissesBeforeonly 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>.nonemark, no ffmpeg (ffmpeg -versionfails, as on an install outside Docker), or a file that the server cannot read answers with no frame.adPlanOfsets the ad plan of a recording fromad_status,ad_breaks_json, thead_removalof its series folder, thead_removal_enabledsetting, andimported_at:clear:ad_statusiscut,no_breaks, ordetectedwith no breaks.marked:ad_statusisdetectedwith breaks.waiting: a scan runs (scanning, orisAdJobRunning), or no scan result yet while ad removal is on for the folder and the recording was imported less than8 hago.frameForanswers pending and does not grab.ad-free: no ad data, the install country isau(countryForTimeZone(currentTimeZone())), andisAdFreeChannelmatches thechannel_nameof the recording: the first word isabc,abctv,abcnews,abckids,abcfamily,abcme, orabc1–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-freealso for a Plex library item with norecording_id(downloadAdPlanOf): an item with amanager(Sonarr or Radarr), or a file that is not a transport stream (.ts,.m2ts,.mts). A library item with arecording_idtakes the plan of that recording (filePlanOfinsrc/epg.js).unknown: any other recording, and a transport stream in Plex with norecording_idand nomanager.frameForanswers with no frame and does not grab.
- The queue runs one grab at a time.
ffprobereads the length of the file.programmeWindowOftakes half of the time the file runs pastduration_sas padding at each end. - With a
clearormarkedplan,adAwareOffsetsOfremoves the breaks from the programme window (programmeSegmentsOf) and moves each segment edge20 sin (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, then30%and70%of the longest segment, up to3offsets. The first usable frame is saved. No segment longer than40 sgives a.nonemark. - With an
ad-freeplan,frameOffsetsOfseeks to25%,40%, and60%of the programme, inside its middle80%. With no length, it seeks to120 s,300 s, and600 s.steadyUsableOfgrabs all3and keeps the usable ones.distinctFramesOfdrops frames whose32 × 18grey fingerprint differs from another by less than3%(the same ad or slate in two breaks). For each frame left, it grabs a second frame2 slater;steadyFrameOfkeeps the first frame that changed less than10%(SCENE_DRIFT_MAX). With none, the file gets a.nonemark. frameArgsOfrunsnice -n 19 ffmpeg -ss <offset> -i <file>for one frame throughyadif, at the display aspect, at most1280px wide, as a JPEG. ffmpeg gets30 s.isUsableFramereadssharpstats: the brightness must be from24to232, and the mean standard deviation of the channels at least18. When frames decode but none is kept, the file gets a.nonemark, unless the file is smaller than thesizeof the recording (still copying). When ffmpeg fails every time, the file waits1 hin memory.- A saved frame writes
<id>.jsonwithoffsetS,adAware,plan, andversion, and callsartFeed.publishfor the title, background and poster, with no stamp, so open pages ask again. The origin of version0isframe:<id>; a later version isframe:<id>-v<version>, so thumbnails and stamps change with the picture.frameForserves a saved frame only when its<id>.jsonhasadAware: trueorplan: 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.
watchGuidePicturesinsrc/epg.jsrunssaveGuidePicturesafter each guide load (onGuideLoaded), one run at a time, as the quiet jobguide-pictures.guidePictureCandidatesOfgroups the airings by title key (showTitleKey) with up to4distinct image addresses, earliest airing first.saveAllsetslast_seen_atfor 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 isunsaved.- It downloads one picture at a time. Each host has a
createHostLimiterwith a1 sgap and acreateCircuitBreakerfromsrc/outbound-http.js. A failed address waits24 h(404,403, not an image) or1 h(an error) in memory. encodeGuidePicturewrites WebP at quality72, at most1280px wide, toartwork/guide/<id>.webp(<id>: the first24hex characters of a SHA-256 hash of the address), then upserts theguide_picturesrow.saveAllskips an address that is a stand-in picture before and after the download, and saves no copy of it.- The origin is
guide-picture:<id>-v<saved_at in base 36>, so a new title copy changes the stamp.originForSourcegives the copy of an address,originForthe 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.
freeviewServiceOfpicks the service fromFREEVIEW_SERVICESby the country ofcurrentTimeZone():aureadsfvau-api-prod.switch.tvand/content/v1/channels/region/<region>;nzreadsfvnz-capi-prod.switch.tvand/content/v1/channels(one region,nz;/channels/region/*answers403). Other countries turn the step off.freeviewRegionOfmaps the zone to a region:Australia/Sydneytoregion_nsw_sydney, and likewise Melbourne, Brisbane, Adelaide, Perth, Hobart, Darwin, and Canberra, with their old aliases (Australia/NSW).Australia/Broken_Hillmaps toregion_nsw_broken_hill,Lindemanto Brisbane,Currieto Hobart,Euclato Perth, andLord_Howeto Sydney. Other zones turn the step off.listChannelTripletsinsrc/tvheadend.jsreadsmpegts/service/grid(sid) andmpegts/mux/grid(onid,tsid).dvbTripletOfwrites each asonid:tsid:sidin 4-digit hex, the form ofdvb_tripletin Freeview AU. Each channel also getsonid::sid(serviceKeyOf), the form of Freeview NZ, whosedvb_triplethas an empty TSID (222A::0514).- The step waits for
guideMerge.firstBuild()(holdFreeviewPicturesUntil), at most20min, so after a start it reads the windows that the merged guide build already read. The picture cache keeps at most2000windows and drops the farthest first. freeviewAiringsOftakes every airing from1 hago on a channel with a triplet, and marks the next2of each titlefetch.matchAiringsmatches thefetchairings first; a later airing matches only from a window already in memory, so it adds no request.matchAiringskeeps the triplets that the region lists (/content/v1/channels/region/<region>, cached24 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 within5min of an edge.matchListingtakes the listing that starts within5min of the airing and whose title agrees (titlesAgree: the same key without spaces, one key a word prefix of the other, or at least2shared words that are60%of the shorter title). It never takes a listing with another title.listingImagesOfgives the episode picture, unless other titles in the window share it (a channel placeholder), and the show picture.listingImageOftakes the show picture, else the episode picture. Addresses onimg-store-prod.switch.tvchange tohttps.- The show picture (else the episode picture) of each
fetchairing goes tosaveAll, 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 than200titles changed, oneartFeed.resettells every page to load all stamps again instead. The warmer resolves the titles after the job and sets the stamps. WhenlistChannelTripletsfails (for example HTTP403without the Admin right), the step is off: the log gets one line per new reason, andguide.pictureswarns with the reason and its fix (freeviewProblemOfreturns{ detail, fix };freeviewPictureProblemreads the last one). Thefreeviewstep of a guide airing serves the episode picture, then the show picture, of the match of that airing from memory (up to20000airings), 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 on2026-11-10:1,121of1,254guide titles match a Freeview listing; one full pass reads533windows in about534requests (6–7min at the500 msgap), at most about2,140requests a day; the first run downloads about1,065pictures (about4.5min at the250 msgap), then about150new pictures a day.
| Rule | Value |
|---|---|
| Client | freeviewClient: createOutboundClient with fvau-api-prod.switch.tv (500 ms gap) and img-store-prod.switch.tv (250 ms gap) |
| Window | 15 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) |
| Failure | A 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 itssource_url. A recording copy (recording:<id>) is checked by its own bytes under the keyrecording:<id>, and by the file name of itsimage_urlfor thenamerule. upload:,frame:, andplex:origins, Plex addresses with a token, TVmaze, Wikipedia, and TMDB addresses are not checked (ok).loadreads an origin and answers no picture for a stand-in, and the picture withverdict: 'weak'for a title card. The resolver, the recording save, and the art pool load through it. The readers (readersinsrc/epg.js) are private to the gate.loadOwnerChoicereads without a check. Change picture and a chosen picture (stagechoice) use it, so an owner choice is never screened.servedThumbnailchecks the known verdict before it reads the image cache, so a cached thumbnail of an address that became a stand-in is not served.loadUnlessCachedanswers 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 asok. Otherwise it reads throughload.- 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. recordingArtleaves 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:
| Reason | Rule |
|---|---|
name | The file name holds default_program_image (or programme) or a logo word |
repeated | Titles 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 |
transparent | At least 20% of the picture is transparent (alpha below 128 on a 64 × 36 sample) |
logo | The fingerprint is within 10 of 64 bits of the fingerprint of a channel logo |
pictureTraitsOfdecodes the picture once, to at most256px. The fingerprint (pictureHashOf) is a64-bit difference hash of that copy: on black, with its plain border trimmed (sharptrim, threshold20), as9 × 8grey 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 (
noteTitlesinannounceGuideLoaded).runGuidePicturesinsrc/epg.jsnotes the fingerprint and mark of each channel logo (getChannelImage, once per channel and logo list).setLogoskeeps them in the settingpicture_logo_traits, andloadreads that setting, so after a restart the logo and title-card rules work before the first run. A logo fingerprint with fewer than8or more than56set bits is not used. judgecomputes 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 inpicture_checks. A row saved before0051has no marks, so the next check with a picture measures it again. A picture that cannot be decoded is saved with an emptyhashand emptymarks, 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,
forgetPlaceholderPicturessaves 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 isnameorlogo. It marks due theart_resolutionsrows 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 notweak(markResolutionsDue). It gives a newprogrammestamp 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 settingstand_in_airing_sources, so a restart bumps nothing new). It sends the new stamps as art events (announcePictureChanges; oneartFeed.resetpast200titles). guide.picturescounts a title as without a picture when its only guide address is a stand-in picture, and leaves outart_resolutionsrows with a stand-in origin.listingImagesOfinsrc/freeview-au.jsstill 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 of5windows (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 than28, 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 a16 × 8coverage grid of that cluster. - Detail (
detailOf): the share of pixels whose step to the right and down neighbours is more than16. - 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.8or more (box aspects within1.43×), or - its detail is below
0.12and a corner mark is the same mark (same window, box within3px, aspect within1.25×, at most4of128bits apart, at least12bits set) as in pictures with detail below0.12from at least2other 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.
- A request that answers pending starts a follow-up in
createArtResolver. The follow-up resolves the title, or the guide airing or episode, again after2 s,15 s, and60 s, with a20 sbudget each time, and stops at the first answer that is not pending. The first picture after a pending answer callsonResolvedwith no stamp, also when the picture is the saved one (for example, after a restart while the Plex list loads). - A picture whose resize runs past the
SHOW_IMAGE_BUDGET_MSbudget answers pending;publishWhenRenderedinsrc/epg.jscallsartFeed.publishwith no stamp when the resize ends. remembercompares the new origin and transform with the saved row (pictureChangeOf). A new picture, a changed picture, or a picture that is gone callsonResolvedwith{ key, kind, stamp }.keyis the client show key (showKeyOf);kindisposterorbackground.stampis the first10hex 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 for24 hunder the URL without a stamp. A first picture needs no stamp: a404is 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.- Guide airing and recording answers have no row, so each title also has one
programmestamp inprogramme_picture_stamps(createProgrammeStampsinsrc/programme-stamps.js):10random hex characters, new on each change.announcePictureChangesinsrc/epg.jsgives a newprogrammestamp 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 a404orno-cache. artFeed(src/art-feed.js) keeps the last500changes in memory, each with a sequence number. A cursor is<boot id>.<sequence>.GET /api/activity/stream?topics=artsends anartevent at once, then at most every2 s(ART_PUSH_MS) while changes come in:{ cursor, reset, stamps }. A batch keeps the newest change per title and kind. Withsince=<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 the500kept changes getsreset: true.GET /api/library/artwork-stampsmerges the owner choices with the saved picture stamps and theprogrammestamps (mergedStampsOf,resolvedArtStampsinsrc/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.
| Event | Client |
|---|---|
A change with a stamp | setStamps saves the stamp (background, poster, or programme), so every URL built with stampedShowImage changes |
| Any change | applyResolvedArt adds 1 to the tick of the title and kind (artResolvedTickOf) |
The first batch, or reset | artStreamResets 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.
| Source | Code | Rule |
|---|---|---|
| Chosen picture | chosenOriginOf in src/epg.js | Reads show_artwork_choices; posters as they are, backgrounds on a 16:9 canvas when narrower |
| Plex | plexShowSources in src/show-artwork.js | art 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 |
| Recording | createLibraryTitles in src/library-titles.js | Saved recording pictures of the title, newest first |
| Guide | imagesByTitle of the guide | Images of the title's airings, earliest first |
| TVmaze | tvmazeArtworkFor in src/show-artwork.js | The widest background image, then the show image; not for films |
| Wikipedia and TMDB | createFallbackArtwork in src/fallback-artwork.js | Online 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.
- With a TMDB key and stored external ids, the lookup goes straight to TMDB.
- Otherwise it searches Wikidata (
wbsearchentities), then Wikipedia, for each title variant, and keeps items with the same title key. - One SPARQL query keeps films (
Q11424) and television programmes (Q15416), with the year, the English article, and the TMDB and IMDb ids. rankEntitiesscores the items by year fit, database ids, and search order;matchEvidenceOfmust accept the article text.- 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 honly, so TMDB is asked again. - 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
| Store | Table | Hit | Miss |
|---|---|---|---|
| Wikipedia and TMDB pictures | artwork_lookups | 30 d | 7 d while the evidence stays the same; a due title asks again |
| Plex and TVmaze pictures | show_artwork | 30 d | 7 d; a due title asks again |
| Change picture pools | art_pools | 7 d | 1 h |
| Ratings, credits | programme_ratings, programme_credits | 30 d | 7 d; 6 h for a film with no guide details (no-guide-details) |
| TVmaze series scores | programme_ratings (tvmaze:series:) | 7 d | 7 d |
- Keys start with
wide-v1:and hold the mode (tmdbwith a key,openwithout), 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 dold. 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 always0; the retry steps are those of the picture resolver. - A failed lookup is not stored; the key waits
10min in memory. - Routes wait for a lookup within a budget, then answer pending:
1.5 sfor guide images and for ratings,3 sfor a show picture,6 sfor 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_resolutionsrow, then read the cache underart:<shape>:<transform>:<origin>. - A guide airing resolves through the airing memory (Picture resolver). On a miss, the airing chain loads each origin through
loadUnlessCachedwith 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 aplex: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:
| Tier | Pictures | Widths |
|---|---|---|
home | Home hero candidates; the in-progress and New recordings episodes (picture); On now airings | 768, 1280, 1920; 384; 384, 768 |
for-you | For you top pick and row items | 384, 768 |
recordings | Library shelf posters and cards | 384 |
guide-today | Guide cells with a picture, from now to 24 h ahead | 192 |
scheduled | Upcoming recordings | 384 |
show-heroes | Show page heroes of library shows | 768 |
show-posters | Show page posters of library shows | 192 |
due-titles | Show 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-week | Guide cells with a picture, 24 h ahead and later | 192 |
frames | Recordings with no saved picture and a file, newest first, up to 500 (the episode route grabs a frame) | 384 |
- Each URL is checked once per run with the
isWarmcheck of its route (createImageWarmCheckinsrc/image-routes.js); it renders nothing and makes no web request. A show picture is warm when the choice or theart_resolutionsrow is not due, the fingerprint of the local steps (Plex, recording, guide) still matches, and the thumbnail is in the cache (peekincreateArtResolver,isShowArtWarminsrc/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 underrecording:<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. - A cold URL runs its route inside
runAsBackgroundWork(src/background-work.js, anAsyncLocalStoragestore). One URL runs at a time, so there is one render at a time. - Before each URL, the warmer waits
5 sat a time while one of these runs: a live or playback session, an ad scan, async,import,ads, orguide-picturesjob, a queued frame grab,4or more background lookups, or an event-loop delay p99 over50 msin a10 swindow (createLoopPressure). - 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.warmfile beside it, so the share survives a restart; a page read deletes it. - A URL that answers pending waits for the background lookups to end (up to
10min) and runs once more at the end of the run. - 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()andonProgressgive{ 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.
| Trigger | Last active under 3 days ago | 3–14 days ago | 14 days ago or more |
|---|---|---|---|
| For you result (new items only) | The new items | The new items | Nothing |
| Guide load, sync finished, Plex watch sync done | Top and next tiers | Top tiers | Nothing |
| Visit window | Top and next tiers | Nothing | Nothing |
Nightly, 03:30 | All tiers | All tiers | All 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 currentimage_focusrow. src/image-focus-worker.jsruns as a child process at priority19,16pictures per run. It runsassets/models/ultraface-rfb-320.onnxthroughonnxruntime-node(ONNX Runtime) and keeps faces with a score of0.7or more. With no face, the focus is thesharpattention point, else the centre.- The worker pauses
10min when free memory falls below400 MB, and30min after a failed run. image_focuskeeps the newest20000rows.methodisfaces,attention, orcentre.GET /api/image-focus?k=<key>takes up to40keys and returns{ enabled, items }. The settingface_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:
| Host | Concurrency | Gap |
|---|---|---|
www.wikidata.org | 2 | 200 ms |
query.wikidata.org | 1 | 1000 ms |
en.wikipedia.org | 2 | 200 ms |
upload.wikimedia.org | 2 | 250 ms |
api.themoviedb.org, image.tmdb.org | 4 | 50 ms |
api.tvmaze.com | 1 | 500 ms |
static.tvmaze.com | 2 | 100 ms |
www.tvmaze.com, www.themoviedb.org | 1 | 1000 ms (HEAD / link checks only) |
| Rule | Value |
|---|---|
| Address | https only, a host from the list, at most 3 redirects that stay on the list |
| JSON request | 8 s timeout (20 s for SPARQL), 2 MB limit, 2 retries |
| Image request | 10 s timeout, 4 MB limit, JPEG, PNG, WebP, or GIF, 1 retry |
| Queue | Up to 200 waiting requests per host; more fail with queue-full |
| Background | createHostLimiter runs urgent tasks before background tasks; reservedForUrgent keeps that many places for urgent tasks; promote(id) moves a background task to the urgent queue |
| Retries | On 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) |
| Jitter | A 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, 410 | The call returns null |
| Circuit breaker | 5 failures in a row open the breaker for 60 s, doubling per trip up to 30 min |
| User-Agent | Freetvarr (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.
| Setting | Default | Effect |
|---|---|---|
ratings_lookup_enabled | On | Scores |
reviews_lookup_enabled | On | Review snippets; they need a TMDB key |
tmdb_api_key | None | Films 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/moviewith 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, andMiniseries, or a TVmaze type outsideScripted,Animation, andDocumentary, ends with the missnot-story. - A TMDB score needs
50votes or more (MIN_TMDB_VOTES). A TVmaze score israting.averagewithvotes: 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:
| Source | company | year | minutes | language |
|---|---|---|---|---|
| TVmaze series | network.name, else webChannel | premiered | averageRuntime, runtime | language |
| TMDB series | networks[0] | first_air_date | episode_run_time[0] | original_language (Intl.DisplayNames) |
| TMDB film | production_companies[0] | release_date | runtime | original_language |
| Wikidata film | P272 label | earliest P577 | P2047 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:
wbsearchentitieson the title, and a full-textlist=searchfor<title> haswbstatement:P31=Q11424sorted byincoming_links_desc.candidateIdsOfkeeps items whose label or alias has the sameshowTitleKey.- One SPARQL query (
filmYearsQueryOf) keeps the items that are an instance of aWIKIDATA_FILM_KINDSclass, with their earliestP577year. The request year, else the single guide release year, must be within1year. - For up to
3films,wbgetentitiesreads the claims:P161cast (ordered by theP1545qualifier, character fromP4633orP453, deprecated statements skipped),P57directors,P58writers,P162producers. A secondwbgetentitiescall reads the labels (en, elsemul) andenwikisitelinks of those items. - One film is the answer. With more than one, the answer is the only film whose description, cast, characters, and crew pass
matchEvidenceOfagainst 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:
- About: the image with the close button (
.programme-sheet-close), the title, the episode line (sheetEpisodeLineOf, which drops an episode title of the formEpisode N), the airing line (sheetAiringLineOf), the synopsis, andMoreInfo. - Recording: one
ui-groupcard (.programme-sheet-recording). It holds the status row, the cancel rows (cancelActions), theui-segmentedchoice fromsheetStrengthsFor,PaddingRows, Keep, Any channel, and Advanced. Advanced is a<details>whose summary uses the sharedui-disclosure-rowstyle. - Actions: Record (
primaryActionOf), Watch from the start, and Watch live. - Menu: Show in TV guide, the movie correction, and the For you hide items, as
library-menurows.
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).
serveShiftedFeedrecords 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_classificationsandprogramme_categories(title_key,start_ms,shift_hours). A +1 copy stores its label withshift_hours1, so it never replaces the base channel's label at the same time. Readers, including the sync and upcoming timers, takeshift_hoursfrom the channel name (timeshiftHours). Rows older than3 dare deleted after each feed load. fallbackClassificationuses the TVHeadend rating label, else maps the TVHeadend age15toMA15+and18toR18+.- The sync stores the label in
recordings.classificationand keeps the first label. Each prune copies labels into recordings with anulllabel. - 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).
| Route | Does |
|---|---|
POST /api/discover-plex | GDM discovery: a UDP broadcast to port 32414, replies collected for 2 s (Plex GDM); needs host networking |
POST /api/plex-detect-token | Reads PlexOnlineToken from Preferences.xml, saves it as plex_token with plex_token_scope = 'this-machine', and returns plex_token_set |
POST /api/plex-sections | Lists the sections (key, title, type, locations) |
POST /api/plex-libraries, POST /api/plex-libraries/create | Plans 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-refresh | Starts a section refresh |
- The path of
Preferences.xmlis the settingplex_prefs_path, elsePLEX_PREFS_PATH, else/plex/Library/Application Support/Plex Media Server/Preferences.xml. The file name must bePreferences.xmlor end in-preferences.xml. storedPlexTokenFor(url)gives the stored token to a URL only under the rules in Secret binding; otherwise the route answersPaste the Plex token for this server.- Requests to Plex use axios with a
5 stimeout; a section item list uses15 s. - After a sync, each kind with an import refreshes its section with
GET /library/sections/<id>/refresh: TV throughnotifyPlexSectionRefresh, one-offs and films throughrefreshSection. 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
doneorpartialrecordings that are not deleted, and items in the three Plex sections. matchPlexIteminsrc/library-actions.jsscores 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 every2min), 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,
500per page, up to400pages (MAX_PAGES). It runs for a manual trigger, on the first run, when the last full pass is24 hold, or after1 hwhen rows lack a snapshot. A quick pass reads items viewed since the last run less2min.
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:
| Rule | Detail |
|---|---|
| First run (no snapshot) | Watched on either side makes both watched; the side with a resume point wins |
| Later runs | The side that changed since the snapshot wins; when both changed, Freetvarr wins for watched and the newer wins for resume points |
| Resume points | Used only when both sides are unwatched; offsets within 15 s are equal |
| End margin | A Plex resume point within 30 s of the end marks the recording watched |
| Toggles | plex_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_itemsrow (rating_key,part_id). A full pass deletes rows that it did not see, except in a section that stopped atMAX_PAGES; that section keeps its unseen rows, and the run log warns.recording_idis set when the file is a Freetvarr recording. localPathOfinsrc/plex-library.jsmaps 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 least2segments).- Files deleted through Freetvarr stay out of
library_itemsfor30min, in memory, so a scan before Plex notices the delete does not save them again. - The scan links each row with no
recording_idto its Sonarr or Radarr manager, and writes Plex and Sonarr GUIDs toexternal_ids. src/library.jsmergeslibrary_itemswith 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 (doneorpartial, nolibrary_state) takes the Plex episode; afailedorskippedrecording of that episode is dropped and the Plex episode stays. Any other item becomes a row with the idplex-<ratingKey>.- A watched mark or resume point on a
plex-row setspending_push(scrobble,unscrobble, orprogress); 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.
| Route | Does |
|---|---|
GET /api/arr | { sonarr, radarr, unmonitorOnDelete } with hasKey and keySource; never the key |
PUT /api/arr | Saves URLs, keys (^[A-Za-z0-9]{16,64}$), and the switch; starts a full watched sync |
POST /api/arr/find | Sends 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:
- With
arr_unmonitor_on_deleteon, unmonitor the episodes (PUT /api/v3/episode/monitor) or the movie (PUT /api/v3/movie/editor). A failure stops the delete. - Call
DELETE /api/v3/episodefile/<id>orDELETE /api/v3/moviefile/<id>. A404counts as done withmissing. - On any other failure, monitor the items again. On success, delete the
library_itemsrows 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.
| Stage | Module | Mechanism |
|---|---|---|
| Events | src/user-events.js, src/user-events-log.js | Writes rows to user_events |
| Profile | src/for-you-profile.js | Folds events and recordings into one affinity per show |
| Scoring | src/for-you.js | Scores each airing, then groups the best airing per show into sections |
| Similarity | src/for-you-similarity.js, src/for-you-engine.js | Compares programme texts by BM25 or by embedding vectors |
| Upkeep | src/for-you-service.js, src/series-ratings.js | Runs the embeddings, the genre lookups, and the TVmaze series scores once a day |
buildForYourunscategorySectionsOfon a cold start too, fortaste, and drops its sections.user_eventskinds: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, androw_hidden_undo.thumb_clearempties both thumbs andfewer_like_thisof a show; the client sends it when More like this turns off, and Show again writes it withnot_interested_undowhen the newest thumb is down. Hidden shows listsnot_interestedshows of the last90days and shows whose newest thumb is down.recording_deletedmeta carrieswatched,season,episode, andwatched_at.profileOfcounts a watched deletion as a finished episode with the keyrec:<recording_id>.- Hide from Finish what you started writes
row_hiddenwith meta{ row: 'finish-started' }, and Undo and Show again writerow_hidden_undo.isRowHiddeninsrc/for-you-profile.jsholds while the hide is newer than the last watched episode (lastWatchTs, episodes with a fraction of0.25or more;WATCHED_FRACTION). With history paused, no watch is written, so the hide stays. It changes no affinity.GET /api/for-you/hiddenadds each row hide with the series key<row>:<show key>, arow, ashowKey, and ashowTitle. - Fewer like this writes
fewer_like_this; turning it off and Undo writefewer_like_this_undo, which empties only the fewer marks. The client no longer writesthumb_down, and olderthumb_downrows keep hiding their show.fewerWeightOfinsrc/for-you-profile.jsis the decay of the newestfewer_like_this(half-life60days), or0when a laterthumb_upor athumb_clearexists or the decay is under0.05(FEWER_MIN_WEIGHT).fewerShowsOfsorts the marked shows by weight, strongest first, before the first12become anchors.fewerFactorOf(weight)is0.2 + 0.8 × (1 − weight)(FEWER_FACTOR0.2, the same asMUTE_FACTOR).scoreAiringmultiplies the show's own score by that factor, and by the factor of the nearestfewer_like_thisshow (fewerAnchorsin the similarity context, weight = similarity score × the show's weight). The nearest-show factor skips a show with an affinity of0.25or more (LIKED_AFFINITY) and a show with athumb_upnewer than the anchor's mark.withFewerCategoriesmultiplies 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_enabledstops writes whenfalse, except the choices inCHOICE_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/eventsclears the history. Rows older than730days, andsuggestion_shownrows older than30days, are deleted on the cron tick. profileOfdecays each event with a half-life of60days. A show with3or more starts, under15%finished, and no thumbs up is abandoned and keeps0.3of its affinity.- Fewer than
5engaged shows (COLD_START_SHOWS) give a cold start: sectionsready-to-watch,finish-started,tonight-movies,top-rated-series,premieres,top-rated, andmovies. A warm response addscoming-up,new-seasons, andmight-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_ORDERinsrc/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-watchlists recordings and takes no show from the airing sections, exceptfinish-started, which skips a show that has aready-to-watchitem. A section with no items is left out. - The new sections hold up to
12items (ROW_LIMIT).GET /api/for-youreturns up to12items per section by default and up to20withlimit.
| Section | Selection | Order |
|---|---|---|
ready-to-watch | Recordings 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 show | Show affinity, then the newest recording |
finish-started | Shows 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 rejects | Start time |
tonight-movies | Films 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.5 | Score plus 0.3 times the weighted TMDB score above 6.5 |
top-rated-series | Series 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 runtime | TVmaze score, then weight |
isBehindWatchedinsrc/for-you.jsrejects an airing with a guideseries_nobelowmaxSeason(the highest recording season, from PlexparentIndex), or with anepisode_noat 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 below1900, or both1900or more).finish-startedskips these airings, andcoming-upskips entries withbehindset.- All sections except
ready-to-watchleave out news and sport where they list episodes, and skip airings that are scheduled, recorded, covered by a series rule, or hidden.ready-to-watchitems carrykind: 'ready', arecordingId, 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-seriessection carriescredit({ 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.jsweights a film score as(votes / (votes + 1000)) * score + (1000 / (votes + 1000)) * 6.5, and keeps at most10films.scoreAiringadds weighted features (affinity,interest,new-season,back,premiere,habit,hour,genre,similar,pinned,prime,image) and applies a penalty for dismissals, thumbs down, andfewer_like_this.src/series-ratings.jssearches TVmaze (GET /search/shows) for each title in the next7days thattitle_genresmatched to TVmaze, when the settingsfor_you_genre_lookupandratings_lookup_enabledare both on. It keeps a result only when the same-title show is dominant (dominantShowOfinsrc/top-rated.js: weight50or more and3times the next same-title show), or when it is the only same-title show from the country of the time zone. It waits1 sbefore each request, usesartworkClientwith an8 stimeout and a256 KBlimit, and looks up at most300titles per run. It storesscore,weight,type,runtime, and the TVmaze page inprogramme_ratingsundertvmaze:series:and the title key for7days; no confident match stores a miss for7days. Withratings_lookup_enabledoff,loadSeriesRatingsreturns no scores, sotop-rated-seriesis empty.60 safter startup,warmSeriesRatingsruns one refresh whenprogramme_ratingshas notvmaze: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 after5failed requests in a row. Upkeep runs it after the genre lookups. The snapshot stampseriesRatings(row count and latest expiry) makes a new score start a new build.src/genre-enrichment.jsstores TVmaze and Wikidata genres intitle_genreswhen the settingfor_you_genre_lookupis on.lookupOrderOfmerges 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 after5failed lookups in a row.
similar uses one of three levels:
| Level | Method | Model |
|---|---|---|
basic | BM25 vectors over titles and descriptions | None |
standard | Embeddings through @huggingface/transformers in a child process (src/for-you-embed-worker.js) | Xenova/all-MiniLM-L6-v2, q8, 384 dimensions |
plus | Embeddings from Ollama when it lists an embedding model, else the local model | Xenova/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.
| Part | Module | Mechanism |
|---|---|---|
| Catalogue | src/for-you-category-catalogue.js | Format and topic categories, each with facets; topic facets have 2 to 4 example sentences (prototypes) |
| Known shows | src/for-you-known-shows.js, src/data/known-shows.json | Labels of about 600 free-to-air shows, keyed by show key |
| Label rules | src/for-you-label-rules.js | Maps TVmaze and Wikidata genres, title words, guide genres, and genre bytes to categories |
| Tagging | src/for-you-categories.js | Gives each title one format, up to 2 topics, a sport code, and an origin country |
| Affinity | src/for-you-categories.js | Sums the household's events per category |
| Rows | src/for-you.js, src/for-you-categories.js | Picks the categories with enough share and enough programmes, then ranks and dedupes the items |
| Vectors | src/for-you-engine.js | Embeds 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):scriptedholdscomedy,drama,crime-drama,soaps, andsci-fi-fantasy;unscriptedholdsreality,quiz,documentaries,lifestyle,talk-shows, andpanel-shows;otherholdsnewsandkids.kidsandnewsare formats that are never rows. Format facets have no prototypes. - Topics:
cooking,home,gardening,politics,true-crime,police-rescue,medical,health-and-lifestyle(shown asHealth),dating,science-and-technology,nature,travel,history,military-and-war,local-life,music-arts,entertainment-news,mystery-and-paranormal,engineering-and-machines, andbusiness-and-money. Hobbies(hobbies) holdsmotoring,fishing, andantiques. Each one is its own row, named after the facet.Sportholds 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), andother-sport.other-sportis never a row. Sport facets have no prototypes.shoppingandreligiontake titles but are never rows.createCategoryIndexsorts the groups withcompareCategoryInfos: formats in catalogue order, then topics and sports by their shown label (localeCompare), withother-sportlast. Settings, the Change categories sheet, and the hidden categories use this order.occasionsInYearOrderOfsorts 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 fromIntl.DisplayNamesandthebefore names such asUnited Kingdom. Its prototypes fill{in}within <country>. With no known country, the row isLocal lifeand{in}is empty. sportLabelOfnames each sport row by the sport:aflisAustralian rules,rugby-leagueisRugby league,rugby-unionisRugby union.soccerisFootball (soccer)inau,Soccerinusandca, elseFootball;american-footballisFootballinusandca, elseAmerican 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.
isFilmAiringinsrc/genre-enrichment.jsreturnsfalsefor 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_genresrecord:type:<TVmaze type>, the plain TVmaze genres (only for atvmaze:source),wd:<Wikidata genre>tokens, andcountry:<code>as the origin. A lookup writeslookup:2when TVmaze and Wikidata both answered, orlookup:partialwith a7-day expiry when Wikidata failed or was skipped; records with neither token are looked up again. After5Wikidata failures in a row, a run uses TVmaze only.rememberTvmazeShowkeeps thewd:,country:, andlookup:tokens of the record. An episode title that reads like a description (isDescriptionLike) is not an episode detail (hasEpisodeDetailsinsrc/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):
titleKindOfsorts each title intofilm,kids,sport,fiction,factual, orunknown.kidsis an OP-39 genre code in group0x5, akidsgenre tag, a kids guide genre (such aschildren's), or airings in kids slots only. A channel whose name sayskidsis a kids slot; when its name also saysfamily, only airings before19:00local time (FAMILY_EVENING_HOUR) are.sportis a TVmaze typeSports, asportgenre tag, or a sport guide genre (SPORT_GUIDE). A live event title isfactual. TVmazeScriptedisfiction; other TVmaze types arefactual. Films take no category.- An owner override (
programme_category_overrides, read byloadTitleGenresascategoryOverrideon the record) comes first. It sets the format and topics, and the origin still comes from the record or the list. The formatsport-formatwith a code sets that sport code above the keywords; any other format removes the automatic sport code and makes the titlefactual. The tags carrycustom: true. - The known-shows list (
knownShowOf) matches the exact show key of the title, after title aliases, and never a prefix, soShark Tanknever matchesShark 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 itschannelsin a channel name, then by the install country, else none. A list entry sets all the labels of the title. A list format ofkidsmakes the titlekids; a fiction format makes itfiction. - A
sporttitle takes its code from the title and channel names first (sportCodeOf). League, competition, and show names map to the sport, such asNRLW,State of Origin, andNRL 360torugby-league. The order isrugby-league,afl,rugby-union,american-football,cricket,soccer, then the other sports. A plainfootballissoccer, oramerican-footballinusandca, and no code inau. When no keyword matches, a guide genre that names the sport gives the code (GUIDE_SPORT_CODES). Asporttitle with fishing words isfishing. With no code, the list labels the title; with no list entry, the title isother-sport. A sport code never comes from TVmaze, the list, or embeddings. - Without a list entry,
evidenceLabelsOfreads 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), anddocumentarieswhenhasStrongDocumentaryEvidenceis true. The topics are the title-word topics, then the exact-genre topics, then the guide-genre and genre-byte topics, at most2. A fiction title takes no topic. - Exact genres: a TVmaze
Panel Showtype or a Wikidatapanel gamegenre givespanel-shows. A TVmazeComedygenre or a Wikidatasitcomorcomedygenre givescomedy, before the TVmaze type. Then the type:Realityisreality,Game Showisquiz,Talk Showistalk-shows, andNewsisnews. A fiction title with a TVmazeCrime,Legal, orEspionagegenre iscrime-drama, elsesoapswithSoapor a Wikidatasoap operaortelenovela, elsecomedywithComedy, elsesci-fi-fantasywithScience-Fiction,Fantasy, orSupernatural, elsedrama. A factual TVmazeRealityshow withRomancegets the topicdating;Romancealone gives nothing. TVmaze genres give topics:Supernatural,Food,DIY,Nature,Travel,Medical,Music, andHistory. A TVmaze typeDocumentaryalone gives no format. documentariesneeds a Wikidata genre withdocumentary, a guide genre such asdocumentaryordocumentary series, the ETSI byte0x23, or the AU nibble0xE. The guide genredocumentary & factualis not enough.- Guide genres are folded to lower case, with
&decoded and split on/(guideGenreKeysOf).special interestandentertainmentgive nothing. - Genre bytes: the ETSI table, plus in
authe nibbles0xC(comedy),0xD(drama), and0xE(documentaries), which are reserved in ETSI. Free-to-air channels in Australia send ETSI bytes such as0x14for sitcoms, so the full Freeview AU table is not used. The nibble0x8givespolitics. - Embeddings run only when steps 3 to 9 give no topic and the format is not
quiz,panel-shows,news, orkids. The title vector is the mean of up to6of its text vectors. A topic facet scores the highest dot product with its prototypes. A topic needs a score of0.42(TOPIC_FLOOR) or more, and a second topic must be within0.08. Embeddings never give a format, a sport,fishing, orshopping. - Weights: with a format and topics, the format weighs
0.4and the topics share0.6(embedding topics by the ramp from0.30to0.45). A format alone or topics alone weigh1. A title is a row member only at a score of0.42or more; rule and list labels score1. - A
newsformat with no topic makes the title a bulletin.mostSpecificCategoryOfgives 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):
| Event | Weight |
|---|---|
A recording, or record_request | 3 |
watch_start or watch_end | 2 |
suggestion_accepted | 1 |
programme_opened | 0.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_iduses the episode of that recording. - Each count decays with the
60-day half-life ofprofileOf. - 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),3or more titles with weight, and4or more upcoming members. At most3category rows show, highest share first. - The sport row needs codes with a share of
4%or more (ROW_SHARE),1or more titles, and4or more upcoming airings. One code gives a row named after the code; more codes give one row namedSport 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:sportAiringKindOfranks matches first, other shows about the sport next, and replays last, then by start time. It keeps at most3airings 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
12items show in earlier sections, or when fewer than4items are left. - The section key is
category-<key>(orsportforSport this week); the title is the category name. Each item carriescategory(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) sendscategory_boostedwith the series keycategory-<key>; Undo sendscategory_unboosted. A boost multiplies the category share by1.5once; 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, sendscategory_muted. Undo and Show again sendcategory_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.2for90days, or until an unmute. After90days the share is back to normal. A mute or boost ofsportcovers every sport. - The setting
for_you_categories_offholds 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 stampcategoriesOffstarts a new build when the list changes. GET /api/for-you/categorieslists every category and sport (categorySettingsOf) withonand, for a format,format: true: off when in the list or muted in the last90days. The client groups them intoFormats,Topics,Sport, andSeasonal.PUT /api/for-you/categories/:keywith{ on }updates the list; turning a category on also sendscategory_unmuted, and for a sport also unmutessport.GET /api/for-you/hiddenlists the muted categories of the last90days (hiddenCategoriesOf) with the hidden shows; a category entry has the series keycategory:<key>and acategoryKey.DELETE /api/for-you/categories/:key/muteunmutes a category in the catalogue, orsport; any other key returns404.DELETE /api/for-you/hidden/:seriesKeyonly handles shows.- The client hides the cards of a muted row at once (
forYouMutedCategoriesinsrc/web/shared/for-you-session.js). - Migration
0052deletes thetheme_*rows ofuser_eventsand the settingfor_you_themes_off, and createsprogramme_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 thetitle_genresrecord.originis{ code, name, source }, withsourceTVmaze,Wikidata, orbuilt-in list.choiceslists every format and the topics that can be rows.PUT /api/for-you/categories/show/:showKeywith{ format, topics }saves an override. The format is a format key ornull, the topics are at most2topic keys, and one of them must be set; anything else returns400.{ 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 holdsformatsport-formatandtopics_json{ "sport": "<code>" }.DELETEremoves the override. Both clear the For you cache. A title with a sport code has the formatsport-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.
| Part | Module | Mechanism |
|---|---|---|
| Occasions | src/for-you-occasions.js | The occasions, with countries, dates, windows, words, and prototype sentences |
| Dates | src/for-you-occasions.js, src/data/occasion-dates.json | Code rules for fixed dates, nth weekdays, and Easter; a table for the lunar dates |
| Tagging | occasionMatchOf in src/for-you-occasions.js | Checks each airing against the words of one occasion |
| Row | seasonalSectionOf in src/for-you.js | Picks the occasion, collects and ranks the airings, and checks the row size |
| Vectors | categoryTextItems in src/for-you-engine.js | Embeds the occasion prototype sentences with the category prototypes |
Dates:
easterOfuses the anonymous Gregorian algorithm (Computus).nthWeekdayOfgives days such as the second Sunday in May.src/data/occasion-dates.jsonholds the dates of Lunar New Year, Eid al-Fitr, Hanukkah, Diwali, and Matariki for2026–2040.scripts/build-occasion-dates.mjswrites it. The script takes the path of a folder withdate-holidaysinstalled (npm install --no-save date-holidays). It gives the calendar code ofdate-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 nodate-holidaysdata. 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 creditsdate-holidaysand the Act. Freetvarr has no runtime date dependency. A test fails when the current year is within3years of the last year of the table.- The days are calendar days in the install time zone (
localDayOf). A window runs frombeforedays before the occasion day toafterdays after it. The first day of a day that starts with a daylight saving jump is its first real instant (localMidnightMsOf).
| Occasion | Key | Countries | Day | Window |
|---|---|---|---|---|
Lunar New Year | lunar-new-year | All | Table | 5 before, 1 after |
Waitangi Day | waitangi-day | nz | 6 February | 3 before |
Eid al-Fitr | eid-al-fitr | All | Table | 5 before, 1 after |
Easter | easter | All | Easter Sunday | 7 before, 1 after |
Anzac Day | anzac-day | au, nz | 25 April | 3 before |
Mother's Day | mothers-day | au, nz, uk, us | Second Sunday in May; in uk, 21 days before Easter Sunday | 3 before |
Father's Day | fathers-day | au, nz, uk, us | First Sunday in September; in uk and us, third Sunday in June | 3 before |
Fourth of July | fourth-of-july | us | 4 July | 3 before |
NAIDOC Week | naidoc-week | au | First Sunday in July | 7 after |
Matariki | matariki | nz | Table | 7 before |
Halloween | halloween | au, nz, uk, us | 31 October | 7 before |
Diwali | diwali | All | Table | 5 before, 1 after |
Bonfire Night | bonfire-night | uk | 5 November | 4 before |
Remembrance Day | remembrance-day | au, nz, uk | 11 November; in uk, the second Sunday in November | 3 before |
Thanksgiving | thanksgiving | us | Fourth Thursday in November | 7 before |
Hanukkah | hanukkah | All | Table (25 Kislev) | 1 before, 7 after |
Christmas | christmas | All | 25 December | 24 before, 1 after |
New Year's Eve | new-years-eve | All | 31 December | 4 before, 1 after |
- The country comes from
countryForTimeZone. With no known country, only the occasions for all countries show. Anzac Day,NAIDOC Week, andRemembrance Dayare commemorations (commemoration: true).
Tagging (occasionMatchOf), for each airing:
- An airing on a channel whose name matches
SHOPPING_CHANNEL(such asshop,TVSN,QVC,Gemporia, orjewellery) never matches. Asporttitle never matches. Akidstitle never matches a commemoration.titleKindOfgives the kind. - The occasion
negativesare removed from the texts first:Easter Island,Christmas in June,Christmas in July, andChristmas Island. - A word of the occasion in the title gives
title. A word in the episode title givesepisode. An episode title over80characters, or with a sentence break, counts as description text. - Else the description needs
2different words of the occasion (SYNOPSIS_TERMS) and givessynopsis. Thesupportingwords (festival of lightsfor Diwali and Hanukkah) count as the second word only, and never in a title or episode title. An airing with anewscategory never matches by description. - When the prototypes and the airing text have vectors, a
synopsismatch also needs a dot product of0.35or more with a prototype (OCCASION_PROTOTYPE_FLOOR).
Row (seasonalSectionOf):
activeOccasionsOflists the occasions whose window holds today, nearest occasion day first. An occasion turned off or muted is left out.- 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.
- The items skip the shows in
ready-to-watch,finish-started, andcoming-up. They ranktitlematches first, thenepisode, thensynopsis, then by score, picture, and start time. One episode (title and episode title, else description) shows once. A title has at most2airings (SEASONAL_PER_TITLE). The row has up to12items. - The first occasion with
4or more items (SEASONAL_MIN_ITEMS) from3or more titles (SEASONAL_MIN_TITLES) gives the row. Else there is no seasonal row. - The row goes after the last of
ready-to-watch,finish-started, andcoming-up. The sections after it drop the shows in the row. Category rows treat the row as an earlier section. - The section key is
seasonal-<occasion>and the title is the occasion title. Each item carriescategory(key,title,phrase,seasonal: true, andcommemoration: truefor a commemoration). Why this? gives the reasonAbout <occasion>, the field that matched, and the occasion date (the first and last day of the window when it runs2or 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_mutedwith the series keycategory-seasonal-<occasion>. Undo and Show again sendcategory_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 lasts365days. GET /api/for-you/categoriesadds one entry per occasion of the install country (seasonalSettingsOf) withseasonal: true. The client lists them in theSeasonalgroup.PUT /api/for-you/categories/seasonal-<occasion>with{ on }updatesfor_you_categories_off. An occasion of another country returns404.GET /api/for-you/hiddenlists a muted occasion (hiddenOccasionsOf) withseasonal: trueanduntil.
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.
readFeedWithreads the in-progress episode, new episodes, unwatched films, on-now entries, recordings, the watchlist, and the For you payload (waiting up to5 s).rankedSlidesOfranks candidates withheroCandidatesOfinsrc/web/home-hero.js. The For you payload carriestaste(tasteOfinsrc/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.getCurrentTasteinsrc/for-you-service.jsgives the lasttastekept in memory (or the saved result's), merged with the hidden show keys, hidden category groups, and switched-off categories read fromuser_eventsand the settings at that moment, so a hide applies at the next build even when the For you rebuild takes longer than5 s.GET /api/for-you/tasteanswers from the same function and never waits for a build.onNowPickOfpicks the Live news or Live sport candidate: a programme on now on a pinned channel that is on air, with ETSI genre group2(news) or4(sport), not on the channel that records now. Withtaste, it drops hidden shows and shows with any hidden category (a sport category also when thesportgroup is hidden), counts genre group4only when the title kind issportwith a sport code (whentastehas no titles, genre group4alone counts), and orders by2for a show affinity above0plus1when one of its categories has a share above0, then by channel order. The candidate carries the title's Hide category insource.category.proofHeroPicture(src/hero-picture-proof.js) tests up to6pictures per slide at1920px and keeps up to3. A picture passes at640px wide or more once its picture focus has settled.- The snapshot keeps at most
10candidates (HERO_CANDIDATE_LIMIT), one per show, and drops a slide with no proven picture. It is saved in the settinghome_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=.
Search
Two indexes share one matching module, src/web/search-index.js.
| Index | Built | Entries | Used by |
|---|---|---|---|
| Overlay index | In the browser (buildShowSearch in src/web/search-results.js) | Shows from GET /api/search/catalogue and series rules from GET /api/series | src/web/components/search-overlay.js (up to 8 show results) |
| Guide index | On the server (buildGuideSearch in src/guide-search.js) | One entry per show key in the guide | GET /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.
| Reason | Score | Rule |
|---|---|---|
title | 100 | The query starts a word of the title |
contains | 90 | The query without region words (au, australia, nz) occurs inside the title |
alias, yours | 85 | The query starts a word of a nickname; an exact nickname scores 101 |
known-as | 80 | The query starts a word of a learned name |
initials | 70 | A one-word query of 3 or more letters equals the title initials; only when direct matches are fewer than 3 |
fuzzy | 60 × containment | Trigram 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:
| Group | Rule |
|---|---|
scheduled | The program_id is in futureRecordings or activeRecordingIds of the live recording state (scheduledIdsOf in src/epg.js) |
series | series_link matches a series rule from the recording state (seriesLinkOfProgramme) |
for-you | The airing program_id is in the cached For you result (cachedForYouIds in src/for-you-service.js) |
guide | Any 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, runsfn(handle), and finishes the job asdone, orfailedwhenfnthrows.join({ kinds })reuses the current job when its kind is inkinds.- A job started inside another job's async context gets that job as
parentId. The context is anAsyncLocalStoragestore. - A handle has
step,update,total,advance,fact,item,log,outcome,fail, andfinish. A job keeps up to200items and100log lines. - A job that works on one recording (
importandads) has asubject:{ recordingId, title, season, episode, episodeTitle, channelName, airedAt, year, film, file }.src/activity-subject.jsbuilds it from the import item (importSubjectOf) or from therecordingsrow (loadRecordingSubject);titleis the show title the library groups the recording under, andfilmis true for a film import, a file inside the movies folder, or a show marked as a movie inprogramme_kind_overrides. Every list entry, detail, andjob_runsrow carries it; other jobs havesubject: null. planandplanEveryregister 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/stream | A 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/:id | One 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
percentfrom the copied size and an ETA from the copy rate. - The ad scan estimates its time as
duration × 0.5(SCAN_REALTIME_FACTORinsrc/commercials.js) and capspercentat99. GET /api/recordingsreturnsprogressper row, and library rows returnad_progress. The recordings list polls every2 swhile any row has progress, else every60 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).
| Id | Checks |
|---|---|
tvh.reach, tvh.auth, tvh.rights, tvh.open | TVHeadend answers (warn below API version 19); the login works; the rights probes answer without 403; no open admin entry |
tvh.tuners, tvh.channels | At least one tuner turned on; at least one channel |
tvh.rules | warn when the series rule title change failed for a rule (read from the setting autorec_anchor_failed, no TVHeadend call) |
guide.depth, guide.logos | fail when the guide ends within 12 h, warn within 48 h; share of channels with an icon |
guide.pictures | Reads 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.sources | Reads 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.hardlink | Readable 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.free | fail under 10 GB free; warn under 20 GB or 10% |
plex.reach, plex.oneoffs | The 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.health | The cron schedule runs; the last sync is not error or partial |
live.encoder, live.streams | ffmpeg on the PATH; the stream limit is not above the benchmark |
ads.comskip | comskip, ffmpeg, and ffprobe on the PATH when ad removal is on |
host.env | A known time zone and a LAN address |
host.names | warn 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.
| Path | Content |
|---|---|
src/web/index.html | Shell with the module preloads, fonts, and stylesheets |
src/web/app.js | Creates the Vue app, registers global components, and mounts it |
src/web/route-table.js, src/web/shared/router.js | Hash routes, aliases, nav entries, and the reactive route |
src/web/view-modules.js | VIEW_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.css | Plain stylesheets |
src/web/tailwind.css | Generated by npm run build:css (Tailwind CSS v4); test/tailwind-css.test.js checks it |
src/web/view-preloads.js | Generated 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.jshashes (SHA-256) the version and every.html,.js,.css, and.woff2file undersrc/web. The first12hex characters are the build id.src/web-assets.jsrewrites each asset URL to?v=<build>. A request with the current build getsCache-Control: public, max-age=31536000, immutable; any other request, andindex.html, getsno-cache.index.htmlgets amodulepreloadlink for each module in the static import graph of/app.js, and the meta tagsfreetvarr-build,freetvarr-health, andfreetvarr-time-zone./vendorservesvue.esm-browser.prod.js,hls.mjs, andhls.worker.jsout ofnode_modules.- Every
/apiresponse carriesX-Freetvarr-Build.src/web/shared/api.jscompares 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, andwelcome; any other hash resolves tohome. src/web/app.jsloads each view excepthomethroughdefineAsyncComponentand prefetches them at idle time.- The phone layout (
PHONE_LAYOUT_QUERY:(max-width: 767px), (max-height: 500px)) has a bottom tab bar and a16 pxgutter. Larger screens have a left rail and a32 pxgutter, or40 pxfrom1280px. - Lists show tables on wide screens and
article.list-rowcards inside.list-rowson narrow screens. src/web/manifest.webmanifestsetsdisplay: standalone.src/webhas 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:
| Directive | Value |
|---|---|
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' |
crossOriginEmbedderPolicyisfalse.hstsisfalse; the service uses plain HTTP.X-Powered-Byis disabled.trust proxyisloopbackplus the addresses inFREETVARR_TRUSTED_PROXIES(trustProxyOf), soreq.ipand the rate limits use the client address behind a trusted proxy.case sensitive routingis on, for the app and for the router insrc/web-assets.js, so/INDEX.HTMLand/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:
| Rule | Examples | Why a rebinding attacker cannot use it |
|---|---|---|
Empty Host | HTTP/1.0 clients | Browsers always send one |
IP literal (net.isIP) | 192.168.1.10, [fe80::1], ::ffff:192.168.1.10 | No DNS answer to rebind |
| One label | nas, freetvarr, diskstation | No public DNS name has one label |
| Private-use suffix | .localhost, .local, .lan, .home, .home.arpa, .internal, .localdomain, .corp | Not delegated in the public root zone |
| Machine name | os.hostname() and its first label | The host's own name under network_mode: host |
| Extra names | The setting allowed_hosts joined with FREETVARR_ALLOWED_HOSTS | The 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.
| Route | Body | Result |
|---|---|---|
GET /api/allowed-hosts | None | { 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/:name | None | Adds 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:
| Field | Value |
|---|---|
password | scrypt$32768$8$1$<salt>$<hash>: a 16-byte random salt and a 64-byte scrypt hash, base64url |
sessionKey | 32 random bytes, base64url; the HMAC-SHA256 key of the session cookie |
apiKey | The SHA-256 digest of the API key, base64url, or null |
trustedHeader | tailscale-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:
Authorization: Bearer <key>whose digest equalsapiKey(via: 'key').- The
trustedHeaderheader, not empty, whenreq.socket.remoteAddressis loopback or inFREETVARR_TRUSTED_PROXIES(via: 'header';req.signedInAsholds the value). The check uses the socket address, notreq.ip, soX-Forwarded-Forcannot change it. - The cookie
freetvarr.session,<issuedAt>.<HMAC of issuedAt>, younger than180days (via: 'cookie'). A cookie older than24 hgets a fresh one, so a device stays signed in for180days 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.
| Route | Body | Result |
|---|---|---|
GET /api/sign-in | None | { 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-in | None | Deletes the file and the cookie |
POST /api/sign-in/sign-out-others | None | Replaces sessionKey and signs this browser in again |
POST /api/sign-in/api-key | None | Makes a 32-byte key and returns it once as api_key |
DELETE /api/sign-in/api-key | None | Deletes 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-out | None | Deletes 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-csrfprotects the state-changing routes withdoubleCsrfProtection(double-submit cookie).GET /api/csrf-tokenreturns{ token }. The browser sends it in thex-csrf-tokenheader, and retries once with a fresh token after a403whose message matches/csrf/i.- The cookie is
freetvarr.x-csrfwithhttpOnly: true,sameSite: 'strict', andsecure: false.getSessionIdentifierreturns 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.
| Limiter | Limit | Routes |
|---|---|---|
syncLimiter | 5 | POST /api/sync, POST /api/reset |
rowActionLimiter | 30 | Recording library (import) and TVHeadend-delete routes, ad-scan and restore |
setupCheckLimiter | 20 | TVHeadend test, detect, shows list, and path check, Plex discovery and library create |
epgLimiter | 60 | Record 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 |
liveLimiter | 20 | POST /api/live, the stream limit routes, POST /api/live/benchmark |
playLimiter | 30 | Playback start and From the start |
playPingLimiter | 120 | Position, heartbeat, attention, watched marks, viewing history |
doctorLimiter | 10 | GET /api/doctor, POST /api/doctor/one-off-placeholder |
bootstrapLimiter, bootstrapStatusLimiter | 10, 30 | TVHeadend setup writes and reads |
guideFeedLimiter | 10 | GET /guide/xmltv.xml |
ratingsLimiter | 240 | Ratings, credits, artwork-choice reads |
showImageLimiter | 1200 | GET /api/epg/show-image |
| Sign-in tries | 5 | POST /login; a refused try gets the sign-in page with 429 |
Errors and paths
- The terminal error handler responds with
err.statusCode,err.status, or500and{ "error": <message> }. It never sends a stack trace. - A
process.on('unhandledRejection')handler logs the reason and does not exit. POST /api/showsandPATCH /api/shows/:idrejectdest_folderandseason_templatevalues that start with/or\or contain.., and an empty, blank, or.show_patternordest_folder(showFieldErrorOfinsrc/show-fields.js). Import paths go throughguardWithinRoot.- 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
realpathandlstat(Library delete). POST /api/settingschecks each root it changes (rootSettingsProbleminsrc/path-check.js).media_root,oneoff_root,movies_root, andrecordings_rootmust 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_pathmust be absolute and not/. A failure gives400with{ 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 answers404. TVHeadend images and channel logos may be SVG (up to1 MB);createThumbnailStorerenders an SVG withsharpto WebP at the requested width, with the density capped between1and2400dpi, so only raster pixels leave Freetvarr. An SVG with a filter (a<filter>element, or afilterattribute or style) is refused unrendered. SVG renders run one at a time (createRenderQueue), with up to20waiting; a request past that answers404and is not marked as failed. Any other body that holds an<svg>tag never reachessharp. A thumbnail that cannot be resized gives no image, and the store skips that thumbnail for10min.
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:
| Secret | Sent to | Address change with no secret in the request |
|---|---|---|
tvh_password | A URL with the origin of tvh_url | POST /api/settings and a passing POST /api/tvh-test delete it and return cleared: ['tvh_password'] |
plex_token | No plex_token_scope: a URL with the origin of plex_url. Scope this-machine (a detected token): a URL on this machine | POST /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_key | The saved URL; the config.xml key only to a URL on this machine at the config.xml port | PUT /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
| Control | Setting |
|---|---|
.npmrc | ignore-scripts=true, engine-strict=true, audit-level=high, save-exact=true, package-lock=true, min-release-age=3 |
| Install | npm ci from the committed package-lock.json |
| Native builds | npm run rebuild:natives rebuilds only better-sqlite3 with --ignore-scripts=false |
| Signatures | npm run setup ends with npm audit signatures |
| Actions | Every 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.
| Variable | Default | Meaning |
|---|---|---|
PORT | 3733 | HTTP 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>/artwork | Folder for saved artwork |
TZ | Unset | Time zone fallback (Time zone) |
CSRF_SECRET | Unset | Replaces the generated secret file (CSRF) |
TVH_URL | Unset | detectServers returns this address and probes nothing |
MEDIA_ROOT | /media/tv | Default for the setting media_root (TV library) |
ONEOFF_ROOT | /media/one-offs | Default for the setting oneoff_root |
MOVIES_ROOT | Empty | Default 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 | /recordings | Default for the setting recordings_root (TVHeadend files as Freetvarr sees them) |
TVH_RECORDINGS_PATH | /recordings | Default for the setting tvh_recordings_path (the prefix TVHeadend reports) |
PLEX_PREFS_PATH | /plex/Library/Application Support/Plex Media Server/Preferences.xml | Plex Preferences.xml for token detection |
SONARR_CONFIG_PATH, RADARR_CONFIG_PATH | /sonarr-config.xml, /radarr-config.xml | The app config.xml for the API key, port, and URL base |
LIVE_TV_BUFFER_MINUTES | 30 | Minutes of live TV kept for pause and rewind; clamped to 0–120 |
LIVE_TV_TRANSCODE | auto | auto, hardware, software, or copy |
LIVE_TV_VAAPI_DEVICE | /dev/dri/renderD128 | VAAPI render device |
LIVE_TV_MAX_SESSIONS | Unset | Cap on live streams and recording playbacks (Stream limit) |
IMAGE_CACHE_MAX_MB | 100 | Megabytes of resized images in image-cache/ |
FREETVARR_ALLOWED_HOSTS | Unset | Extra names Freetvarr answers to, joined with the setting allowed_hosts (Host check) |
FREETVARR_LOGIN | Unset | off, 0, false, or no turns sign-in off and keeps the password (Sign-in) |
FREETVARR_TRUSTED_PROXIES | Unset | Addresses, separated by commas or spaces, whose sign-in proxy header Freetvarr reads, with loopback (Sign-in) |
PATH | System | The 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.
| Variable | Default | Meaning |
|---|---|---|
PUID, PGID | 1000 | Owner of the files; user: of Freetvarr and the PUID and PGID of TVHeadend and Plex |
CONFIG_PATH | ./config | Host root of the config folders |
DATA_PATH | ./data | Host root of recordings/ and media/ |
FREETVARR_PORT | 3733 | Becomes PORT in the container |
PLEX_PREFS_PATH | Unset | Host path of Preferences.xml; mounted at /plex-preferences.xml, or /dev/null |
SONARR_CONFIG_PATH, RADARR_CONFIG_PATH | Unset | Host paths of config.xml; mounted read-only, or /dev/null |
COMPOSE_PROFILES | Unset | plex adds the plex service |
PLEX_CLAIM | Unset | Claim token for the plex service |
RENDER_GID | None | Group 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:
- Install
tini,tzdata,wget,comskip, andffmpeg, plusmesa-va-driversand, onamd64only,intel-media-va-driver-non-free(VAAPI drivers). - Run
npm install -g npm@11.15.0,npm ci --omit=dev --ignore-scripts, andnpm run rebuild:natives. - Remove the
onnxruntime-nodebinaries of other platforms,onnxruntime-web, and the unused@huggingface/transformersbuilds. - Copy the repository, set
NODE_ENV=productionandDB_PATH=/config/state.db, andEXPOSE 3733. - Create
/config, owned bynode, and switch toUSER node(uid1000). The composeuser:line overrides the user.
| Item | Value |
|---|---|
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.sh | Config 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.dbexists andDB_PATHpoints elsewhere: the message says to move the database to the folder ofDB_PATH.- The config folder, or an existing
state.db,state.db-wal,state.db-shm, orcsrf-secretin it, is not writable: the message gives the user id, the owner of the folder, theuser:line to set when that owner is not root, andsudo 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.
| Service | Image | Network | Starts after |
|---|---|---|---|
init | busybox:stable | none | None |
tvheadend | lscr.io/linuxserver/tvheadend:latest | host | init |
freetvarr | ghcr.io/furey/freetvarr:latest | host | init and tvheadend |
plex (profile plex) | lscr.io/linuxserver/plex:latest | host | init |
- The services publish no
ports:. Freetvarr binds${FREETVARR_PORT}on the host; TVHeadend uses9981(HTTP) and9982(HTSP); Plex uses32400. Host networking lets TVHeadend find a network tuner by UDP broadcast. initcreates/config/tvheadend,/config/freetvarr,/config/plex,/data/recordings,/data/media/tv, and/data/media/one-offs, owned byPUID:PGID.freetvarrruns asPUID:PGID(user:), drops every Linux capability (cap_drop: [ALL]), and setsno-new-privileges.initrunschownas root, and the linuxserver images start as root, so they keep the Docker defaults.docker-compose.dev.ymlbuildsfreetvarr:devfrom the checkout.docker-compose.hwaccel.example.yml, saved asdocker-compose.override.yml, maps/dev/driand adds the group${RENDER_GID}.
| Service | Container path | Host path | Content |
|---|---|---|---|
tvheadend | /config, /recordings | ${CONFIG_PATH}/tvheadend, ${DATA_PATH}/recordings | TVHeadend settings and DVR entries; .ts recordings |
freetvarr | /config | ${CONFIG_PATH}/freetvarr | The 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 variables | Plex token and app API keys |
plex | /config, /data/media | ${CONFIG_PATH}/plex, ${DATA_PATH}/media | Plex 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
git clone https://github.com/furey/freetvarr
cd freetvarr
cp .env.example .env
npm run setup
npm startcp .env.example .envis optional.npm startandnpm run devload./.envwith Node--env-file-if-exists.npm run setupinstalls from the lockfile, rebuildsbetter-sqlite3, and verifies signatures.npm startrunsnpm run migrate(creates./configand applies the migrations), then listens onhttp://localhost:3733.package.jsonsetsenginesto Node>=24.0.0and npm>=11.10.0. Thevoltablock (Volta) pins Node24.21.0and npm11.15.0.better-sqlite3is pinned to12.11.1, which has prebuilt binaries for Node 24.- The TVHeadend address is a runtime setting (
tvh_url), set in the wizard.
Scripts
| Command | Runs |
|---|---|
npm run setup | npm ci --ignore-scripts && npm run rebuild:natives && npm audit signatures |
npm run migrate | mkdir -p config && knex migrate:latest |
npm run migrate:refresh | Deletes ./config/state.db, then migrates |
npm start | npm run migrate && node --env-file-if-exists=.env src/server.js |
npm run dev | The same with --watch |
npm run build:css | tailwindcss -i src/tailwind.css -o src/web/tailwind.css --minify |
npm test | node --test --import ./test/setup/no-outbound-network.js 'test/*.test.js' |
npm run test:integration | node --test --import ./test/setup/no-outbound-network.js --test-concurrency=1 'test/integration/*.test.js' |
npm run doctor | The health checks against the configured database (Health checks) |
Tests
The runner is the Node test runner; there are no test dependencies.
test/*.test.jsholds the unit tests, named after the module they cover (for exampletest/sync.test.js,test/live-*.test.js).test/setup/no-outbound-network.jsloads before every test file. It throwsENETBLOCKEDfor 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 reallscr.io/linuxserver/tvheadend:latestcontainer thattvheadend-container.jsstarts withdocker 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:
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
390and1280px. - On a loopback address, it answers the credits and ratings lookups with a fixture after
250 ms.movie-page-cold-lookupsanswerspendingfirst, 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 than0.5 pxfails the screen and shows in theguidecolumn, 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 than700 ms(one already showing when the watch starts is not timed), content that arrives more than1500 msafter the first frame, or a page error. Pictures that finish loading are reported in theartcolumn 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 theslowcolumn and fail only after2500 ms; every other item keeps the1500 mslimit. - On
more-info, moves in the first500 msafter 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
playerscreen 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.0fromscripts/.cache/playwright-1.49.0(the capture scripts install it there).PLAYWRIGHT_DIRpoints it somewhere else. LAYOUT_SCREENSlimits the run to named screens,LAYOUT_VIEWPORTSsets the widths,LAYOUT_FRAMES_DIRsaves a screencast of each screen, andLAYOUT_REPORTwrites 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-mediaGitHub release, not files in git.scripts/docs-media.txtlists them;scripts/fetch-docs-media.shdownloads them;scripts/upload-docs-media.shuploads them and starts the docs workflow. - The
scripts/capture-*.shscripts record the screenshots and videos with Playwright against a throwaway server (scripts/capture-local-server.sh, port3801). The server reads only the demo pack inscripts/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, unlessDOCS_MEDIA_UPLOAD=0is set.