diff --git a/.gitignore b/.gitignore
index abd32e8..7c8c923 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,5 @@
-*__pycache__*
\ No newline at end of file
+*__pycache__*
+/Videos/
+/Images/
+/ffplay.log
+/.thumbnails/
\ No newline at end of file
diff --git a/README.md b/README.md
index 962e769..0e5ee3a 100644
--- a/README.md
+++ b/README.md
@@ -10,4 +10,286 @@ Simple Goal List
- FFPlay based playback of video and audio
- Ahead of time downloading of Youtube video content
- Ahead of time uploading of pictures and videos from external devices
-- USB media awareness/playback
\ No newline at end of file
+- USB media awareness/playback
+
+## Fullscreen player
+
+Install FFplay (usually provided by FFmpeg), then run the player in the graphical
+session connected to the display:
+
+```sh
+python3 player.py
+```
+
+The player reads `config.json` beside the script and checks the database every
+two seconds. Use `--config /path/to/config.json` for another configuration.
+Relative database paths and local media paths are resolved against the config
+file's directory; stream URLs are passed through unchanged.
+
+Selection priority is:
+
+1. The lowest-ID row with `media_active = 1`.
+2. If none is active, the lowest-ID row with `media_default = 1`.
+3. If neither exists, a fullscreen black screen generated by FFplay.
+
+A selected row with a missing or blank URI also displays black. Changes to the
+effective selected row or its URI stop the old FFplay process before starting
+its replacement. Changes to other rows do not interrupt playback. Unexpected
+FFplay exits are retried on the next poll. A finite video holds its last frame
+at the end rather than clearing its active flag or automatically selecting
+another item. Static images remain displayed until selection changes.
+
+FFplay always starts fullscreen with its banner and progress output disabled.
+Only FFplay errors are appended to `ffplay.log` beside `config.json`; stdout is
+discarded. Use `--log-file /path/to/errors.log` to choose another log. The player
+itself reports selection changes and database/process errors to the console.
+Ctrl+C or SIGTERM stops the child process; a child that ignores termination is
+killed after two seconds. The player does not modify the database and currently
+does not apply `media_playback_option` records.
+
+Use **Play Media** from the home page to select an item in the unified library.
+Alternatively, set selection flags directly in SQLite. For example, select media
+ID 3 without temporarily leaving several active rows:
+
+```sql
+BEGIN;
+UPDATE media SET media_active = 0;
+UPDATE media SET media_active = 1 WHERE media_id = 3;
+COMMIT;
+```
+
+Clear active flags to return to the default. Clear default flags too for black.
+Flask and the player run separately; starting the web app alone does not start
+playback. The player requires a working graphical display/audio session, not
+just an SSH shell without display access.
+
+## Media library and playback selection
+
+Open **Play Media** from the homepage, or visit `/media`. All media types share
+one page, with a **Play** button per item and image/video/stream icons. Clicking
+Play clears the previous active selection and activates the new item in a single
+database transaction; default flags are preserved. The separate player picks up
+the change on its next two-second check.
+
+A green border and **Selected** badge show the item selected for playback,
+including the default when no active item exists. The selection banner and badges
+refresh every two seconds. These indicators reflect the database's requested
+selection, not proof that FFplay is running or that a stream is healthy. Refresh
+the page to load newly added media or edited names/sources. Empty sources cannot
+be selected using the Play button.
+
+Local images and videos receive lazy-loaded, cached PNG thumbnails generated by
+FFmpeg (the first video frame, scaled to at most 240×135). Cache files live in
+`.thumbnails/` beside `config.json` and are excluded from Git. Source path, size,
+and modification time determine the cache key; deleting this folder is safe and
+causes previews to regenerate. Streams use an icon without opening a network
+connection. Missing FFmpeg, unsupported files, or generation failures also fall
+back to the type icon. Thumbnail generation has a ten-second timeout.
+
+Previews are restricted to files inside configured image, video, and legacy
+upload storage folders, including custom storage locations. Symlinks outside
+those folders are rejected, and FFmpeg's preview input is restricted to local
+file/pipe protocols. A local file outside those folders can still be selected
+for playback but has no preview. Media types are inferred from local filename
+extensions or URL schemes; no schema changes are required.
+
+As with uploads, keep this interface on a trusted network until authentication
+and broader access controls are implemented.
+
+### Deleting media
+
+Choose **Delete** beneath an item in `/media`. A separate confirmation page names
+the item and explains whether its stored file will be deleted or retained.
+Nothing is deleted by opening that page; use **Cancel** to go back or **Yes,
+delete media** to confirm. If the record or file changed since the prompt, it
+must be reviewed and confirmed again. This works without JavaScript.
+
+Confirmed deletion removes the `media` row and its playback options. Local files
+inside the configured image, video, and legacy upload folders are removed to
+free storage, including files downloaded from YouTube. A file used by another
+media row is retained until its last reference is deleted. Streams, missing
+files, paths outside managed storage, directories, and symbolic links only lose
+their database record; no remote source, outside file, or directory tree is
+deleted. YouTube job history remains unchanged.
+
+Deleting active/default media lets the player choose the next active/default
+item or black on its next check. An open player process can retain the deleted
+file's disk space until it releases that file. Cached thumbnails for the item
+are also removed (including the current legacy-format thumbnail, if present).
+
+A local file is temporarily renamed in place before the database transaction
+commits. Database errors restore it rather than destroying it. If final file
+cleanup fails after commit, the page explicitly reports that storage was not
+freed; the server log identifies the retained `.deleting-*` file for an
+administrator to remove. A forced shutdown during deletion can also leave a
+`.deleting-*` file: check the database before restoring its original filename
+(if the record remains) or removing it (if the deletion committed).
+
+## Submission validation
+
+All new image, video, stream, and YouTube submissions require a nonblank media
+name of at most 120 characters, without control characters. Surrounding spaces
+are removed. Names must be unique across the media catalog and pending or
+currently downloading YouTube jobs, compared case-insensitively after Unicode
+normalization and trimming. Failed jobs do not reserve names; completed jobs
+normally have a catalog entry that does. Existing records are not renamed or
+removed. This rule is enforced by the app and worker when writing under SQLite
+transactions, not by a database constraint; direct SQL can bypass it.
+
+Stream registration accepts HTTP, HTTPS, RTSP, RTMP, RTMPS, UDP, and TCP network
+URLs, including local-network hosts. YouTube requests require a supported
+individual video URL. Validation checks syntax, not network reachability.
+
+Image and video uploads require **FFprobe and FFmpeg on PATH** for local-only,
+time-limited content validation. Extensions and client MIME types alone are not
+trusted; a video stream and a decodable first frame are required. Full files are
+not decoded or scanned for malware. Missing validation tools, storage issues,
+database failures, and invalid fields produce user-facing errors without saving
+an incomplete media entry. Retrying a failed upload starts it from the beginning.
+
+## Uploading local videos
+
+Use **Upload a Video** on the home page, or visit `/upload/video`. Enter a display
+name and select one video. The limit is 5GB (5 × 1024³ bytes), checked both in the
+browser and on the server. Common formats including MP4, MKV, MOV, WebM, AVI,
+MPEG, and WMV are accepted by extension. Before saving, FFprobe checks for a
+video stream and FFmpeg decodes its first frame; the upload does not transcode the
+file or guarantee the rest of the video is valid.
+
+The page displays transfer progress and warns against navigating away. At 100%,
+wait for the server to finish saving; only then will the page automatically
+return home. Errors remain on the page so the user can retry. JavaScript is
+required for this workflow.
+
+Videos use the same `youtube_download_location` configuration as YouTube downloads
+(default `Videos`, relative to `config.json`). Files receive unique generated
+names, while the entered display name and absolute file path are saved to
+`media`. Failed uploads are cleaned up. The separate player can display the
+video when its media record is marked active or default.
+
+This route requires Flask 3.1+ for its per-request size limit. Its request limit
+includes a small allowance for multipart form overhead without raising other
+routes' existing limits. If deploying behind a proxy, configure its request-size
+limit and timeouts to permit 5GB uploads plus form overhead. Allow sufficient
+space for both Flask's temporary upload and the final video file.
+
+## Uploading static images
+
+Use **Upload a Static Image** on the home page, or visit `/upload/photo`. Enter
+an image name and choose one JPG/JPEG, PNG, WebP, BMP, TIFF, or GIF file. Files
+are checked against their extensions and decoded for validation. Images may be
+animated, but only the first frame is checked; dimensions are limited to 50
+megapixels. SVG and other active-content formats are not accepted.
+
+Image uploads now use `"image_upload_location": "Images"` in `config.json`,
+relative to that file. The folder is created automatically when saving an upload
+and excluded from Git. Existing images in the older `uploads` location and their
+media records are left unchanged.
+
+The image page has a 100MB (100 × 1024² bytes) file limit in both the browser
+and server. Like video uploads, it provides progress feedback, a warning not to
+navigate away, and an automatic return home only after saving succeeds. Both pages share the same
+upload JavaScript. Errors stay on the page for retry. Files have unique storage
+names; the requested display name and absolute path are stored in `media`.
+Failed uploads are cleaned up. JavaScript and Flask 3.1+ are required, and proxy
+limits, timeouts, and temporary disk space must accommodate large uploads.
+
+## YouTube download worker
+
+Install `yt-dlp` and make sure its command is on `PATH`. Install FFmpeg as well
+for downloads that need video/audio merging or other postprocessing. The worker
+uses Python's standard library; it does not need Flask.
+
+From the project directory, initialize or upgrade the database, then start the worker:
+
+```sh
+python3 sc_database_generator.py
+python3 youtube_downloader.py
+```
+
+The initializer requires Python 3.12 or newer (the SQLite wrapper uses
+`Connection.autocommit`). It preserves existing jobs when adding the media-name
+and retry-count columns and upgrading the allowed statuses. Existing jobs start
+with a retry count of zero. Stop running workers before upgrading the database.
+The worker polls every five seconds when idle or after a failed attempt;
+use `--poll-interval 10` to change that delay, or `--config /path/to/config.json`
+to select another configuration file.
+
+`config.json` includes `"youtube_download_location": "Videos"`. The folder is
+created automatically. The worker resolves relative storage and database paths
+against the configuration file's directory. Downloaded files are named
+`job-.` to avoid collisions and keep display names out of file paths.
+The default `Videos/` folder is excluded from Git.
+
+### Web interface
+
+Start the Flask app with `python3 sc_webserver.py` and use the home page's
+**Get Video from YouTube** link, or visit `/youtube/download`. Enter a media name
+and a YouTube video URL to queue a job. Invalid submissions show an error without
+creating a job; successful submissions redirect to `/youtube/jobs`.
+
+The jobs page shows pending, downloading, and failed jobs by default, including
+each job's name, URL, status, and failed-attempt count. Check **Include completed
+jobs** and click **Update List** to also show downloaded jobs. Refresh the page
+to see worker updates. Both pages are linked from the home screen.
+
+The download worker must run separately from Flask to process requests; submitting
+a form only adds a pending job. As with the existing upload endpoints, keep this
+interface on a trusted network until access controls are implemented.
+
+Alternatively, queue a job using SQL against `scdb.db`:
+
+```sql
+INSERT INTO youtube_download_job (
+ youtube_download_job_url,
+ youtube_download_job_media_name
+) VALUES (
+ 'https://www.youtube.com/watch?v=VIDEO_ID',
+ 'Desired button name'
+);
+```
+
+Jobs default to `pending`. The worker claims the oldest pending job by ID and
+marks it `downloading` before invoking `yt-dlp` without a shell interpreter.
+After a successful download and postprocessing, it checks that the reported file
+exists inside storage, then atomically inserts a `media` record and marks the job
+`downloaded`. The media record contains the requested display name and the final
+absolute file path. For older jobs or blank names, the video's title is used.
+No playback-option records are created automatically.
+
+`config.json` sets `"youtube_download_max_retries": 3`. This must be a
+non-negative integer; zero allows only the initial attempt. Each failed worker
+attempt increments the job's persistent `youtube_download_job_retry_count`.
+While the count is at or below the limit, the job returns to `pending` for retry
+after the polling delay. When the count exceeds the limit, its status becomes
+`failed` and the worker ignores it, allowing later jobs to run. With the default
+limit, this allows one initial attempt plus three retries (four failed attempts
+total). These are worker attempts; yt-dlp may also retry network requests
+internally. Successful downloads and Ctrl+C interruptions do not increment the
+counter.
+
+To manually retry a failed job with a fresh budget:
+
+```sql
+UPDATE youtube_download_job
+SET youtube_download_job_status = 'pending', youtube_download_job_retry_count = 0
+WHERE youtube_download_job_id = 123
+ AND youtube_download_job_status = 'failed';
+```
+
+Ctrl+C releases an in-flight job, but a forced termination or power loss can leave
+it `downloading`. Once you have confirmed no worker is still handling that job,
+reset it manually (this preserves its retry count):
+
+```sql
+UPDATE youtube_download_job
+SET youtube_download_job_status = 'pending'
+WHERE youtube_download_job_id = 123
+ AND youtube_download_job_status = 'downloading';
+```
+
+Run the database and worker tests without downloading any videos:
+
+```sh
+python3 -m unittest test.youtube_download_job_test test.youtube_download_web_test test.upload_video_test test.upload_photo_test test.player_test test.media_library_test test.submission_validation_test test.media_deletion_test -v
+```
\ No newline at end of file
diff --git a/TODO.md b/TODO.md
new file mode 100644
index 0000000..36cab45
--- /dev/null
+++ b/TODO.md
@@ -0,0 +1,95 @@
+# Sanctuary Commander TODO
+
+Sanctuary Commander is the planned successor to Video Commander: a simple,
+web-based interface for managing sanctuary TVs and displaying dynamically added
+media. The current implementation provides the web interface, media storage, and
+an FFplay-based player with unified playback selection; device control is still future work.
+
+## Completed foundations
+
+- [x] Set up a Flask web server with configuration loaded from `config.json`.
+- [x] Organize implemented pages into Flask blueprints.
+- [x] Build a Bootstrap-based home page with controls grouped into common tools,
+ playback, and media submission.
+- [x] Create the configured upload directory automatically when the server starts.
+- [x] Upload named static images (up to 100MB) to the configurable `Images` folder,
+ show progress and navigation warnings, and return home after saving the file
+ and media record.
+- [x] Add browser-side upload progress reporting and basic upload error feedback.
+- [x] Implement stream registration with a display name and URL.
+- [x] Provide a SQLite database wrapper and a database initialization script.
+- [x] Define the media catalog and weighted playback-option tables.
+- [x] Add a YouTube download jobs table storing each URL and its status:
+ `pending`, `downloading`, `downloaded`, or `failed`.
+- [x] Store an optional fullscreen playback flag for registered streams.
+- [x] Remove the old preparation and component tables and slideshow scaffolding;
+ retain the media and playback-option tables and their existing records.
+
+## Finish the current workflows
+
+- [x] Link the home page to a unified media library with Play buttons, live selection
+ indicators, media-type icons, and cached local image/video thumbnails.
+- [x] Delete media with a confirmation step, removing records/playback options and
+ unshared files in managed storage while preserving outside/shared sources.
+- [ ] Connect the existing placeholder controls to backend actions.
+- [x] Add input validation for media names, duplicate names, stream URLs, and
+ uploaded files.
+- [ ] Ensure upload destinations remain inside the configured upload directory.
+- [x] Handle missing form fields, missing files, and storage/database failures
+ with useful error messages.
+- [x] Close request-scoped database connections when requests finish.
+
+## Playback and media preparation
+
+- [x] Implement fullscreen FFPlay-based playback with error-only FFplay logging.
+- [x] Display uploaded static images when selected as active or default media.
+- [x] Play registered stream URIs using the player.
+- [ ] Apply compatible stored playback options without overriding fullscreen or logging rules.
+- [x] Upload named local video files (up to 5GB) to the shared video storage folder,
+ show upload progress and navigation warnings, and return home after saving.
+- [x] Play uploaded local video files when selected as active or default media.
+- [x] Download YouTube videos ahead of time for later playback using queued jobs.
+- [x] Implement a download worker that updates job status from `pending` to
+ `downloading` to `downloaded` after the file is saved successfully.
+- [x] Store requested media names on jobs and register successful downloads in the
+ media catalog using the final local file path.
+- [x] Configure download storage (default: `Videos`) and return failed attempts to
+ pending for retry with logged errors.
+- [x] Add a web workflow for submitting YouTube URLs and desired media names.
+- [x] List pending, downloading, and failed jobs, with an opt-in checkbox to include
+ completed jobs.
+- [x] Persist per-job retry counts and mark jobs failed once they exceed the
+ configured retry limit (default: three retries after the initial attempt).
+- [ ] Add increasing retry backoff and recovery of jobs left downloading after a
+ forced termination.
+- [ ] Design a new approach to media preparation tracking, including the role of
+ the existing `media_preparing` flag; do not restore the old preparation table.
+- [ ] Implement background media preparation using the new tracking approach.
+- [ ] Surface preparation status in the web interface.
+- [x] Poll active/default media every two seconds, prioritizing active media and
+ falling back to default media or a fullscreen black screen.
+- [x] Add web controls for changing active media atomically, with status matching
+ the player's active/default priority.
+- [ ] Add web controls for changing default media.
+- [ ] Implement the Disable Video and Blackout Screen controls.
+- [ ] Detect USB media and make it available for playback.
+
+## TV and device control
+
+- [ ] Integrate with Home Assistant.
+- [ ] Implement TV power controls.
+- [ ] Implement TV volume controls.
+- [ ] Implement TV input selection.
+- [ ] Connect the home-page TV controls to the integration.
+
+## End goals and readiness
+
+- [ ] Provide one browser-based location for TV control and media playback.
+- [ ] Let users prepare and submit content dynamically rather than maintaining a
+ static media configuration file.
+- [ ] Keep everyday operation simple for less technically experienced users.
+- [ ] Document installation, dependencies, configuration, and normal operation.
+- [ ] Add automated coverage for upload, stream-registration, preparation,
+ playback, and device-control workflows as they are implemented.
+- [ ] Define appropriate access controls and a production deployment setup before
+ exposing upload or device-control endpoints beyond a trusted environment.
diff --git a/blueprints/configure_stream/configure_stream.html b/blueprints/configure_stream/configure_stream.html
index 6dee3b6..45f4841 100644
--- a/blueprints/configure_stream/configure_stream.html
+++ b/blueprints/configure_stream/configure_stream.html
@@ -14,17 +14,18 @@
Configure a stream, content that is played from a location on the local network or the Internet.
-
+
+ Delete Media
+ {% if error %}
+ {{ error }}
+ {% endif %}
+ {% if media is defined %}
+ Are you sure you want to delete {{ media[1] }}?
+
+
{{ plan.message }}
+
The media record and its playback options will be permanently removed. This cannot be undone.
+
+ {% if media[3] == 1 or media[4] == 1 %}
+ This item is active or marked as default. The player will select another active/default item, or a blank screen, on its next check.
+ {% endif %}
+
+ {% else %}
+ Return to media library
+ {% endif %}
+
+
diff --git a/blueprints/media_library/media_delete.html b/blueprints/media_library/media_delete.html
new file mode 100644
index 0000000..780f499
--- /dev/null
+++ b/blueprints/media_library/media_delete.html
@@ -0,0 +1,34 @@
+
+
+