diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6fb38b4e..b1c5798e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -39,17 +39,21 @@ jobs: DATABASE_HOST: localhost DATABASE_PORT: 5432 DJANGO_ENV: DEBUG + # RealFfmpegTests (test_video_utils.py) skips when ffmpeg is missing, so a + # laptop without it stays green; here a missing ffmpeg is a failure. + REQUIRE_FFMPEG: "1" steps: - uses: actions/checkout@v4 # Mirror the Dockerfile's system deps: ImageMagick + Ghostscript power the # PDF→thumbnail path that Artifact.save() runs (exercised by the Talk - # fixtures); libpq-dev is needed to build psycopg2 from source. + # fixtures); libpq-dev is needed to build psycopg2 from source; ffmpeg + # (with ffprobe) runs RealFfmpegTests, the banner video commands (#1468). - name: Install system dependencies run: | sudo apt-get update - sudo apt-get install -y --no-install-recommends imagemagick ghostscript libpq-dev + sudo apt-get install -y --no-install-recommends imagemagick ghostscript libpq-dev ffmpeg sudo cp imagemagick-policy.xml /etc/ImageMagick-6/policy.xml - name: Set up Python @@ -170,7 +174,7 @@ jobs: run: python -m playwright install --with-deps chromium - name: Run end-to-end tests - run: python manage.py test website.tests.test_member_e2e --settings=makeabilitylab.settings_test --verbosity=2 + run: python manage.py test website.tests.test_member_e2e website.tests.test_hero_carousel_e2e --settings=makeabilitylab.settings_test --verbosity=2 # Accessibility sweep (Pa11y + Axe, WCAG 2.0 AA). CONTRIBUTING requires Pa11y # on UI changes but nothing enforced it (#1278 item 6). This wires it in. diff --git a/CLAUDE.md b/CLAUDE.md index 4e8be2e5..2594a6a3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,6 +43,7 @@ A superuser is required to use `/admin` and add content; create one with `python - When fixing a bug reachable through a real queryset, URL, or view, add a regression test in the matching style before applying the fix (matches the tests-first workflow). - **Always use the `--settings=makeabilitylab.settings_test` shim.** It sets `MIGRATION_MODULES = {'website': None}` so the test DB is built directly from the current models, sidestepping the gitignored, per-environment `website/migrations/` history. This is the durable fix for #1267 — without it, a fresh test DB can fail at creation with `column "..." already exists` (old workaround: `docker exec makeabilitylabwebsite-db-1 psql -U admin -d postgres -c "DROP DATABASE IF EXISTS test_makeability;"`). - **CI:** `.github/workflows/test.yml` runs this same command on every push to `master` and every PR (free/unlimited for this public repo). It reports a green ✓ / red ✗ — it does not block pushes or the deploy. See the testing roadmap in #1278. + - **Banner video tests (#1468):** `transaction.on_commit` callbacks never fire by themselves in a `TestCase`, so every test of a save that may queue a conversion wraps it in `self.captureOnCommitCallbacks(execute=True)` and asserts how many callbacks were registered; `settings_test.py` sets `BANNER_VIDEO_CONVERT_INLINE = True` so the captured callback runs the job in the test thread. ffprobe/ffmpeg are patched everywhere except `RealFfmpegTests` (`test_video_utils.py`), which runs the real commands and skips when ffmpeg is absent; `REQUIRE_FFMPEG=1` (set in CI's `test` job) turns that skip into a failure. The hero's video loading is covered by Playwright in `test_hero_carousel_e2e.py` (CI `e2e` job). - **Coverage (#1278 item 4):** the CI `test` job wraps the suite in `coverage run` and publishes a table to the run's Summary; config is in `.coveragerc` (measures the `website` app, branch coverage on). It's **report-only** — no `--fail-under` gate; the number targets backfill. Run locally inside the container: `pip install -r requirements-dev.txt`, then `coverage run manage.py test website --settings=makeabilitylab.settings_test && coverage report` (or `coverage html` for a browsable `htmlcov/`). - Accessibility (Pa11y CI + Axe, WCAG 2.0 AA): start the site, then `docker-compose -f docker-compose-local-dev.yml --profile testing run --rm a11y`. URLs to scan are configured in `.pa11yci.json`. Run this before submitting UI changes. @@ -148,6 +149,17 @@ Every container start runs, in order: `collectstatic` → `makemigrations` → ` **`image_cropping` is an in-repo fork**, not the PyPI `django-image-cropping` (which was EOL Jcrop+jQuery, Django ≤4.0). Like `sortedm2m_filter_horizontal_widget`, the top-level `image_cropping/` package is project source code and shadows/replaces the dropped dependency. Its admin widget is **Cropper.js** (vendored static, no build step): editors preview and crop client-side *before* the first save (#1299/#1269). The data layer is intentionally unchanged — `ImageRatioField` is still a `CharField` whose `deconstruct()` returns `image_cropping.fields.ImageRatioField`, so the gitignored per-environment migrations that `import image_cropping.fields` keep working and the DB column is untouched (a regression test pins this path). See `image_cropping/README.md`. To bump Cropper.js, replace the vendored `static/image_cropping/cropper.min.{js,css}` (stay on the v1.x API; v2 is a different API). +### Banner videos (#1468) + +An editor's banner video upload is **not** stored as `Banner.video`. `BannerAdminForm` (used by `BannerAdmin` and the project page's `BannerInline`) checks it in `clean_video` (extension and signature, at most 250 MB, then `ffprobe`: a real video stream, at most 60 s, frame at most 4096 px, landscape, not PQ HDR) and changes nothing; `save()` stores it as `Banner.video_original` under a server-generated name in `banner/videos/originals/`, sets `video_conversion_started`, and registers a job with `transaction.on_commit`. After the commit a daemon thread in that Gunicorn worker (`website/utils/banner_video_jobs.py`) converts it, one job at a time across workers (an `fcntl.flock` in the temp dir), and sets `Banner.video` to an MP4 of at most 10 MB with one `UPDATE` filtered on the banner id, the original's name and the start time, so a superseded job (new upload, "Convert again", video cleared, banner deleted) changes nothing and deletes its output. No task queue, no startup command. + +- **Encoding** (`website/utils/video_utils.py`, where all the limits live): a file already H.264 `yuv420p`, at most 1920×1080 and 10 MB, is stream-copied (still strips audio and metadata such as location); anything else gets one `libx264` pass fitting inside 1600×900 (never cropped or enlarged), at most 30 fps, CRF 27 with `-maxrate min(2500, 72000/duration)` kbit/s, and one retry at three quarters of that if the result is over 10 MB. HLG HDR is tone-mapped to BT.709. Every command is an argv list with the demuxer forced from the file signature, `-protocol_whitelist file` and `-map 0:V:0` (capital V, so cover art is never picked), under `timeout -k 10 300 nice -n 10`; on failure the tail of ffmpeg's stderr is logged with paths removed. The 60 s limit has 0.5 s of slack (a real 60 s clip probes as 60.03 s). +- **The original is kept** (on success and on failure) so "Convert again from the original upload" (a banner list action) can re-run it. It is linked only from the admin, never rendered publicly (a test pins this), deleted with the banner (`pre_delete`) and when a new upload replaces it. Originals can be up to 250 MB each on the media filesystem, which is snapshotted. +- **State:** `Banner.video_status` is `converting`, `interrupted` (started over 30 minutes ago and never finished, e.g. the worker was killed), `failed` (`video_conversion_error`), `ready` or `none`; the banner list's **Video** column and a read-only row on the form show it. `Banner.objects.displayable()` leaves out a banner whose only media is an unconverted original (landing and project pages). +- **No ffmpeg** (the checkout can be ahead of the image): an upload of at most 10 MB is stored as `video` exactly as before (and any kept original, job and error are dropped, so "Convert again" can't resurrect an older upload), a larger one is refused, the help text and the browser size check switch to 10 MB, and `/version.json` reports `"ffmpeg": false`. `validate_banner_video_size` on `Banner.video` is the 10 MB backstop for new uploads. +- **Hero markup** (`base.html`, `carousel.js`): `` follows the file (omitted for `.mov`, which Chromium would otherwise skip), only the first slide autoplays, and for a banner **with an image** (its poster) the other slides are `preload="none"` and each source is gated with `media="(prefers-reduced-motion: no-preference)"`. A banner with no image is never gated, because its paused first frame is all that can fill the hero (gated, it would be black under reduced motion or after Pause). `setVideoPlayback` lifts the gate (and calls `load()`) whenever a video is about to play, so Play works under reduced motion for every slide shown after it. +- Logs record banner ids, sizes, bitrates and timings, never file names. + ### Rich text News items use `django-ckeditor`. Uploaded files via CKEditor land under `media/uploads/`, with filenames generated by `website.utils.fileutils.get_ckeditor_image_filename`. diff --git a/Dockerfile b/Dockerfile index 42a3a483..50bbfe8d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,6 +28,11 @@ RUN pip install --upgrade pip # - sqlite3: Useful for debugging, though we use PostgreSQL in production # - git: lets docker-entrypoint.sh capture the deployed commit SHA into # build-info.json for the /version/ endpoint (#1366) +# - ffmpeg: converts uploaded banner videos to a web-ready MP4 of at most +# 10 MB (#1468). The package also provides ffprobe. It grows +# this layer by about 560 MB (132 MB -> 692 MB): apt counts 361 MB +# for ffmpeg's packages, plus the packages it upgrades, which are +# stored again in this layer. # # We clean up the apt cache afterward to reduce the final image size. RUN apt-get update \ @@ -36,6 +41,7 @@ RUN apt-get update \ ghostscript \ sqlite3 \ git \ + ffmpeg \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 515983d5..15322b1f 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -87,6 +87,29 @@ Match `git_sha` against the commit you pushed — **not `built_at`**, which has fresh while the host served stale code. The build log is the workflow run's log in the repository's GitHub Actions tab (`gh run list --workflow=deploycse-test.yml`). +### Image dependency: ffmpeg (banner videos, #1468) + +The image installs Debian's `ffmpeg` package (which also provides `ffprobe`) to +convert uploaded banner videos. It grows the image by about 560 MB, and the first build after +it was added is slow, because the new `apt` layer invalidates the cached `pip` +layer. + +`/version.json` reports `"ffmpeg": true` when both tools are on the image's +PATH. `false` means the bind-mounted checkout is ahead of the image (or the +image was built without ffmpeg); the site still works, but banner video uploads +over 10 MB are refused, and smaller ones are served as uploaded, until the image +is rebuilt. Locally, rebuild with `./run-docker-local-dev.sh --build`. + +After a deploy that changes this, check on the test server before tagging: + +- `/version.json` shows the new `git_sha` and `"ffmpeg": true`; +- in `/admin`, upload a banner video: the banner list's **Video** column reads + `converting…`, then the converted size (reload to see it change); +- uploads of about 100, 200 and 250 MB succeed through the CSE proxy (its body + limit and timeouts are not in this repo), on campus and on a slower + connection. If they fail below 250 MB, lower `MAX_UPLOAD_BYTES` in + `website/utils/video_utils.py` or raise the Gunicorn worker timeout. + ## Versioning We use [Semantic Versioning](https://semver.org/) for production releases. diff --git a/makeabilitylab/settings.py b/makeabilitylab/settings.py index 7e7f81f4..9659f408 100644 --- a/makeabilitylab/settings.py +++ b/makeabilitylab/settings.py @@ -228,11 +228,15 @@ def parse_allowed_hosts(value, django_env): CSRF_COOKIE_SECURE = True # Makeability Lab Global Variables, including Makeability Lab version -ML_WEBSITE_VERSION = "2.35.5" # Keep this updated with each release and also change the short description below -ML_WEBSITE_VERSION_DESCRIPTION = "Each of the three login-throttle pages under Administration (Access attempts, logs, failures) now explains what it records and how to unlock an account." +ML_WEBSITE_VERSION = "2.36.0" # Keep this updated with each release and also change the short description below +ML_WEBSITE_VERSION_DESCRIPTION = "Banner videos of any size up to 250 MB and 60 seconds are converted on the server to a web-ready MP4 of 10 MB or less, and the hero carousel loads only the video it is showing (none for visitors who prefer reduced motion)." DATE_MAKEABILITYLAB_FORMED = datetime.date(2012, 1, 1) # Date Makeability Lab was formed MAX_BANNERS = 7 # Maximum number of banners on a page +# Banner video conversion (#1468) runs in a daemon thread after the admin save +# commits. settings_test.py turns this on so tests run the job inline. +BANNER_VIDEO_CONVERT_INLINE = False + # With the upgrade to Django 3.2, we now need to specify the default auto field for primary keys # See: # - https://docs.djangoproject.com/en/3.2/releases/3.2/#customizing-type-of-auto-created-primary-keys diff --git a/makeabilitylab/settings_test.py b/makeabilitylab/settings_test.py index e43d2754..32414146 100644 --- a/makeabilitylab/settings_test.py +++ b/makeabilitylab/settings_test.py @@ -52,3 +52,7 @@ # state would leak between tests that share a username. The tests that cover # the throttle itself (test_login_throttle.py) switch it back on. AXES_ENABLED = False + +# Run banner video conversions (#1468) inside the on_commit callback instead of +# a background thread, so a test can capture the callback and see the result. +BANNER_VIDEO_CONVERT_INLINE = True diff --git a/website/admin/banner_admin.py b/website/admin/banner_admin.py index 225c1890..c54ace35 100644 --- a/website/admin/banner_admin.py +++ b/website/admin/banner_admin.py @@ -1,11 +1,226 @@ -from django.contrib import admin +import os +import tempfile +from contextlib import contextmanager + +from django import forms +from django.contrib import admin, messages +from django.core.exceptions import ValidationError +from django.core.files.storage import default_storage +from django.core.files.uploadedfile import UploadedFile +from django.db import transaction from django.db.models import Q +from django.utils import timezone from django.utils.html import format_html from easy_thumbnails.files import get_thumbnailer from image_cropping import ImageCroppingMixin from website.models import Banner from website.admin.admin_site import ml_admin_site +from website.utils import banner_video_jobs, video_utils +from website.utils.upload_validators import validate_video_upload + + +@contextmanager +def _local_path(upload): + """A filesystem path holding ``upload``'s bytes, for ffprobe. + + Uploads over 2.5 MB already stream to a temp file; smaller ones are held in + memory, so they are written to one here and removed afterwards. + """ + if hasattr(upload, "temporary_file_path"): + yield upload.temporary_file_path() + return + suffix = os.path.splitext(upload.name)[1] + with tempfile.NamedTemporaryFile(suffix=suffix) as handle: + for chunk in upload.chunks(): + handle.write(chunk) + handle.flush() + upload.seek(0) + yield handle.name + + +class BannerAdminForm(forms.ModelForm): + """The banner form for both BannerAdmin and the project page's inline. + + A video upload is not stored as ``Banner.video`` (#1468). ``clean_video`` + checks it and decides, changing nothing; ``save()`` stores it as + ``video_original``, marks the conversion as started and, after the + transaction commits, a background job converts it and sets ``video`` to a + web-ready MP4 of 10 MB or less. Until then the banner keeps its previous + video (or shows its image). + + Without ffmpeg (the checkout can be ahead of the image), an upload of 10 MB + or less is stored as ``video`` exactly as before, and a larger one is + refused. + """ + + class Meta: + model = Banner + fields = '__all__' + + class Media: + js = ('website/js/banner_video_size_check.js',) + + NO_FFMPEG_MESSAGE = ("This server cannot convert videos right now, so a banner video " + "must be 10 MB or less and is served as uploaded.") + # Replaces the field's help text while ffmpeg is missing: the normal text + # promises a conversion that can't happen. + NO_FFMPEG_HELP_TEXT = (NO_FFMPEG_MESSAGE + " Use a landscape MP4 (H.264) or WebM file, " + "and please also add an image below: it is shown until the video " + "loads and to visitors who prefer reduced motion.") + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._video_to_convert = None + self.video_conversion_queued = False + field = self.fields.get('video') + if field is not None: + # Read by banner_video_size_check.js, which stops an oversized + # upload before it is sent; the server checks again. + field.widget.attrs['accept'] = '.mp4,.webm,.mov,.m4v,video/mp4,video/webm,video/quicktime' + if video_utils.ffmpeg_available(): + field.widget.attrs['data-max-upload-bytes'] = str(video_utils.MAX_UPLOAD_BYTES) + else: + field.widget.attrs['data-max-upload-bytes'] = str(video_utils.MAX_SERVED_BYTES) + field.help_text = self.NO_FFMPEG_HELP_TEXT + + def clean_video(self): + """Check a new upload and decide what to do with it. Stores nothing. + + Returns None for an upload that will be converted, so the instance's + current ``video`` is left alone; ``save()`` takes it from there. + """ + value = self.cleaned_data.get('video') + self._video_to_convert = None + if not isinstance(value, UploadedFile): + return value # unchanged, or False for "Clear" + + validate_video_upload(value) # extension + signature + if value.size > video_utils.MAX_UPLOAD_BYTES: + raise ValidationError( + f"This file is {value.size / 1_000_000:.1f} MB; a banner video upload can be " + f"at most {video_utils.MAX_UPLOAD_BYTES // 1_000_000} MB.", + code='video_upload_too_large') + + if not video_utils.ffmpeg_available(): + if value.size > video_utils.MAX_SERVED_BYTES: + raise ValidationError(self.NO_FFMPEG_MESSAGE, code='no_ffmpeg') + return value # stored as Banner.video, as before #1468 + + value.seek(0) + demuxer = video_utils.demuxer_for_header(value.read(64)) + value.seek(0) + if demuxer is None: # validate_video_upload already insists on one + raise ValidationError("This file couldn't be read as a video.", code='invalid_video') + try: + with _local_path(value) as path: + info = video_utils.probe(path, demuxer) + video_utils.check_upload(info) + except video_utils.VideoRejected as exc: + raise ValidationError(str(exc), code='video_rejected') + + self._video_to_convert = value + return None + + def save(self, commit=True): + """Store a checked upload as the original and queue its conversion. + + Clearing the video also clears the job and removes the original, so a + job still running matches nothing when it finishes and can't put the + video back. So does an upload stored directly (no ffmpeg), so "Convert + again" can't later replace it with a conversion of an older upload. A + superseded original is deleted once the new one is stored. Both happen + after the commit, so a rollback keeps them. + """ + instance = self.instance + upload = self._video_to_convert + cleared = self.cleaned_data.get('video') is False + stored_directly = isinstance(self.cleaned_data.get('video'), UploadedFile) + superseded = None + if upload is not None or cleared or stored_directly: + if instance.video_original: + superseded = instance.video_original.name + instance.video_conversion_error = '' + instance.video_conversion_started = None + instance.video_original = None + if upload is not None: + instance.video_original = upload # stored by Banner.save() under a server-made name + instance.video_conversion_started = timezone.now() + self.video_conversion_queued = upload is not None + + saved = super().save(commit=commit) + if upload is not None or superseded: + if commit: + self._after_instance_saved(instance, upload is not None, superseded) + else: + # The admin saves the instance itself, then calls save_m2m(). + save_m2m = self.save_m2m + + def save_m2m_then_queue(): + save_m2m() + self._after_instance_saved(instance, upload is not None, superseded) + self.save_m2m = save_m2m_then_queue + return saved + + @staticmethod + def _after_instance_saved(instance, queue, superseded): + job = ((instance.pk, instance.video_original.name, instance.video_conversion_started) + if queue else None) + + def on_commit(): + if superseded and (job is None or superseded != job[1]): + default_storage.delete(superseded) + if job is not None: + banner_video_jobs.schedule(*job) + transaction.on_commit(on_commit) + + +def conversion_queued_message(banner): + """The message shown after a save that queued a conversion.""" + message = ("The video was received and is being converted to a web-ready MP4; " + "this usually takes under a minute. Until it finishes, the banner keeps " + "its current video or image. Reload the banner list to see the result.") + if not banner.image: + message += (" This banner has no image: please add one. It is shown while the " + "video loads and to visitors who prefer reduced motion.") + return message + + +def video_status_text(banner): + """Short text for a banner's video state, used in the list and the form.""" + status = banner.video_status + if status == Banner.VIDEO_CONVERTING: + return 'converting…' + if status == Banner.VIDEO_INTERRUPTED: + return 'interrupted' + if status == Banner.VIDEO_FAILED: + return f'conversion failed: {banner.video_conversion_error}' + if status == Banner.VIDEO_READY: + try: + size = banner.video.size + except (OSError, ValueError): + return 'file missing' + ext = os.path.splitext(banner.video.name)[1].lower() + text = f'{size / 1_000_000:.1f} MB {ext}' + if size > video_utils.MAX_SERVED_BYTES: + text += ' (over 10 MB)' + return text + return '—' + + +def video_conversion_status_html(banner): + """The change form's read-only "Video status" row, with the original's link.""" + if banner is None or banner.pk is None: + return '—' + text = video_status_text(banner) + if not banner.video_original: + return text + try: + size = f'{banner.video_original.size / 1_000_000:.1f} MB' + except (OSError, ValueError): + size = 'file missing' + return format_html('{} · original upload ({})', + text, banner.video_original.url, size) class MediaTypeFilter(admin.SimpleListFilter): @@ -46,13 +261,14 @@ def filter_queryset(queryset, value): @admin.register(Banner, site=ml_admin_site) class BannerAdmin(ImageCroppingMixin, admin.ModelAdmin): + form = BannerAdminForm # In Django, you can specify the order of fields using one of two methods: # - fields, a list of fields you want to display in order # - fieldsets, allows you to organize fields into sets fieldsets = [ ('Banner Title and Caption', {'fields': ["title", "caption", "link"]}), - ('Banner Video', {'fields': ["video"]}), + ('Banner Video', {'fields': ["video", "video_conversion_status"]}), ('Banner Image', {'fields': ["image", "alt_text", "cropping"]}), ('Banner Pages', {'fields': ["landing_page", "project"]}), ('Banner Properties', {'fields': ["favorite", "date_added"]}) @@ -61,7 +277,7 @@ class BannerAdmin(ImageCroppingMixin, admin.ModelAdmin): # The list page is the main tool for managing the ~200 banners on prod, so # it leads with a visual thumbnail and exposes inline toggles (#1082). list_display = ('thumbnail', 'title', 'project', 'landing_page', 'favorite', - 'date_added', 'get_media_url') + 'date_added', 'video_status_column', 'get_media_url') list_display_links = ('title',) list_editable = ('landing_page', 'favorite') @@ -73,10 +289,10 @@ class BannerAdmin(ImageCroppingMixin, admin.ModelAdmin): list_per_page = 50 autocomplete_fields = ['project'] - readonly_fields = ('date_added',) + readonly_fields = ('date_added', 'video_conversion_status') actions = ('add_to_landing_page', 'remove_from_landing_page', - 'mark_favorite', 'unmark_favorite') + 'mark_favorite', 'unmark_favorite', 'convert_video_again') # 1600x500 is the banner's native aspect ratio; keep the list thumbnail # proportional so editors can recognize a banner at a glance. @@ -110,6 +326,45 @@ def get_media_url(self, obj): return format_html('{}', media_url, media_url) if media_url else None get_media_url.short_description = 'Media' + @admin.display(description='Video') + def video_status_column(self, obj): + """Size and type of the served video, or the conversion's state (#1468).""" + return video_status_text(obj) + + @admin.display(description='Video status') + def video_conversion_status(self, obj): + return video_conversion_status_html(obj) + + def save_model(self, request, obj, form, change): + super().save_model(request, obj, form, change) + if getattr(form, 'video_conversion_queued', False): + self.message_user(request, conversion_queued_message(obj), messages.INFO) + + @admin.action(description='Convert video again from the original upload', + permissions=['change']) + def convert_video_again(self, request, queryset): + """Restart conversion from the kept original: the way out of a failed + or interrupted conversion, with no second upload.""" + if not video_utils.ffmpeg_available(): + self.message_user(request, BannerAdminForm.NO_FFMPEG_MESSAGE, messages.ERROR) + return + queued = skipped = 0 + for banner in queryset: + if not banner.video_original: + skipped += 1 + continue + banner.video_conversion_started = timezone.now() + banner.video_conversion_error = '' + Banner.objects.filter(pk=banner.pk).update( + video_conversion_started=banner.video_conversion_started, + video_conversion_error='') + banner_video_jobs.queue_conversion(banner) + queued += 1 + message = f'{queued} banner video(s) queued for conversion.' + if skipped: + message += f' {skipped} had no original upload to convert.' + self.message_user(request, message) + @admin.action(description='Add selected banners to the landing page') def add_to_landing_page(self, request, queryset): updated = queryset.update(landing_page=True) diff --git a/website/admin/project_admin.py b/website/admin/project_admin.py index ccb51148..a5bbd08d 100644 --- a/website/admin/project_admin.py +++ b/website/admin/project_admin.py @@ -14,6 +14,9 @@ from django.db.models.functions import Greatest, Coalesce from website.admin.utils import related_count_subquery from website.admin.admin_site import ml_admin_site +from website.admin.banner_admin import ( + BannerAdminForm, conversion_queued_message, video_conversion_status_html, +) def _contributor_count_subquery(): @@ -52,10 +55,19 @@ def get_queryset(self, request): return qs.order_by(F('end_date').desc(nulls_first=True)) class BannerInline(ImageCroppingMixin, admin.StackedInline): - """This allows us to edit Banner from the Project page""" + """This allows us to edit Banner from the Project page. + + Uses the same form as BannerAdmin, so a video uploaded here is kept as the + original and converted in the background too (#1468).""" model = Banner + form = BannerAdminForm + readonly_fields = ('video_conversion_status',) extra = 1 # Number of extra "empty" forms to show at the bottom + @admin.display(description='Video status') + def video_conversion_status(self, obj): + return video_conversion_status_html(obj) + class PhotoInline(ImageCroppingMixin, admin.StackedInline): """This allows us to add Photos from the Project page""" model = Photo @@ -228,6 +240,14 @@ def get_display_thumbnail(self, obj): get_display_thumbnail.short_description = 'Thumbnail' + def save_formset(self, request, form, formset, change): + super().save_formset(request, form, formset, change) + # A banner video uploaded through the inline is converted in the + # background (#1468); tell the editor, as BannerAdmin does. + for inline_form in formset.forms: + if getattr(inline_form, 'video_conversion_queued', False): + self.message_user(request, conversion_queued_message(inline_form.instance)) + def get_search_results(self, request, queryset, search_term): """In this code, get_search_results is a method that Django calls to get the list of results for the autocomplete dropdown. By overriding this method, you can modify the queryset that diff --git a/website/models/banner.py b/website/models/banner.py index 64b4341c..cf1aaf06 100644 --- a/website/models/banner.py +++ b/website/models/banner.py @@ -1,9 +1,16 @@ +import datetime + from django.db import models +from django.db.models import Q from django.dispatch import receiver from django.db.models.signals import pre_delete, post_save, m2m_changed, post_delete +from django.utils import timezone from website.utils.fileutils import UniquePathAndRename -from website.utils.upload_validators import validate_image_upload, validate_video_upload +from website.utils.upload_validators import ( + validate_banner_video_size, validate_image_upload, validate_video_upload, +) +from website.utils.video_utils import STALE_JOB_MINUTES from image_cropping import ImageRatioField from .project import Project @@ -11,9 +18,36 @@ import os # for joining paths + +class BannerQuerySet(models.QuerySet): + def displayable(self): + """Leave out banners whose only media is a video still being converted. + + A new video-only banner has nothing to show until its first conversion + finishes (#1468), so it would be an empty slide. Banners with no media + and no pending original (title-only slides) are kept, as before. + """ + no_image = Q(image='') | Q(image__isnull=True) + no_video = Q(video='') | Q(video__isnull=True) + has_original = ~(Q(video_original='') | Q(video_original__isnull=True)) + return self.exclude(no_image & no_video & has_original) + + class Banner(models.Model): UPLOAD_DIR = 'banner/' # relative path VIDEO_UPLOAD_DIR = os.path.join(UPLOAD_DIR, "videos") + # Uploads are kept here, under server-generated names, and linked only from + # the admin. Public pages only ever use the converted ``video`` (#1468). + VIDEO_ORIGINALS_DIR = os.path.join(VIDEO_UPLOAD_DIR, "originals") + + # Values of the ``video_status`` property. + VIDEO_NONE = 'none' + VIDEO_READY = 'ready' + VIDEO_CONVERTING = 'converting' + VIDEO_INTERRUPTED = 'interrupted' + VIDEO_FAILED = 'failed' + + objects = BannerQuerySet.as_manager() landing_page = models.BooleanField(default=False) landing_page.help_text = 'Check this box if this banner should appear on the landing page.' @@ -24,8 +58,28 @@ class Banner(models.Model): Please note that since we are using a responsive design with fixed height banners, your selected image may appear\ differently on various screens.' - video = models.FileField(upload_to=UniquePathAndRename(VIDEO_UPLOAD_DIR, True), blank=True, null=True, validators=[validate_video_upload]) - video.help_text = "Add in a background video. Ideally, video should be 10MB or less. If both a video and image are specified, the video is prioritized. The image is fallback." + # The served file. Since #1468 the banner form stores an upload as + # video_original and a background job sets this to the converted MP4; + # validate_banner_video_size is the backstop that keeps anything over 10 MB + # from being stored here through a form. + video = models.FileField(upload_to=UniquePathAndRename(VIDEO_UPLOAD_DIR, True), blank=True, null=True, + validators=[validate_video_upload, validate_banner_video_size]) + video.help_text = ("A background video: MP4, WebM or MOV, landscape, up to 60 seconds and 250 MB. " + "The server converts it to a web-ready MP4 of 10 MB or less, usually within a minute, " + "and keeps your upload. Files over about 100 MB need a fast connection. " + "Please also add an image below: it is shown until the video loads, while it converts, " + "and to visitors who prefer reduced motion.") + + # The editor's upload, kept so a conversion can be re-run. Never rendered + # publicly. Set by BannerAdminForm.save(), not by editors directly. + video_original = models.FileField(upload_to=UniquePathAndRename(VIDEO_ORIGINALS_DIR, False), + blank=True, null=True, editable=False, max_length=255) + # Set when a conversion is queued; cleared when it finishes or fails. Also + # identifies the job: a job only applies its result if this and + # video_original still match what it started with. + video_conversion_started = models.DateTimeField(blank=True, null=True, editable=False) + # Why the last conversion failed ('' when it didn't). + video_conversion_error = models.CharField(max_length=500, blank=True, default='', editable=False) alt_text = models.CharField(max_length=1024, blank=True, null=True) alt_text.help_text = "Please set the alt text for the banner" @@ -52,6 +106,38 @@ class Banner(models.Model): def __str__(self): return f"Title={self.title} Project={self.project} LandingPage={self.landing_page} Favorite={self.favorite}" + @property + def video_mime_type(self): + """The ```` for the served video, or '' to omit it. + + A ``.mov`` gets no type on purpose: Chromium doesn't claim + ``video/quicktime``, so a truthful type would make it skip a file it can + play, while with no type it fetches the file and decides. + """ + if not self.video: + return '' + ext = os.path.splitext(self.video.name)[1].lower() + return {'.mp4': 'video/mp4', '.m4v': 'video/mp4', '.webm': 'video/webm'}.get(ext, '') + + @property + def video_status(self): + """One of the VIDEO_* values: the state of this banner's video. + + A job that started more than ``STALE_JOB_MINUTES`` ago and never + finished (the worker was killed or the container restarted) reads as + interrupted; "Convert again" in the admin restarts it. + """ + if self.video_conversion_started: + age = timezone.now() - self.video_conversion_started + if age > datetime.timedelta(minutes=STALE_JOB_MINUTES): + return self.VIDEO_INTERRUPTED + return self.VIDEO_CONVERTING + if self.video_conversion_error: + return self.VIDEO_FAILED + if self.video: + return self.VIDEO_READY + return self.VIDEO_NONE + @receiver(pre_delete, sender=Banner) def banner_delete(sender, instance, **kwargs): @@ -61,4 +147,9 @@ def banner_delete(sender, instance, **kwargs): # delete video file (if it exists) if instance.video: - instance.video.delete(False) \ No newline at end of file + instance.video.delete(False) + + # delete the kept upload (if it exists); a job still running for this + # banner then matches no row and deletes its own output (#1468) + if instance.video_original: + instance.video_original.delete(False) diff --git a/website/static/website/js/banner_video_size_check.js b/website/static/website/js/banner_video_size_check.js new file mode 100644 index 00000000..5c9da0f6 --- /dev/null +++ b/website/static/website/js/banner_video_size_check.js @@ -0,0 +1,119 @@ +/*! + * Banner video size check (#1468) — vanilla JS, admin only. + * + * A banner video upload must arrive within the server's request time limit, + * so the server refuses files over a ceiling (250 MB). Without this script an + * editor would only learn that after the whole file had been sent. This checks + * the chosen file's size in the browser, before the upload starts: + * + * - on `change`, an oversized file gets an error message beside the field + * (role="alert", so screen readers announce it) and the input is marked + * aria-invalid; + * - on `submit`, the form is stopped and focus moves to the first oversized + * field. + * + * It applies to every file input carrying `data-max-upload-bytes` (set by + * BannerAdminForm), including inline banner rows added later on the project + * page, because both listeners are delegated from `document`. The server + * checks again; this is only a convenience. + */ +(function () { + 'use strict'; + + var SELECTOR = 'input[type="file"][data-max-upload-bytes]'; + + function formatMB(bytes) { + return (bytes / 1000000).toFixed(1) + ' MB'; + } + + /** Returns the oversized File chosen in `input`, or null. */ + function oversizedFile(input) { + var max = parseInt(input.getAttribute('data-max-upload-bytes'), 10); + if (!max || !input.files || input.files.length === 0) { + return null; + } + var file = input.files[0]; + return file.size > max ? file : null; + } + + /** The input's error element; created only when `create` is true. */ + function errorElementFor(input, create) { + var id = input.id ? input.id + '-size-error' : ''; + var el = id ? document.getElementById(id) : null; + if (!el && create) { + el = document.createElement('p'); + if (id) { + el.id = id; + } + el.className = 'errornote banner-video-size-error'; + el.setAttribute('role', 'alert'); + input.insertAdjacentElement('afterend', el); + } + return el; + } + + /** Shows or clears the size error for one input; returns true if oversized. */ + function check(input) { + var file = oversizedFile(input); + var el = errorElementFor(input, !!file); + if (file) { + var max = parseInt(input.getAttribute('data-max-upload-bytes'), 10); + el.textContent = 'This file is ' + formatMB(file.size) + + '; a banner video upload can be at most ' + formatMB(max) + + '. Trim or compress it and choose it again.'; + el.hidden = false; + input.setAttribute('aria-invalid', 'true'); + if (el.id) { + setDescribedBy(input, el.id, true); + } + return true; + } + if (el) { + el.textContent = ''; + el.hidden = true; + if (el.id) { + setDescribedBy(input, el.id, false); + } + } + input.removeAttribute('aria-invalid'); + return false; + } + + /** + * Adds or removes one id in the input's aria-describedby, keeping the ids + * already there (Django links the help text that way). + */ + function setDescribedBy(input, id, present) { + var ids = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter(function (t) { + return t && t !== id; + }); + if (present) { + ids.push(id); + } + if (ids.length) { + input.setAttribute('aria-describedby', ids.join(' ')); + } else { + input.removeAttribute('aria-describedby'); + } + } + + document.addEventListener('change', function (event) { + if (event.target.matches && event.target.matches(SELECTOR)) { + check(event.target); + } + }); + + document.addEventListener('submit', function (event) { + var inputs = event.target.querySelectorAll ? event.target.querySelectorAll(SELECTOR) : []; + var firstBad = null; + Array.prototype.forEach.call(inputs, function (input) { + if (check(input) && !firstBad) { + firstBad = input; + } + }); + if (firstBad) { + event.preventDefault(); + firstBad.focus(); + } + }, true); +})(); diff --git a/website/static/website/js/carousel.js b/website/static/website/js/carousel.js index 1534ce51..6b53b846 100644 --- a/website/static/website/js/carousel.js +++ b/website/static/website/js/carousel.js @@ -14,9 +14,16 @@ * * Accessibility: * - Honors prefers-reduced-motion: no autoplay, no looping hero video, and - * (via CSS) no crossfade. The video keeps its `autoplay` attribute so the - * no-JS baseline still plays it; this script pauses it when reduced motion - * is set. See issue #1294. + * (via CSS) no crossfade. The first slide's video keeps its `autoplay` + * attribute so the no-JS baseline still plays it; this script pauses it + * when reduced motion is set. See issue #1294. For a banner with an image + * (its poster), each video is gated with a `media` query, so + * under reduced motion no video is even downloaded until the visitor + * presses Play (#1468). A banner with no image is not gated: its paused + * first frame is all that can fill the hero. + * - For banners with an image, only the active slide's video loads: the + * others have preload="none" and start downloading when play() is called + * as they become active. * - WCAG 2.2.2 (Pause, Stop, Hide): a visible `.carousel-motion-toggle` * button (if present) pauses/plays BOTH the auto-advance and the hero video * for all users — a discoverable mechanism, not just hover/focus. @@ -72,11 +79,33 @@ return slide ? slide.querySelector('video') : null; } + /** + * Lifts the reduced-motion gate from a video's sources (#1468). Each + * carries media="(prefers-reduced-motion: no-preference)", so a + * visitor who prefers reduced motion downloads nothing. Once motion is + * allowed (they pressed Play), every video about to play is ungated; if + * the browser had selected no source, load() runs source selection again. + */ + function ungateSources(video) { + var gated = video.querySelectorAll('source[media]'); + if (gated.length === 0) { + return; + } + Array.prototype.forEach.call(gated, function (source) { + source.removeAttribute('media'); + }); + if (!video.currentSrc) { + video.load(); + } + } + function setVideoPlayback(video, shouldPlay) { if (!video) { return; } if (shouldPlay) { + // Here, not in toggleMotion: every slide shown after Play needs it. + ungateSources(video); var playback = video.play(); if (playback && playback.catch) { playback.catch(function () { /* autoplay blocked — ignore */ }); diff --git a/website/templates/website/base.html b/website/templates/website/base.html index 3a52e895..4198390b 100644 --- a/website/templates/website/base.html +++ b/website/templates/website/base.html @@ -309,13 +309,21 @@ {% if banner.video %} {% comment %} - autoplay is kept so the no-JS baseline still plays the video; carousel.js - pauses it under prefers-reduced-motion and via the pause control (#1294). - The poster (banner image, when set) is the still shown while paused. + Only the first (active) slide autoplays, so the no-JS baseline still + plays it; carousel.js calls play() on each slide as it becomes + active (#1468). type follows the file and is omitted for .mov, which + Chromium would otherwise skip. The poster (banner image, when set) is + the still shown while paused (#1294). + With a poster: inactive slides get preload="none" (play() starts the + download) and the source is gated on prefers-reduced-motion: + no-preference, so a visitor who prefers reduced motion downloads no + video and sees the poster; pressing Play lifts the gate (carousel.js). + Without a poster neither applies: the paused first frame is all that + can fill the hero, and gating it would leave the hero black. {% endcomment %} - {% elif banner.image %}
hi")}) + self.assertFalse(form.is_valid()) + self.probe_mock.assert_not_called() + + def test_editing_another_field_mid_conversion_keeps_the_job(self): + # Only a new upload or "Clear" may drop the kept original and cancel + # the running job; a title edit on a banner that already has a video + # must not (#1477 review 2). + self.patch_tools() + banner = self.make_pending(Banner.objects.create( + title="Converting", landing_page=True, video="banner/videos/old.mp4")) + original, started = banner.video_original.name, banner.video_conversion_started + form = self.form(data=_data(title="Renamed mid-conversion"), instance=banner) + self.assertTrue(form.is_valid(), form.errors) + with self.captureOnCommitCallbacks(execute=True) as callbacks: + form.save() + self.assertEqual(len(callbacks), 0) + banner.refresh_from_db() + self.assertEqual(banner.title, "Renamed mid-conversion") + self.assertEqual(banner.video_original.name, original) + self.assertEqual(banner.video_conversion_started, started) + self.assertEqual(banner.video.name, "banner/videos/old.mp4") + self.assertTrue(default_storage.exists(original)) + + def test_unchanged_video_is_not_probed_again(self): + self.patch_tools() + banner = Banner.objects.create(title="Has video", video="banner/videos/old.mp4") + form = self.form(data=_data(title="Renamed"), instance=banner) + self.assertTrue(form.is_valid(), form.errors) + with self.captureOnCommitCallbacks(execute=True) as callbacks: + form.save() + self.assertEqual(len(callbacks), 0) + self.probe_mock.assert_not_called() + banner.refresh_from_db() + self.assertEqual(banner.video.name, "banner/videos/old.mp4") + self.assertIsNone(banner.video_conversion_started) + + def test_without_ffmpeg_small_upload_is_kept_and_large_one_rejected(self): + self.patch_tools(available=False) + banner, _ = self.save_upload(_upload("small.mp4"), expect_callbacks=0) + banner.refresh_from_db() + self.assertTrue(banner.video.name.startswith("banner/videos/small")) + self.assertFalse(banner.video_original) + self.assertIsNone(banner.video_conversion_started) + self.probe_mock.assert_not_called() + + form = self.form(files={"video": _upload("big.mov", size=10_000_001)}) + self.assertFalse(form.is_valid()) + self.assertIn("cannot convert videos right now", " ".join(form.errors["video"])) + + def test_without_ffmpeg_help_text_says_so(self): + self.patch_tools(available=False) + field = self.form().fields["video"] + self.assertIn("cannot convert videos right now", str(field.help_text)) + # It replaces the normal text rather than contradicting it. + self.assertNotIn("250 MB", str(field.help_text)) + self.assertNotIn("converts it", str(field.help_text)) + # The browser check uses the limit that applies now. + self.assertEqual(field.widget.attrs["data-max-upload-bytes"], + str(self.vu.MAX_SERVED_BYTES)) + self.patch_tools(available=True) + field = self.form().fields["video"] + self.assertNotIn("cannot convert videos right now", str(field.help_text)) + self.assertEqual(field.widget.attrs["data-max-upload-bytes"], + str(self.vu.MAX_UPLOAD_BYTES)) + + def test_without_ffmpeg_direct_upload_drops_the_stale_original(self): + # Upload A with ffmpeg (kept as the original), then B without. B is + # served as is, so A's original, job and error must go: otherwise + # "Convert again" would replace B with a conversion of A (#1477 review). + self.patch_tools() + banner, _ = self.save_upload() + banner = Banner.objects.get(pk=banner.pk) + first_original = banner.video_original.name + Banner.objects.filter(pk=banner.pk).update(video_conversion_error="old failure") + banner.refresh_from_db() + + self.patch_tools(available=False) + banner, _ = self.save_upload(_upload("b.mp4"), instance=banner) + banner.refresh_from_db() + self.assertTrue(banner.video.name.startswith("banner/videos/b")) + self.assertFalse(banner.video_original) + self.assertIsNone(banner.video_conversion_started) + self.assertEqual(banner.video_conversion_error, "") + self.assertFalse(default_storage.exists(first_original)) + + def test_disallowed_extension_with_video_header_is_refused(self): + # validate_video_upload is the only check on the convert path: + # video_original has no validators and keeps the upload's extension. + self.patch_tools() + for name in ("clip.html", "clip.svg", "clip.avi"): + with self.subTest(name): + form = self.form(files={"video": _upload(name)}) + self.assertFalse(form.is_valid()) + self.assertIn("video", form.errors) + self.probe_mock.assert_not_called() + + def test_size_messages_use_one_decimal(self): + self.patch_tools() + form = self.form(files={"video": _upload(size=250_400_000)}) + self.assertFalse(form.is_valid()) + self.assertIn("250.4 MB", " ".join(form.errors["video"])) + + def test_inline_form_is_banner_admin_form(self): + from website.admin.project_admin import BannerInline + self.assertTrue(issubclass(BannerInline.form, self.BannerAdminForm)) + + @override_settings(BANNER_VIDEO_CONVERT_INLINE=False) + def test_thread_started_after_commit_when_not_inline(self): + self.patch_tools() + with mock.patch.object(self.jobs.threading, "Thread") as thread: + banner, callbacks = self.save_upload(execute=False) + thread.assert_not_called() # nothing before the commit + callbacks[0]() + thread.assert_called_once() + kwargs = thread.call_args.kwargs + self.assertTrue(kwargs["daemon"]) + self.assertEqual(kwargs["args"][0], banner.pk) + self.assertEqual(kwargs["args"][1], banner.video_original.name) + thread.return_value.start.assert_called_once() + self.convert_mock.assert_not_called() # the thread (mocked) does the work + + def test_job_older_than_30_minutes_reads_as_interrupted(self): + banner = self.make_pending() + self.assertEqual(banner.video_status, "converting") + banner.video_conversion_started = timezone.now() - datetime.timedelta(minutes=29) + self.assertEqual(banner.video_status, "converting") + banner.video_conversion_started = timezone.now() - datetime.timedelta(minutes=31) + self.assertEqual(banner.video_status, "interrupted") + + def test_convert_again_action_restarts_from_original(self): + from website.admin.admin_site import ml_admin_site + from website.admin.banner_admin import BannerAdmin + self.patch_tools() + banner = self.make_pending() + Banner.objects.filter(pk=banner.pk).update( + video_conversion_started=None, video_conversion_error="ffmpeg timed out") + no_original = Banner.objects.create(title="Nothing to convert") + admin = BannerAdmin(Banner, ml_admin_site) + request = RequestFactory().post("/") + with mock.patch.object(admin, "message_user") as message_user, \ + self.captureOnCommitCallbacks(execute=True) as callbacks: + admin.convert_video_again( + request, Banner.objects.filter(pk__in=[banner.pk, no_original.pk])) + self.assertEqual(len(callbacks), 1) + message_user.assert_called() + banner.refresh_from_db() + self.assertTrue(banner.video.name.endswith(".mp4")) + self.assertEqual(banner.video_conversion_error, "") + self.assertIsNone(banner.video_conversion_started) + self.convert_mock.assert_called_once() + self.assertEqual(self.convert_mock.call_args.args[0], + default_storage.path(banner.video_original.name)) + + def test_replacing_video_deletes_superseded_original(self): + self.patch_tools() + banner, _ = self.save_upload() + first = Banner.objects.get(pk=banner.pk).video_original.name + self.assertTrue(default_storage.exists(first)) + banner, _ = self.save_upload(instance=Banner.objects.get(pk=banner.pk)) + banner.refresh_from_db() + self.assertNotEqual(banner.video_original.name, first) + self.assertFalse(default_storage.exists(first)) + self.assertTrue(default_storage.exists(banner.video_original.name)) + + def test_deleting_banner_deletes_original(self): + self.patch_tools() + banner, _ = self.save_upload() + banner.refresh_from_db() + original, video = banner.video_original.name, banner.video.name + banner.delete() + self.assertFalse(default_storage.exists(original)) + self.assertFalse(default_storage.exists(video)) + + def test_public_pages_never_reference_original(self): + self.patch_tools() + project = self.make_project(name="Clip Project", short_name="clipproject", + is_visible=True) + banner = Banner.objects.create(title="Public", landing_page=True, project=project) + self.save_upload(instance=banner, data=_data(title="Public", project=str(project.pk))) + banner.refresh_from_db() + self.assertEqual(banner.project, project) + self.assertTrue(banner.video and banner.video_original) + for url in (reverse("website:index"), + reverse("website:project", args=[project.short_name])): + html = self.client.get(url).content.decode() + self.assertIn(banner.video.name, html, url) + self.assertNotIn("originals/", html, url) + self.assertNotIn(banner.video_original.name, html, url) + + def test_banner_with_only_unconverted_original_is_not_shown(self): + project = self.make_project(name="Pending Project", short_name="pendingproject", + is_visible=True) + pending = self.make_pending( + Banner.objects.create(title="PendingOnlyBanner", landing_page=True, + project=project)) + # The landing view queries favourites and the rest separately. + self.make_pending(Banner.objects.create(title="PendingFavouriteBanner", + landing_page=True, favorite=True)) + Banner.objects.create(title="TitleOnlyBanner", landing_page=True, project=project) + urls = (reverse("website:index"), + reverse("website:project", args=[project.short_name])) + for url in urls: + html = self.client.get(url).content.decode() + self.assertNotIn("PendingOnlyBanner", html, url) + self.assertNotIn("PendingFavouriteBanner", html, url) + self.assertIn("TitleOnlyBanner", html, url) # existing behaviour kept + Banner.objects.filter(pk=pending.pk).update(video="banner/videos/done.mp4") + for url in urls: + self.assertIn("PendingOnlyBanner", self.client.get(url).content.decode(), url) + + def test_log_lines_use_ids_and_sizes(self): + self.patch_tools() + with self.assertLogs("website.utils.banner_video_jobs", level="INFO") as logs: + banner, _ = self.save_upload(_upload("Secret Trip To Somewhere.mov")) + banner.refresh_from_db() + text = "\n".join(logs.output) + self.assertIn(f"Banner {banner.pk} ", text) + self.assertIn("1500000", text) # output size in bytes + self.assertIn(str(len(MOV_BYTES)), text) # original size in bytes + self.assertNotIn("Secret", text) + self.assertNotIn("originals/", text) + self.assertNotIn(banner.video.name, text) + + +class BannerVideoJobRunnerTests(_MediaRootMixin, DatabaseTestCase): + """The job runner's plumbing and the "Convert again" action's edges.""" + + def admin(self): + from website.admin.admin_site import ml_admin_site + from website.admin.banner_admin import BannerAdmin + return BannerAdmin(Banner, ml_admin_site) + + def test_thread_closes_its_database_connection(self): + with mock.patch.object(self.jobs, "run_job") as run_job, \ + mock.patch.object(self.jobs.connection, "close") as close: + self.jobs._thread_main(1, "x", None) + run_job.assert_called_once_with(1, "x", None) + close.assert_called_once() + + def test_jobs_take_an_exclusive_lock(self): + import fcntl + self.patch_tools() + with mock.patch.object(self.jobs.fcntl, "flock", wraps=fcntl.flock) as flock: + self.save_upload() + # Django's file storage locks files too; keep only the job lock's calls. + ops = [c.args[1] for c in flock.call_args_list + if getattr(c.args[0], "name", None) == self.jobs._lock_path()] + self.assertEqual(ops, [fcntl.LOCK_EX, fcntl.LOCK_UN]) + + def test_job_superseded_before_it_starts_does_no_work(self): + self.patch_tools() + banner, callbacks = self.save_upload(execute=False) + self.probe_mock.reset_mock() # the form probed the upload; the job must not + Banner.objects.filter(pk=banner.pk).update( + video_conversion_started=timezone.now() + datetime.timedelta(seconds=5)) + callbacks[0]() + self.convert_mock.assert_not_called() + self.probe_mock.assert_not_called() + + def test_convert_again_needs_ffmpeg(self): + self.patch_tools(available=False) + banner = self.make_pending() + Banner.objects.filter(pk=banner.pk).update(video_conversion_started=None) + admin = self.admin() + with mock.patch.object(admin, "message_user") as message_user, \ + self.captureOnCommitCallbacks(execute=True) as callbacks: + admin.convert_video_again(RequestFactory().post("/"), + Banner.objects.filter(pk=banner.pk)) + self.assertEqual(len(callbacks), 0) + self.assertIn("cannot convert", message_user.call_args.args[1]) + banner.refresh_from_db() + self.assertIsNone(banner.video_conversion_started) + + def test_convert_again_requires_change_permission(self): + self.assertEqual(tuple(self.admin().convert_video_again.allowed_permissions), + ("change",)) + + def test_convert_again_supersedes_a_running_job(self): + self.patch_tools() + banner = self.make_pending() + old_start = banner.video_conversion_started + admin = self.admin() + with mock.patch.object(admin, "message_user"), \ + self.captureOnCommitCallbacks(execute=False) as callbacks: + admin.convert_video_again(RequestFactory().post("/"), + Banner.objects.filter(pk=banner.pk)) + self.assertEqual(len(callbacks), 1) + banner.refresh_from_db() + self.assertGreater(banner.video_conversion_started, old_start) + + def test_size_backstop_is_wired_and_matches_the_cap(self): + from website.utils import upload_validators + self.assertEqual(upload_validators.BANNER_VIDEO_MAX_BYTES, self.vu.MAX_SERVED_BYTES) + validators = Banner._meta.get_field("video").validators + self.assertIn(upload_validators.validate_banner_video_size, validators) + + +def _browser_post_data(html): + """What a browser would submit for the admin form in ``html``: every named + input, select and textarea with its current value (no files, no buttons, + no empty-form templates).""" + from html.parser import HTMLParser + + class Scraper(HTMLParser): + def __init__(self): + super().__init__() + self.data, self.select, self.multiple = {}, None, False + self.first, self.chosen, self.textarea = None, False, None + + def handle_starttag(self, tag, attrs): + a = dict(attrs) + name = a.get("name") + if tag == "input" and name: + kind = a.get("type", "text") + if kind in ("checkbox", "radio"): + if "checked" in a: + self.data[name] = a.get("value", "on") + elif kind not in ("file", "submit", "button"): + self.data[name] = a.get("value", "") + elif tag == "select" and name: + self.select, self.multiple = name, "multiple" in a + self.first, self.chosen = None, False + elif tag == "option" and self.select: + if self.first is None: + self.first = a.get("value", "") + if "selected" in a: + self.chosen = True + if self.multiple: + self.data.setdefault(self.select, []).append(a.get("value", "")) + else: + self.data[self.select] = a.get("value", "") + elif tag == "textarea" and name: + self.textarea = name + self.data[name] = "" + + def handle_endtag(self, tag): + if tag == "select" and self.select: + if not self.chosen and not self.multiple: + self.data[self.select] = self.first or "" + self.select = None + elif tag == "textarea": + self.textarea = None + + def handle_data(self, data): + if self.textarea: + self.data[self.textarea] += data + + scraper = Scraper() + scraper.feed(html) + return {k: v for k, v in scraper.data.items() + if "__prefix__" not in k and k != "csrfmiddlewaretoken"} + + +class BannerVideoAdminViewTests(_MediaRootMixin, DatabaseTestCase): + """Uploads through the real admin views. BannerAdmin saves with + ``commit=False`` (the job is queued from the wrapped ``save_m2m``), and the + project page saves banners through its inline formset; both must queue + the conversion and tell the editor (#1477 review, finding 4).""" + + def setUp(self): + super().setUp() + user = get_user_model().objects.create_superuser("root", "r@example.com", "pw") + self.client.force_login(user) + self.patch_tools() + + def messages(self, response): + from django.contrib.messages import get_messages + return [str(m) for m in get_messages(response.wsgi_request)] + + def test_banner_add_view_queues_conversion_and_says_so(self): + data = {"title": "Added", "caption": "", "link": "", "alt_text": "", + "cropping": "", "landing_page": "on", "project": "", "video": _upload()} + with self.captureOnCommitCallbacks(execute=True) as callbacks: + response = self.client.post(reverse("admin:website_banner_add"), data) + self.assertEqual(response.status_code, 302) + self.assertEqual(len(callbacks), 1) + banner = Banner.objects.get(title="Added") + self.assertRegex(banner.video.name, r"^banner/videos/[0-9a-f]{32}\.mp4$") + self.assertTrue(banner.video_original) + self.assertTrue(any("being converted" in m for m in self.messages(response))) + + def test_project_inline_upload_queues_conversion_and_says_so(self): + project = self.make_project(name="Inline Project", short_name="inlineproject", + is_visible=True) + url = reverse("admin:website_project_change", args=[project.pk]) + page = self.client.get(url) + self.assertEqual(page.status_code, 200) + data = _browser_post_data(page.content.decode()) + data["banner_set-0-title"] = "Inline banner" + data["banner_set-0-video"] = _upload() + with self.captureOnCommitCallbacks(execute=True) as callbacks: + response = self.client.post(url, data) + self.assertEqual(response.status_code, 302, + getattr(response, "context", None) and [ + fs.formset.errors for fs in response.context["inline_admin_formsets"]]) + self.assertEqual(len(callbacks), 1) + banner = Banner.objects.get(project=project) + self.assertTrue(banner.video.name.endswith(".mp4")) + self.assertTrue(any("being converted" in m for m in self.messages(response))) + + +class BannerAdminSaveGuardTests(DatabaseTestCase): + """**(guard)** Passes on master: the admin re-reads the banner on POST, so a + form opened before a conversion finished does not undo the new video.""" + + def test_form_save_after_finished_conversion_keeps_new_video(self): + user = get_user_model().objects.create_superuser("root", "r@example.com", "pw") + self.client.force_login(user) + banner = Banner.objects.create(title="Before", video="banner/videos/old.mp4") + url = reverse("admin:website_banner_change", args=[banner.pk]) + page = self.client.get(url) # the editor opens the form ... + self.assertEqual(page.status_code, 200) + # ... a background conversion finishes ... + Banner.objects.filter(pk=banner.pk).update(video="banner/videos/converted.mp4") + # ... and the editor saves a title change without touching the video. + response = self.client.post(url, { + "title": "After", "caption": "", "link": "", "alt_text": "", + "cropping": "", "landing_page": "on", "project": "", + }) + self.assertEqual(response.status_code, 302, getattr(response, "context", None) + and response.context["adminform"].form.errors) + banner.refresh_from_db() + self.assertEqual(banner.title, "After") + self.assertEqual(banner.video.name, "banner/videos/converted.mp4") diff --git a/website/tests/test_hero_carousel_e2e.py b/website/tests/test_hero_carousel_e2e.py new file mode 100644 index 00000000..7b1306a0 --- /dev/null +++ b/website/tests/test_hero_carousel_e2e.py @@ -0,0 +1,290 @@ +""" +Browser tests for how the hero carousel loads banner videos (#1468). + +They count the browser's requests for banner video URLs, which the Django test +client cannot see: + +* only the active slide's video is requested on load; +* another slide's video is requested when that slide is shown; +* a visitor who prefers reduced motion requests no video at all; +* pressing Play under reduced motion loads the active video, and every slide + shown after that (the gate comes off in ``setVideoPlayback``, not only on the + slide that was active when Play was pressed). + +Each reduced-motion test first loads the same page with no preference and +asserts a video *is* requested, so it cannot pass just because nothing was ever +requested. + +Media is not served by the test server (DEBUG is off), so the video requests +are intercepted and answered with a 404. Only whether a request was made +matters here. + +Skip-guarded like ``test_member_e2e.py``: the module skips when Playwright or +its Chromium is missing. Run with: + + python manage.py test website.tests.test_hero_carousel_e2e \ + --settings=makeabilitylab.settings_test +""" + +import os +import shutil +import tempfile +import unittest + +from django.contrib.staticfiles.testing import StaticLiveServerTestCase +from django.test import override_settings + +try: + from playwright.sync_api import sync_playwright + _PLAYWRIGHT_IMPORT_ERROR = None +except Exception as exc: # pragma: no cover - environment dependent + sync_playwright = None + _PLAYWRIGHT_IMPORT_ERROR = exc + +os.environ.setdefault("DJANGO_ALLOW_ASYNC_UNSAFE", "1") + +# How long to give the page to (not) request something before asserting. +SETTLE_MS = 1500 + + +def _png_upload(name="poster.png"): + """A small real PNG, so the banner has an image (and its video a poster).""" + from io import BytesIO + + from django.core.files.uploadedfile import SimpleUploadedFile + from PIL import Image + + buffer = BytesIO() + Image.new("RGB", (160, 50), (90, 9, 121)).save(buffer, format="PNG") + return SimpleUploadedFile(name, buffer.getvalue(), content_type="image/png") + + +class _BrowserMixin: + """One Chromium per class; a temp MEDIA_ROOT per test.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + try: + cls._pw = sync_playwright().start() + cls._browser = cls._pw.chromium.launch() + except Exception as exc: # browser binary missing, etc. + super().tearDownClass() + raise unittest.SkipTest(f"Chromium unavailable for Playwright: {exc}") + + @classmethod + def tearDownClass(cls): + try: + cls._browser.close() + cls._pw.stop() + finally: + super().tearDownClass() + + def setUp(self): + super().setUp() + media_root = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, media_root, ignore_errors=True) + override = override_settings(MEDIA_ROOT=media_root) + override.enable() + self.addCleanup(override.disable) + + +@unittest.skipIf(sync_playwright is None, + f"Playwright not installed ({_PLAYWRIGHT_IMPORT_ERROR})") +class HeroCarouselVideoLoadingE2ETests(_BrowserMixin, StaticLiveServerTestCase): + """Banners with an image: the image is the poster, so their videos are + gated on reduced motion and the inactive ones don't preload.""" + + # ---- fixtures ----------------------------------------------------------- + + def setUp(self): + super().setUp() + from website.models import Banner + for i in range(3): + Banner.objects.create(title=f"Slide {i}", landing_page=True, favorite=True, + video=f"banner/videos/slide{i}.mp4", + image=_png_upload(f"poster{i}.png")) + + def _open(self, reduced_motion="no-preference"): + """Open the landing page; return (page, list of requested video names).""" + context = self._browser.new_context( + viewport={"width": 1280, "height": 800}, reduced_motion=reduced_motion) + self.addCleanup(context.close) + page = context.new_page() + requested = [] + + def handle(route): + requested.append(route.request.url.rsplit("/", 1)[-1]) + route.fulfill(status=404, body="") + page.route("**/media/banner/videos/**", handle) + page.goto(f"{self.live_server_url}/") + page.wait_for_selector("#main-carousel .item.active video") + page.wait_for_timeout(SETTLE_MS) + return page, requested + + def _slide_video_names(self, page): + """Video file names in slide order, as rendered.""" + return page.eval_on_selector_all( + "#main-carousel .carousel-inner > .item source", + "els => els.map(e => e.getAttribute('src').split('/').pop())") + + def _wait_for_request(self, page, requested, name): + for _ in range(30): + if name in requested: + return + page.wait_for_timeout(100) + self.fail(f"{name} was never requested; requested: {requested}") + + # ---- tests -------------------------------------------------------------- + + def test_only_active_slide_video_is_requested(self): + page, requested = self._open() + names = self._slide_video_names(page) + self.assertEqual(len(names), 3) + self.assertEqual(set(requested), {names[0]}) + + def test_second_video_requested_when_its_slide_is_shown(self): + page, requested = self._open() + names = self._slide_video_names(page) + self.assertNotIn(names[1], requested) + page.click("#main-carousel .carousel-indicators li:nth-child(2)") + self._wait_for_request(page, requested, names[1]) + self.assertNotIn(names[2], requested) + + def test_no_video_requested_under_reduced_motion(self): + _, control = self._open() + self.assertTrue(control, "control: with no preference a video must load") + _, requested = self._open(reduced_motion="reduce") + self.assertEqual(requested, []) + + def test_play_control_loads_video_under_reduced_motion(self): + _, control = self._open() + self.assertTrue(control, "control: with no preference a video must load") + page, requested = self._open(reduced_motion="reduce") + self.assertEqual(requested, []) + names = self._slide_video_names(page) + toggle = page.locator("#main-carousel .carousel-motion-toggle") + self.assertEqual(toggle.get_attribute("aria-label"), "Play background motion") + toggle.click() + self._wait_for_request(page, requested, names[0]) + + def test_after_play_under_reduced_motion_the_next_slide_also_loads(self): + _, control = self._open() + self.assertTrue(control, "control: with no preference a video must load") + page, requested = self._open(reduced_motion="reduce") + self.assertEqual(requested, []) + names = self._slide_video_names(page) + page.locator("#main-carousel .carousel-motion-toggle").click() + self._wait_for_request(page, requested, names[0]) + page.click("#main-carousel .carousel-indicators li:nth-child(2)") + self._wait_for_request(page, requested, names[1]) + + +# A one-second 320x160 H.264 clip, small enough to keep in the repo, so the +# browser has real frames to paint (the CI e2e job has no ffmpeg to make one). +FIXTURE_MP4 = os.path.join(os.path.dirname(__file__), "fixtures", "hero_frame.mp4") + + +@unittest.skipIf(sync_playwright is None, + f"Playwright not installed ({_PLAYWRIGHT_IMPORT_ERROR})") +class HeroVideoWithoutImageE2ETests(_BrowserMixin, StaticLiveServerTestCase): + """A video banner with no image has no poster, so it is never gated: its + first frame is the only thing that can fill the hero. Gating it would leave + a black hero for reduced-motion visitors and for anyone who pauses (#1477 + review, finding 1).""" + + def setUp(self): + super().setUp() + from website.models import Banner + for i in range(2): + Banner.objects.create(title=f"Bare {i}", landing_page=True, favorite=True, + video=f"banner/videos/bare{i}.mp4") + with open(FIXTURE_MP4, "rb") as handle: + self.clip = handle.read() + + def _open(self, reduced_motion): + context = self._browser.new_context( + viewport={"width": 1280, "height": 800}, reduced_motion=reduced_motion) + self.addCleanup(context.close) + page = context.new_page() + page.route("**/media/banner/videos/**", + lambda route: route.fulfill(status=200, body=self.clip, + content_type="video/mp4")) + page.goto(f"{self.live_server_url}/") + page.wait_for_selector("#main-carousel .item.active video") + return page + + def _wait_for_frame(self, page, slide_index): + """Wait until that slide's video has a frame to paint (readyState >= 2).""" + page.wait_for_function( + "i => { const v = document.querySelectorAll(" + "'#main-carousel .carousel-inner > .item video')[i];" + " return v && v.readyState >= 2; }", arg=slide_index, timeout=5000) + + def test_first_frame_is_painted_under_reduced_motion(self): + page = self._open("reduce") + self._wait_for_frame(page, 0) + video = page.locator("#main-carousel .item.active video") + self.assertTrue(video.evaluate("v => v.paused"), "reduced motion must not play") + + def test_next_slide_has_a_frame_after_pause(self): + page = self._open("no-preference") + page.locator("#main-carousel .carousel-motion-toggle").click() # Pause + page.click("#main-carousel .carousel-indicators li:nth-child(2)") + self._wait_for_frame(page, 1) + + +@unittest.skipIf(sync_playwright is None, + f"Playwright not installed ({_PLAYWRIGHT_IMPORT_ERROR})") +class BannerVideoSizeCheckE2ETests(_BrowserMixin, StaticLiveServerTestCase): + """banner_video_size_check.js on the banner admin form.""" + + def setUp(self): + super().setUp() + from django.contrib.auth import get_user_model + get_user_model().objects.create_superuser("root", "r@example.com", "pw-e2e") + + def _add_page(self): + context = self._browser.new_context(viewport={"width": 1280, "height": 900}) + self.addCleanup(context.close) + page = context.new_page() + page.goto(f"{self.live_server_url}/admin/login/") + page.fill("#id_username", "root") + page.fill("#id_password", "pw-e2e") + page.click("input[type=submit]") + page.goto(f"{self.live_server_url}/admin/website/banner/add/") + # Shrink the ceiling so a small file stands in for an oversized one. + page.eval_on_selector("#id_video", "el => el.setAttribute('data-max-upload-bytes', '100')") + return page + + def test_oversized_file_blocks_submit_and_is_announced(self): + page = self._add_page() + posts = [] + page.on("request", lambda r: posts.append(r.url) if r.method == "POST" else None) + page.set_input_files("#id_video", files=[{ + "name": "big.mp4", "mimeType": "video/mp4", "buffer": b"\x00" * 500}]) + error = page.locator("#id_video-size-error") + self.assertEqual(error.get_attribute("role"), "alert") + # One decimal, like the server's message: 500 bytes against a + # 100-byte ceiling reads "0.0 MB", not "0 MB". + self.assertIn("This file is 0.0 MB; a banner video upload can be at most 0.0 MB", + error.inner_text()) + self.assertEqual(page.get_attribute("#id_video", "aria-invalid"), "true") + page.click("input[name=_save]") + page.wait_for_timeout(500) + self.assertEqual(posts, [], "the form must not be submitted") + self.assertEqual(page.evaluate("document.activeElement.id"), "id_video") + + def test_valid_file_restores_aria_describedby(self): + page = self._add_page() + original = page.get_attribute("#id_video", "aria-describedby") or "" + page.set_input_files("#id_video", files=[{ + "name": "big.mp4", "mimeType": "video/mp4", "buffer": b"\x00" * 500}]) + described = page.get_attribute("#id_video", "aria-describedby").split() + self.assertIn("id_video-size-error", described) + for token in original.split(): + self.assertIn(token, described) # the help text stays linked + page.set_input_files("#id_video", files=[{ + "name": "ok.mp4", "mimeType": "video/mp4", "buffer": b"\x00" * 50}]) + self.assertEqual(page.get_attribute("#id_video", "aria-describedby") or "", original) + self.assertIsNone(page.get_attribute("#id_video", "aria-invalid")) diff --git a/website/tests/test_hero_motion.py b/website/tests/test_hero_motion.py index 24d82bc8..c0e73bcc 100644 --- a/website/tests/test_hero_motion.py +++ b/website/tests/test_hero_motion.py @@ -17,6 +17,8 @@ manually + via Pa11y; these tests guard the markup it hooks into. """ +import re +import shutil import tempfile from django.test import override_settings @@ -85,3 +87,78 @@ def test_pause_control_rendered(self): ) html = self.client.get(reverse("website:index")).content.decode() self.assertIn("carousel-motion-toggle", html) + + +class HeroVideoLoadingTests(DatabaseTestCase): + """Hero markup from #1468: a truthful (or absent) ``type``, only the first + slide autoplays, and, for a banner with an image (its poster), inactive + slides don't preload and every source is gated on + ``prefers-reduced-motion: no-preference``, so a visitor who prefers reduced + motion downloads no video at all. A banner with no image is never gated: + its first frame is all that can fill the hero.""" + + def setUp(self): + super().setUp() + media_root = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, media_root, ignore_errors=True) + override = override_settings(MEDIA_ROOT=media_root) + override.enable() + self.addCleanup(override.disable) + + def _videos(self, *names, image=True): + for i, name in enumerate(names): + Banner.objects.create(title=f"V{i}", landing_page=True, favorite=True, + video=f"banner/videos/{name}", + image=_make_png_upload(f"p{i}.png") if image else None) + # The landing view shuffles banners, so assertions below are about + # position in the page, not about which file lands where. + html = self.client.get(reverse("website:index")).content.decode() + return re.findall(r"", html, re.S) + + def _source(self, video_html): + return re.search(r"]*>", video_html).group(0) + + def _tag(self, video_html): + return video_html.split(">")[0] + + def test_source_type_follows_extension(self): + for name, mime in (("a.mp4", "video/mp4"), ("b.m4v", "video/mp4"), + ("c.webm", "video/webm"), ("d.MP4", "video/mp4")): + with self.subTest(name): + Banner.objects.all().delete() + (video,) = self._videos(name) + self.assertIn(f'type="{mime}"', self._source(video)) + + def test_mov_source_has_no_type_attribute(self): + # Chromium doesn't claim video/quicktime, so a truthful type would make + # it skip a .mov it can actually play. With no type it fetches and decides. + (video,) = self._videos("legacy.mov") + self.assertNotIn("type=", self._source(video)) + self.assertIn("legacy.mov", self._source(video)) + + def test_only_first_slide_autoplays(self): + for image in (True, False): + with self.subTest(image=image): + Banner.objects.all().delete() + videos = self._videos("a.mp4", "b.mp4", "c.mp4", image=image) + self.assertEqual(len(videos), 3) + self.assertEqual([("autoplay" in self._tag(v)) for v in videos], + [True, False, False]) + + def test_inactive_slides_have_preload_none(self): + videos = self._videos("a.mp4", "b.mp4") + self.assertNotIn('preload="none"', self._tag(videos[0])) + self.assertIn('preload="none"', self._tag(videos[1])) + + def test_sources_are_gated_on_reduced_motion(self): + for video in self._videos("a.mp4", "b.mov"): + self.assertIn('media="(prefers-reduced-motion: no-preference)"', + self._source(video)) + + def test_banner_without_image_is_not_gated_and_preloads(self): + # No poster: the paused first frame is the only thing that can fill the + # hero, so the browser must be allowed to fetch it. + videos = self._videos("a.mp4", "b.mp4", image=False) + for video in videos: + self.assertNotIn("media=", self._source(video)) + self.assertNotIn('preload="none"', self._tag(video)) diff --git a/website/tests/test_upload_validators.py b/website/tests/test_upload_validators.py index 9b104bd2..a77880a4 100644 --- a/website/tests/test_upload_validators.py +++ b/website/tests/test_upload_validators.py @@ -23,6 +23,13 @@ ) +def _banner_size_validator(): + # Imported lazily: it is new in #1468, and the rest of this module must + # still run on code that predates it. + from website.utils.upload_validators import validate_banner_video_size + return validate_banner_video_size + + # --- Sample file headers --------------------------------------------------- PNG = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR" + b"\x00" * 16 @@ -160,3 +167,22 @@ def test_committed_files_are_not_validated(self): validate_pdf_upload(_CommittedFile("legacy.txt")) validate_video_upload(_CommittedFile("legacy.avi")) validate_raw_file_upload(_CommittedFile("legacy.tex")) + + +class BannerVideoSizeTests(SimpleTestCase): + """Backstop on Banner.video (#1468): nothing over 10 MB is stored as the + served file. Normal uploads never reach it, because the banner form diverts + them to the original and converts them; it catches the no-ffmpeg path and + any code that assigns Banner.video directly through a form.""" + + def test_banner_video_over_10mb_rejected(self): + validate = _banner_size_validator() + validate(_upload("ok.mp4", MP4 + b"\x00" * (10_000_000 - len(MP4)))) + with self.assertRaisesRegex(ValidationError, "10 MB"): + validate(_upload("big.mp4", MP4 + b"\x00" * (10_000_001 - len(MP4)))) + + def test_committed_banner_video_not_rechecked(self): + validate = _banner_size_validator() + legacy = _CommittedFile("banner/videos/legacy-40mb.mp4") + legacy.size = 40_000_000 + validate(legacy) # an existing (stored) file is never re-checked diff --git a/website/tests/test_version_endpoint.py b/website/tests/test_version_endpoint.py index 255c81cc..17053724 100644 --- a/website/tests/test_version_endpoint.py +++ b/website/tests/test_version_endpoint.py @@ -155,6 +155,17 @@ def test_reports_degraded_rotation(self): data = json.loads(self.client.get("/version/").content) self.assertEqual(data["log_rotation"], "RotatingFileHandler") + def test_reports_ffmpeg_availability(self): + """``ffmpeg`` says whether this server can convert banner videos (#1468). + False means the checkout is ahead of the image (or the image lacks + ffmpeg), so banner uploads over 10 MB are refused.""" + from unittest import mock + from website.utils import video_utils + for available in (True, False): + with mock.patch.object(video_utils, "ffmpeg_available", return_value=available): + data = json.loads(self.client.get("/version/").content) + self.assertIs(data["ffmpeg"], available) + def test_build_info_missing_falls_back_to_unknown(self): with override_settings(): # Point at a path that doesn't exist. diff --git a/website/tests/test_video_utils.py b/website/tests/test_video_utils.py new file mode 100644 index 00000000..ed74bbce --- /dev/null +++ b/website/tests/test_video_utils.py @@ -0,0 +1,564 @@ +""" +Tests for website.utils.video_utils, the ffprobe/ffmpeg layer behind banner +video conversion (#1468). + +Two styles: + +* **Unit** (``SimpleTestCase``, ``subprocess.run`` patched): the probe parser, + the upload checks, the stream-copy rule, the bitrate and frame-rate rules, + and the exact ffmpeg command lines. These need no ffmpeg. +* **RealFfmpegTests**: builds short clips with ffmpeg's own test source and runs + the real commands. The command line is the product, and a mock cannot tell a + working flag from a typo or from a flag one ffmpeg version lacks. The class + skips when ffmpeg is absent, so the suite stays green on a laptop or an old + image; set ``REQUIRE_FFMPEG=1`` (CI does) to turn that skip into a failure. +""" + +import json +import os +import shutil +import subprocess +import tempfile +import unittest +from unittest import mock + +from django.test import SimpleTestCase + +from website.utils import video_utils +from website.utils.video_utils import ( + ConversionError, + VideoInfo, + VideoRejected, +) + + +def _info(**overrides): + """A landscape 1080p30 H.264 clip; override any field.""" + fields = dict( + width=1920, height=1080, rotation=0, duration=8.0, codec="h264", + pix_fmt="yuv420p", r_frame_rate="30/1", avg_frame_rate="30/1", + color_transfer=None, + ) + fields.update(overrides) + return VideoInfo(**fields) + + +def _ffprobe_json(streams=None, duration="8.000000"): + if streams is None: + streams = [{ + "codec_type": "video", "codec_name": "h264", "width": 1920, + "height": 1080, "pix_fmt": "yuv420p", "r_frame_rate": "30/1", + "avg_frame_rate": "30/1", + }] + fmt = {"format_name": "mov,mp4,m4a,3gp,3g2,mj2"} + if duration is not None: + fmt["duration"] = duration + return {"streams": streams, "format": fmt} + + +def _completed(returncode=0, stdout=b"", stderr=b""): + return subprocess.CompletedProcess(args=[], returncode=returncode, + stdout=stdout, stderr=stderr) + + +class ProbeTests(SimpleTestCase): + + def test_probe_parses_ffprobe_json(self): + data = _ffprobe_json(streams=[ + {"codec_type": "audio", "codec_name": "aac"}, + {"codec_type": "video", "codec_name": "hevc", "width": 3840, + "height": 2160, "pix_fmt": "yuv420p10le", "r_frame_rate": "30/1", + "avg_frame_rate": "30/1", "color_transfer": "arib-std-b67", + "side_data_list": [{"side_data_type": "Display Matrix", + "rotation": -90}]}, + ], duration="12.5") + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed(stdout=json.dumps(data).encode())): + info = video_utils.probe("/tmp/x.mov", "mov") + self.assertEqual(info.width, 3840) + self.assertEqual(info.height, 2160) + self.assertEqual(info.rotation, -90) + self.assertEqual(info.duration, 12.5) + self.assertEqual(info.codec, "hevc") + self.assertEqual(info.pix_fmt, "yuv420p10le") + self.assertEqual(info.color_transfer, "arib-std-b67") + + def test_probe_command_forces_demuxer_and_whitelists_file_protocol(self): + cmd = video_utils.build_probe_command("/tmp/x.mov", "mov") + self.assertEqual(cmd[0], "ffprobe") + self.assertIn("-protocol_whitelist", cmd) + self.assertEqual(cmd[cmd.index("-protocol_whitelist") + 1], "file") + self.assertEqual(cmd[cmd.index("-f") + 1], "mov") + self.assertLess(cmd.index("-f"), cmd.index("/tmp/x.mov")) + + def test_probe_rejects_file_without_video_stream_even_when_ffprobe_exits_zero(self): + data = _ffprobe_json(streams=[{"codec_type": "audio", "codec_name": "aac"}]) + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed(stdout=json.dumps(data).encode())): + with self.assertRaises(VideoRejected): + video_utils.probe("/tmp/x.mp4", "mov") + + def test_probe_ignores_cover_art_stream(self): + data = _ffprobe_json(streams=[{ + "codec_type": "video", "codec_name": "mjpeg", "width": 600, + "height": 600, "disposition": {"attached_pic": 1}, + }]) + with self.assertRaises(VideoRejected): + video_utils.parse_probe(data) + + def test_probe_rejects_when_ffprobe_fails_or_times_out(self): + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed(returncode=1, stderr=b"moov atom not found")): + with self.assertRaises(VideoRejected): + video_utils.probe("/tmp/x.mp4", "mov") + with mock.patch.object(video_utils.subprocess, "run", + side_effect=subprocess.TimeoutExpired("ffprobe", 30)): + with self.assertRaises(VideoRejected): + video_utils.probe("/tmp/x.mp4", "mov") + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed(stdout=b"not json")): + with self.assertRaises(VideoRejected): + video_utils.probe("/tmp/x.mp4", "mov") + + def test_demuxer_follows_signature(self): + self.assertEqual(video_utils.demuxer_for_header(b"\x00\x00\x00\x18ftypmp42"), "mov") + self.assertEqual(video_utils.demuxer_for_header(b"\x1aE\xdf\xa3\x01"), "matroska") + self.assertIsNone(video_utils.demuxer_for_header(b"#EXTM3U\n")) + + +class UploadCheckTests(SimpleTestCase): + + def test_accepts_ordinary_landscape_clip(self): + video_utils.check_upload(_info()) # no exception + + def test_rejects_clip_over_60_seconds(self): + with self.assertRaisesRegex(VideoRejected, r"60\.6 seconds long.*at most 60 seconds"): + video_utils.check_upload(_info(duration=60.6)) + video_utils.check_upload(_info(duration=60.0)) + + def test_clip_at_60_seconds_with_container_overhang_is_accepted(self): + # A real 60 s clip at 29.97 fps probes as 60.027 s (#1477 review). + video_utils.check_upload(_info(duration=60.027)) + video_utils.check_upload(_info(duration=60.5)) + + def test_rejects_frame_over_4096(self): + with self.assertRaises(VideoRejected): + video_utils.check_upload(_info(width=4097, height=2160)) + video_utils.check_upload(_info(width=4096, height=2160)) + + def test_rejects_pq_transfer(self): + with self.assertRaisesRegex(VideoRejected, "HDR"): + video_utils.check_upload(_info(color_transfer="smpte2084")) + # HLG is converted, not refused. + video_utils.check_upload(_info(color_transfer="arib-std-b67")) + + def test_rejects_unknown_duration(self): + with self.assertRaises(VideoRejected): + video_utils.check_upload(_info(duration=None)) + + def test_portrait_detected_from_rotation_side_data(self): + # A phone clip: stored 1920x1080, rotated 90 on display. + self.assertTrue(video_utils.is_portrait(_info(rotation=90))) + self.assertTrue(video_utils.is_portrait(_info(rotation=-90))) + self.assertTrue(video_utils.is_portrait(_info(width=1080, height=1920))) + self.assertFalse(video_utils.is_portrait(_info(rotation=180))) + self.assertFalse(video_utils.is_portrait(_info(width=1080, height=1920, rotation=90))) + with self.assertRaisesRegex(VideoRejected, "(?i)portrait"): + video_utils.check_upload(_info(rotation=90)) + + +class StreamCopyRuleTests(SimpleTestCase): + + def test_stream_copy_allowed_for_small_h264_yuv420p(self): + self.assertTrue(video_utils.can_stream_copy(_info(), 2_000_000)) + self.assertTrue(video_utils.can_stream_copy(_info(), 10_000_000)) + + def test_stream_copy_refused_when_not_h264(self): + self.assertFalse(video_utils.can_stream_copy(_info(codec="hevc"), 2_000_000)) + + def test_stream_copy_refused_when_not_yuv420p(self): + self.assertFalse(video_utils.can_stream_copy(_info(pix_fmt="yuv420p10le"), 2_000_000)) + + def test_stream_copy_refused_when_over_10mb(self): + self.assertFalse(video_utils.can_stream_copy(_info(), 10_000_001)) + + def test_stream_copy_refused_when_larger_than_1080p(self): + self.assertFalse(video_utils.can_stream_copy(_info(width=2560, height=1440), 2_000_000)) + + def test_stream_copy_refused_for_hlg(self): + self.assertFalse(video_utils.can_stream_copy( + _info(color_transfer="arib-std-b67"), 2_000_000)) + + +class CommandTests(SimpleTestCase): + + def _encode_cmd(self, info=None, maxrate=2500): + return video_utils.build_encode_command( + "/tmp/in.mov", "/tmp/out.mp4", "mov", info or _info(), maxrate) + + def _vf(self, cmd): + return cmd[cmd.index("-vf") + 1] + + def test_command_drops_audio_strips_metadata_and_sets_faststart(self): + for cmd in (self._encode_cmd(), + video_utils.build_copy_command("/tmp/in.mov", "/tmp/out.mp4", "mov")): + self.assertIn("-an", cmd) + self.assertEqual(cmd[cmd.index("-movflags") + 1], "+faststart") + self.assertEqual(cmd[cmd.index("-map_metadata") + 1], "-1") + # Capital V: video streams that are not attached pictures, the same + # rule parse_probe uses. "0:v:0" can pick cover art (#1477 review). + self.assertEqual(cmd[cmd.index("-map") + 1], "0:V:0") + self.assertEqual(cmd[-1], "/tmp/out.mp4") + cmd = self._encode_cmd() + self.assertEqual(cmd[cmd.index("-pix_fmt") + 1], "yuv420p") + self.assertEqual(cmd[cmd.index("-c:v") + 1], "libx264") + self.assertIn("format=yuv420p", self._vf(cmd)) + + def test_command_forces_demuxer_and_uses_no_shell(self): + cmd = self._encode_cmd() + self.assertIsInstance(cmd, list) + self.assertEqual(cmd[cmd.index("-f") + 1], "mov") + self.assertLess(cmd.index("-f"), cmd.index("-i")) + self.assertEqual(cmd[cmd.index("-protocol_whitelist") + 1], "file") + self.assertLess(cmd.index("-protocol_whitelist"), cmd.index("-i")) + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed()) as run: + video_utils.run_ffmpeg(cmd) + self.assertIs(run.call_args.args[0], cmd) + self.assertFalse(run.call_args.kwargs.get("shell", False)) + + def test_command_is_wrapped_in_timeout(self): + for cmd in (self._encode_cmd(), + video_utils.build_copy_command("/tmp/in.mov", "/tmp/out.mp4", "mov")): + # -k: if ffmpeg ignores SIGTERM, timeout SIGKILLs it 10 s later + # instead of waiting (and being killed itself, orphaning ffmpeg). + self.assertEqual(cmd[:4], ["timeout", "-k", "10", + str(video_utils.FFMPEG_TIMEOUT_SECONDS)]) + self.assertEqual(cmd[4:7], ["nice", "-n", "10"]) + self.assertEqual(cmd[7], "ffmpeg") + + def test_encode_fits_inside_1600x900_without_cropping(self): + vf = self._vf(self._encode_cmd()) + self.assertIn("min(1600,iw)", vf) + self.assertIn("min(900,ih)", vf) + self.assertIn("force_original_aspect_ratio=decrease", vf) + self.assertNotIn("crop", vf) + + def test_bitrate_ceiling_follows_duration(self): + self.assertEqual(video_utils.bitrate_ceiling_kbps(8), 2500) + self.assertEqual(video_utils.bitrate_ceiling_kbps(60), 1200) + self.assertEqual(video_utils.bitrate_ceiling_kbps(36), 2000) + cmd = self._encode_cmd(maxrate=1200) + self.assertEqual(cmd[cmd.index("-maxrate") + 1], "1200k") + self.assertEqual(cmd[cmd.index("-bufsize") + 1], "2400k") + + def test_frame_rate_rule_handles_variable_rate_and_caps_at_30(self): + rate = video_utils.output_frame_rate + self.assertEqual(rate("24/1", "24/1"), "24") + self.assertEqual(rate("30000/1001", "30000/1001"), "30000/1001") + self.assertEqual(rate("60/1", "60/1"), "30") + # Variable-rate phone clip: r_frame_rate is meaningless, use avg. + self.assertEqual(rate("90000/1", "2997/100"), "30") + self.assertEqual(rate("600/1", "24/1"), "24") + self.assertEqual(rate("0/0", "0/0"), "30") + vf = self._vf(self._encode_cmd(_info(r_frame_rate="24/1", avg_frame_rate="24/1"))) + self.assertIn("fps=24", vf) + + def test_hlg_source_gets_tone_mapping_filters(self): + sdr = self._vf(self._encode_cmd()) + self.assertNotIn("tonemap", sdr) + hlg = self._vf(self._encode_cmd(_info(color_transfer="arib-std-b67"))) + self.assertIn("tonemap=hable", hlg) + self.assertIn("zscale=t=linear", hlg) + # The tone mapping runs after the downscale. + self.assertLess(hlg.index("scale="), hlg.index("zscale")) + + +class ConvertTests(SimpleTestCase): + """video_utils.convert(): stream copy or encode, size check, one retry.""" + + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + self.src = os.path.join(self.tmp, "in.mov") + self.dst = os.path.join(self.tmp, "out.mp4") + with open(self.src, "wb") as f: + f.write(b"\x00" * 100) + + def _writes(self, *sizes): + """A run_ffmpeg stand-in that writes outputs of the given sizes in turn.""" + sizes = list(sizes) + + def fake(cmd): + with open(cmd[-1], "wb") as f: + f.truncate(sizes.pop(0)) + return fake + + def test_retry_runs_once_when_result_is_over_cap(self): + info = _info(codec="hevc", duration=12) + with mock.patch.object(video_utils, "run_ffmpeg", + side_effect=self._writes(10_000_001, 9_000_000)) as run: + result = video_utils.convert(self.src, self.dst, "mov", info, 50_000_000) + self.assertEqual(run.call_count, 2) + first, second = (c.args[0] for c in run.call_args_list) + self.assertEqual(first[first.index("-maxrate") + 1], "2500k") + self.assertEqual(second[second.index("-maxrate") + 1], "1875k") + self.assertEqual(result.size, 9_000_000) + self.assertEqual(result.mode, "encode") + + def test_conversion_fails_when_retry_is_still_over_cap(self): + info = _info(codec="hevc") + with mock.patch.object(video_utils, "run_ffmpeg", + side_effect=self._writes(12_000_000, 10_000_001)) as run: + with self.assertRaisesRegex(ConversionError, "10 MB"): + video_utils.convert(self.src, self.dst, "mov", info, 50_000_000) + self.assertEqual(run.call_count, 2) + + def test_result_at_exactly_the_cap_is_served(self): + with mock.patch.object(video_utils, "run_ffmpeg", + side_effect=self._writes(10_000_000)) as run: + result = video_utils.convert(self.src, self.dst, "mov", + _info(codec="hevc"), 50_000_000) + self.assertEqual(run.call_count, 1) + self.assertEqual(result.size, 10_000_000) + + def test_over_cap_stream_copy_falls_back_to_encode(self): + with mock.patch.object(video_utils, "run_ffmpeg", + side_effect=self._writes(10_000_001, 2_000_000)) as run: + result = video_utils.convert(self.src, self.dst, "mov", _info(), 9_000_000) + self.assertEqual(run.call_count, 2) + self.assertEqual(result.mode, "encode") + self.assertEqual(result.size, 2_000_000) + + def test_small_h264_is_stream_copied(self): + with mock.patch.object(video_utils, "run_ffmpeg", + side_effect=self._writes(1_000_000)) as run: + result = video_utils.convert(self.src, self.dst, "mov", _info(), 1_200_000) + self.assertEqual(result.mode, "copy") + cmd = run.call_args.args[0] + self.assertEqual(cmd[cmd.index("-c") + 1], "copy") + + def test_python_limit_outlasts_the_timeout_wrapper(self): + # If Python's subprocess timeout fired first it would kill `timeout` + # and orphan ffmpeg, which is what -k exists to prevent. + cmd = video_utils.build_copy_command(self.src, self.dst, "mov") + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed()) as run: + video_utils.run_ffmpeg(cmd) + self.assertGreater(run.call_args.kwargs["timeout"], + video_utils.FFMPEG_TIMEOUT_SECONDS + + video_utils.FFMPEG_KILL_AFTER_SECONDS) + + def test_failure_log_keeps_only_the_last_lines_and_the_status(self): + cmd = video_utils.build_copy_command(self.src, self.dst, "mov") + stderr = "".join(f"line {i}\n" for i in range(1, 9)).encode() + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed(returncode=3, stderr=stderr)), \ + self.assertLogs("website.utils.video_utils", level="WARNING") as logs: + with self.assertRaises(ConversionError): + video_utils.run_ffmpeg(cmd) + text = "\n".join(logs.output) + self.assertIn("status 3", text) + self.assertIn("line 4 | line 5 | line 6 | line 7 | line 8", text) + self.assertNotIn("line 3", text) + + def test_failure_logs_stderr_tail_without_paths(self): + cmd = video_utils.build_copy_command(self.src, self.dst, "mov") + stderr = (f"{self.src}: Invalid data found when processing input\n" + f"Error opening output {self.dst}\nboom at the end\n").encode() + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed(returncode=1, stderr=stderr)), \ + self.assertLogs("website.utils.video_utils", level="WARNING") as logs: + with self.assertRaises(ConversionError): + video_utils.run_ffmpeg(cmd) + text = "\n".join(logs.output) + self.assertIn("boom at the end", text) + self.assertIn("Invalid data found", text) + self.assertNotIn(self.src, text) + self.assertNotIn(self.dst, text) + + def test_conversion_fails_on_ffmpeg_error_and_on_timeout(self): + cmd = video_utils.build_copy_command(self.src, self.dst, "mov") + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed(returncode=1, stderr=b"boom")): + with self.assertRaisesRegex(ConversionError, "status 1"): + video_utils.run_ffmpeg(cmd) + # coreutils `timeout` exits 124 when it stops ffmpeg; with -k it can + # end as 137 (128 + SIGKILL), or be reported as killed by signal 9. + limit = video_utils.FFMPEG_TIMEOUT_SECONDS + for code in (124, 137, -9): + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed(returncode=code)), \ + mock.patch.object(video_utils.time, "monotonic", + side_effect=[0.0, limit + 10.0]): + with self.assertRaisesRegex(ConversionError, "timed out"): + video_utils.run_ffmpeg(cmd) + # A SIGKILL well before the limit is something else (the OOM killer, + # an operator), not the timeout (#1477 review 2). + for code in (137, -9): + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed(returncode=code)), \ + mock.patch.object(video_utils.time, "monotonic", + side_effect=[0.0, 1.5]): + with self.assertRaisesRegex(ConversionError, f"status {code}$"): + video_utils.run_ffmpeg(cmd) + with mock.patch.object(video_utils.subprocess, "run", + side_effect=subprocess.TimeoutExpired("timeout", 330)): + with self.assertRaisesRegex(ConversionError, "timed out"): + video_utils.run_ffmpeg(cmd) + # And convert() passes the failure on rather than serving anything. + with mock.patch.object(video_utils.subprocess, "run", + return_value=_completed(returncode=1)): + with self.assertRaises(ConversionError): + video_utils.convert(self.src, self.dst, "mov", _info(codec="hevc"), 50_000_000) + + +def _moov_children_udta_first(data): + """Return an MP4 with its moov box's children reordered so udta comes + right after mvhd, which makes ffmpeg list the attached picture first.""" + import struct + pos, out = 0, [] + while pos < len(data): + size, kind = struct.unpack(">I4s", data[pos:pos + 8]) + if size == 1: + size = struct.unpack(">Q", data[pos + 8:pos + 16])[0] + elif size == 0: + size = len(data) - pos + box = data[pos:pos + size] + if kind == b"moov": + children, p = [], 8 + while p < len(box): + child_size, child_kind = struct.unpack(">I4s", box[p:p + 8]) + children.append((child_kind, box[p:p + child_size])) + p += child_size + children.sort(key=lambda c: {b"mvhd": 0, b"udta": 1}.get(c[0], 2)) + box = box[:8] + b"".join(c[1] for c in children) + out.append(box) + pos += size + return b"".join(out) + + +def _require_ffmpeg(): + return os.environ.get("REQUIRE_FFMPEG") == "1" + + +_HAVE_FFMPEG = bool(shutil.which("ffmpeg") and shutil.which("ffprobe")) + + +@unittest.skipIf(not _HAVE_FFMPEG and not _require_ffmpeg(), + "ffmpeg/ffprobe not installed (set REQUIRE_FFMPEG=1 to make this a failure)") +class RealFfmpegTests(SimpleTestCase): + """Runs the real commands against clips made with ffmpeg's test source.""" + + def setUp(self): + if not _HAVE_FFMPEG: + self.fail("REQUIRE_FFMPEG=1 but ffmpeg/ffprobe are not on PATH") + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + + def _make(self, name, *args): + path = os.path.join(self.tmp, name) + subprocess.run(["ffmpeg", "-v", "error", "-y", *args, path], check=True) + return path + + def _streams(self, path): + out = subprocess.run( + ["ffprobe", "-v", "error", "-print_format", "json", "-show_streams", + "-show_format", path], check=True, capture_output=True).stdout + return json.loads(out) + + def _demuxer(self, path): + with open(path, "rb") as f: + return video_utils.demuxer_for_header(f.read(64)) + + def test_encode_produces_web_ready_mp4(self): + src = self._make( + "src.mov", + "-f", "lavfi", "-i", "testsrc2=size=2560x1440:rate=60:duration=3", + "-f", "lavfi", "-i", "sine=frequency=440:duration=3", + "-c:v", "libx264", "-pix_fmt", "yuv444p", "-c:a", "aac", "-shortest") + info = video_utils.probe(src, self._demuxer(src)) + dst = os.path.join(self.tmp, "out.mp4") + result = video_utils.convert(src, dst, "mov", info, os.path.getsize(src)) + self.assertEqual(result.mode, "encode") + data = self._streams(dst) + self.assertEqual([s["codec_type"] for s in data["streams"]], ["video"]) + video = data["streams"][0] + self.assertEqual(video["codec_name"], "h264") + self.assertEqual(video["pix_fmt"], "yuv420p") + self.assertLessEqual(video["width"], 1600) + self.assertLessEqual(video["height"], 900) + self.assertEqual(video["r_frame_rate"], "30/1") + with open(dst, "rb") as f: + head = f.read(4096) + # +faststart: the index (moov) comes before the media data (mdat). + self.assertIn(b"moov", head) + self.assertLessEqual(os.path.getsize(dst), video_utils.MAX_SERVED_BYTES) + + def test_stream_copy_strips_location_tag(self): + src = self._make( + "tagged.mov", + "-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30:duration=2", + "-c:v", "libx264", "-pix_fmt", "yuv420p", + "-metadata", "location=+47.6062-122.3321/", "-metadata", "title=secret") + self.assertIn("location", json.dumps(self._streams(src)["format"].get("tags", {}))) + info = video_utils.probe(src, "mov") + dst = os.path.join(self.tmp, "copy.mp4") + result = video_utils.convert(src, dst, "mov", info, os.path.getsize(src)) + self.assertEqual(result.mode, "copy") + tags = json.dumps(self._streams(dst)["format"].get("tags", {})) + self.assertNotIn("location", tags) + self.assertNotIn("secret", tags) + + def test_hlg_source_comes_out_8bit_bt709(self): + src = self._make( + "hlg.mov", + "-f", "lavfi", "-i", "testsrc2=size=1280x720:rate=30:duration=2", + "-c:v", "libx265", "-pix_fmt", "yuv420p10le", + "-color_primaries", "bt2020", "-color_trc", "arib-std-b67", + "-colorspace", "bt2020nc", "-tag:v", "hvc1") + info = video_utils.probe(src, "mov") + self.assertTrue(video_utils.is_hlg(info)) + video_utils.check_upload(info) + dst = os.path.join(self.tmp, "sdr.mp4") + video_utils.convert(src, dst, "mov", info, os.path.getsize(src)) + video = self._streams(dst)["streams"][0] + self.assertEqual(video["pix_fmt"], "yuv420p") + self.assertEqual(video.get("color_transfer"), "bt709") + self.assertEqual(video.get("color_primaries"), "bt709") + + def test_cover_art_ahead_of_the_video_is_not_served(self): + """An MP4 whose attached picture is stream 0 (its udta box precedes the + video trak). probe() skips the picture; the commands must too.""" + vid = self._make("v.mp4", "-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30:duration=2", + "-c:v", "libx264", "-pix_fmt", "yuv420p") + cover = self._make("cover.png", "-f", "lavfi", "-i", "color=c=red:size=320x180", + "-frames:v", "1") + art = self._make("art.mp4", "-i", vid, "-i", cover, "-map", "0", "-map", "1", + "-c", "copy", "-disposition:v:1", "attached_pic") + crafted = os.path.join(self.tmp, "art-first.mp4") + with open(art, "rb") as f, open(crafted, "wb") as out: + out.write(_moov_children_udta_first(f.read())) + streams = self._streams(crafted)["streams"] + self.assertEqual(streams[0]["disposition"]["attached_pic"], 1, "fixture: art first") + info = video_utils.probe(crafted, "mov") + self.assertEqual(info.codec, "h264") + dst = os.path.join(self.tmp, "out.mp4") + video_utils.convert(crafted, dst, "mov", info, os.path.getsize(crafted)) + out_streams = self._streams(dst)["streams"] + self.assertEqual([(x["codec_name"], x["width"]) for x in out_streams], [("h264", 640)]) + + def test_garbage_file_is_rejected(self): + path = os.path.join(self.tmp, "garbage.mp4") + with open(path, "wb") as f: + f.write(b"\x00\x00\x00\x18ftypmp42" + os.urandom(4000)) + with self.assertRaises(VideoRejected): + video_utils.probe(path, "mov") + + def test_playlist_renamed_mp4_is_rejected(self): + path = os.path.join(self.tmp, "list.mp4") + with open(path, "wb") as f: + f.write(b"#EXTM3U\n#EXTINF:1,\nfile:///etc/passwd\n") + self.assertIsNone(self._demuxer(path)) + with self.assertRaises(VideoRejected): + video_utils.probe(path, "mov") diff --git a/website/utils/banner_video_jobs.py b/website/utils/banner_video_jobs.py new file mode 100644 index 00000000..41cef7c2 --- /dev/null +++ b/website/utils/banner_video_jobs.py @@ -0,0 +1,184 @@ +""" +Background conversion of banner videos (#1468). + +The admin request only stores the upload as ``Banner.video_original`` and sets +``video_conversion_started``; the conversion runs after the transaction +commits, in a daemon thread of the same Gunicorn worker. There is no task +queue: a handful of uploads a month doesn't justify a new service, and a thread +needs nothing from CSE IT. + +How a job behaves: + +* **One at a time.** A file lock (``fcntl.flock``) in the container's temp + directory serializes jobs across Gunicorn's three workers. The kernel drops + the lock if a worker dies. +* **Identity.** A job is (banner id, original's stored name, start time). It + applies its result with one ``UPDATE`` filtered on all three, so a job that + was superseded (a new upload, "Convert again", the video cleared, the banner + deleted) changes nothing and deletes its own output. +* **Failure** is recorded in ``video_conversion_error``; the original and the + previous video stay. +* **A killed worker** leaves ``video_conversion_started`` set, which the admin + shows as "interrupted" after ``STALE_JOB_MINUTES``; "Convert again" restarts + it from the kept original. ffmpeg runs under ``timeout``, so it ends itself + even with no parent. +* **Logging** records banner ids, sizes, bitrates and timings, never file + names: the uploaded name is the editor's, and the stored names are not + needed to diagnose anything. + +Tests set ``BANNER_VIDEO_CONVERT_INLINE = True`` so a captured ``on_commit`` +callback runs the job in the test thread. +""" + +import fcntl +import logging +import os +import shutil +import tempfile +import threading +import time +from contextlib import contextmanager + +from django.conf import settings +from django.core.files import File +from django.core.files.storage import default_storage +from django.db import connection, transaction + +from website.utils import video_utils +from website.utils.fileutils import UniquePathAndRename + +_logger = logging.getLogger(__name__) + +#: Longest error text kept on the banner (the column is 500 characters). +_MAX_ERROR_LENGTH = 500 + + +def _lock_path(): + # Per-uid so a lock file left by another user can't block us. + return os.path.join(tempfile.gettempdir(), f"makelab-banner-video-{os.getuid()}.lock") + + +@contextmanager +def _job_lock(): + """Hold an exclusive lock so only one conversion runs at a time.""" + with open(_lock_path(), "a") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(handle, fcntl.LOCK_UN) + + +def queue_conversion(banner): + """Register this banner's current job to start after the commit. + + The job's identity is read now, from the saved banner, so a later change + to the instance can't alter which job runs. + """ + banner_id = banner.pk + original_name = banner.video_original.name + started = banner.video_conversion_started + transaction.on_commit(lambda: schedule(banner_id, original_name, started)) + + +def schedule(banner_id, original_name, started): + """Run the job inline (tests) or in a daemon thread (servers).""" + if getattr(settings, "BANNER_VIDEO_CONVERT_INLINE", False): + run_job(banner_id, original_name, started) + return + thread = threading.Thread(target=_thread_main, args=(banner_id, original_name, started), + name=f"banner-video-{banner_id}", daemon=True) + thread.start() + + +def _thread_main(banner_id, original_name, started): + try: + run_job(banner_id, original_name, started) + finally: + # A thread opens its own database connection; close it so it isn't + # left for the server to time out. + connection.close() + + +def _current(banner_id, original_name, started): + """The banner rows this job may still write to (empty if superseded).""" + from website.models import Banner + return Banner.objects.filter(pk=banner_id, video_original=original_name, + video_conversion_started=started) + + +def run_job(banner_id, original_name, started): + """Convert one banner's original; never raises.""" + try: + with _job_lock(): + _convert(banner_id, original_name, started) + except Exception: # a thread has no one to report to; log and move on + _logger.exception("Banner %s video conversion crashed", banner_id) + _record_failure(banner_id, original_name, started, "unexpected error (see the log)") + + +def _record_failure(banner_id, original_name, started, reason): + try: + _current(banner_id, original_name, started).update( + video_conversion_started=None, + video_conversion_error=str(reason)[:_MAX_ERROR_LENGTH]) + except Exception: + _logger.exception("Banner %s: could not record a conversion failure", banner_id) + + +def _convert(banner_id, original_name, started): + from website.models import Banner + + if not _current(banner_id, original_name, started).exists(): + _logger.info("Banner %s video job skipped: superseded before it started", banner_id) + return + + src = default_storage.path(original_name) + src_size = os.path.getsize(src) + with open(src, "rb") as handle: + demuxer = video_utils.demuxer_for_header(handle.read(64)) + if demuxer is None: + _record_failure(banner_id, original_name, started, "the file is not a video") + return + + began = time.monotonic() + workdir = tempfile.mkdtemp(prefix="banner-video-") + try: + dst = os.path.join(workdir, "out.mp4") + try: + info = video_utils.probe(src, demuxer) + result = video_utils.convert(src, dst, demuxer, info, src_size) + except (video_utils.VideoRejected, video_utils.ConversionError) as exc: + _logger.warning("Banner %s video conversion failed after %.1f s " + "(original %d bytes): %s", + banner_id, time.monotonic() - began, src_size, exc) + _record_failure(banner_id, original_name, started, exc) + return + + # Never serve a file over the cap, whatever convert() returned. + size = os.path.getsize(dst) + if size > video_utils.MAX_SERVED_BYTES: + _logger.warning("Banner %s video conversion produced %d bytes, over the cap", + banner_id, size) + _record_failure(banner_id, original_name, started, + f"the converted file was over " + f"{video_utils.MAX_SERVED_BYTES // 1_000_000} MB") + return + + target = UniquePathAndRename(Banner.VIDEO_UPLOAD_DIR, False)(None, "video.mp4") + with open(dst, "rb") as handle: + stored_name = default_storage.save(target, File(handle)) + finally: + shutil.rmtree(workdir, ignore_errors=True) + + updated = _current(banner_id, original_name, started).update( + video=stored_name, video_conversion_started=None, video_conversion_error="") + if not updated: + default_storage.delete(stored_name) + _logger.info("Banner %s video job superseded while converting; output discarded", + banner_id) + return + _logger.info("Banner %s video converted by %s in %.1f s: original %d bytes -> " + "%d bytes (maxrate %s kbit/s, %d pass(es))", + banner_id, result.mode, time.monotonic() - began, src_size, + result.size, result.maxrate_kbps, result.attempts) diff --git a/website/utils/upload_validators.py b/website/utils/upload_validators.py index 618d0d38..9fd0e1cf 100644 --- a/website/utils/upload_validators.py +++ b/website/utils/upload_validators.py @@ -207,6 +207,34 @@ def validate_video_upload(value): ) +#: Largest file stored as the served ``Banner.video`` (decimal: 10,000,000 +#: bytes). Kept equal to ``video_utils.MAX_SERVED_BYTES``; defined here too so +#: this module stays free of the ffmpeg layer. +BANNER_VIDEO_MAX_BYTES = 10_000_000 + + +def validate_banner_video_size(value): + """ + Refuse a new ``Banner.video`` over 10 MB (#1468). + + A backstop, not the main path: the banner admin form diverts every upload + to ``Banner.video_original`` and a background job converts it, so a normal + upload never reaches this. It catches the no-ffmpeg mode (where a small + upload is stored as ``video`` directly) and any other form that assigns + ``video``. Existing (committed) files are never re-checked, so legacy + oversized banners stay editable. + """ + if not _is_new_upload(value): + return + size = getattr(value, "size", None) + if size is not None and size > BANNER_VIDEO_MAX_BYTES: + raise ValidationError( + "Banner videos can be at most 10 MB as served. This file is " + f"{size / 1_000_000:.1f} MB.", + code="banner_video_too_large", + ) + + def validate_raw_file_upload(value): """ Validate a raw source file: allowlisted extension + a denylist content diff --git a/website/utils/video_utils.py b/website/utils/video_utils.py new file mode 100644 index 00000000..d2c98e0f --- /dev/null +++ b/website/utils/video_utils.py @@ -0,0 +1,467 @@ +""" +ffprobe / ffmpeg helpers for banner videos (#1468). + +An editor may upload a large banner video (up to :data:`MAX_UPLOAD_BYTES` and +:data:`MAX_DURATION_SECONDS`). The server keeps that upload as the *original* +and serves a web-ready MP4 of at most :data:`MAX_SERVED_BYTES` made from it. +This module is the media layer of that pipeline; it knows nothing about Django +models. ``website.utils.banner_video_jobs`` runs it in the background, and +``BannerAdminForm`` uses :func:`probe` and :func:`check_upload` to refuse bad +uploads before anything is stored. + +Pipeline, in short: + +1. :func:`demuxer_for_header` picks the demuxer from the file's signature + (``mov`` for ISO-BMFF, ``matroska`` for WebM). ffmpeg is never left to + auto-detect: a text playlist renamed ``.mp4`` would otherwise be opened by + the HLS demuxer, which follows the URLs inside it. +2. :func:`probe` runs ffprobe and returns a :class:`VideoInfo`. A file counts as + a video only if it has a real video stream; ffprobe exits 0 on a valid MP4 + header followed by garbage. +3. :func:`check_upload` refuses what the hero can't use: over 60 s, a frame + over 4096 px, portrait, or PQ (HDR10). HLG HDR (the iPhone default) is + tone-mapped to SDR instead. +4. :func:`convert` stream-copies a file that is already small, H.264 and + ``yuv420p``, which still strips audio and metadata such as a recorded + location; anything else gets one ``libx264`` encode with a bitrate ceiling + that follows the clip's length, plus one retry at three quarters of it if + the result is over 10 MB. + +Every command is an argv list (no shell), reads only local files +(``-protocol_whitelist file``) and runs under ``timeout`` and ``nice``, so a +hung ffmpeg ends itself even if the worker that started it is killed. + +Example:: + + from website.utils import video_utils + + demuxer = video_utils.demuxer_for_header(open(src, "rb").read(64)) + info = video_utils.probe(src, demuxer) + video_utils.check_upload(info) # raises VideoRejected + result = video_utils.convert(src, dst, demuxer, info, os.path.getsize(src)) + result.size # <= MAX_SERVED_BYTES +""" + +import json +import logging +import os +import shutil +import subprocess +import time +from dataclasses import dataclass +from fractions import Fraction + +_logger = logging.getLogger(__name__) + +# --- Limits --------------------------------------------------------------- +# Sizes are decimal (10 MB = 10,000,000 bytes), matching what editors see. + +#: Largest upload accepted. The upload must arrive inside Gunicorn's 120 s +#: worker timeout, which at 250 MB needs about 17 Mbit/s. +MAX_UPLOAD_BYTES = 250_000_000 +#: Largest file ever served as ``Banner.video``. +MAX_SERVED_BYTES = 10_000_000 +#: Longest clip accepted. +MAX_DURATION_SECONDS = 60 +#: Slack on that limit: containers report a little more than the frames span +#: (a real 60 s clip at 29.97 fps probes as 60.027 s). +DURATION_TOLERANCE_SECONDS = 0.5 +#: Largest frame side accepted (4K DCI is 4096 wide). +MAX_FRAME_SIDE = 4096 +#: The encode fits the frame inside this box and never enlarges or crops. +OUTPUT_MAX_WIDTH = 1600 +OUTPUT_MAX_HEIGHT = 900 +#: Frame rate cap; lower source rates are kept (forcing 30 on 24 fps judders). +MAX_OUTPUT_FPS = 30 +#: A stream copy is allowed only up to this frame size. +COPY_MAX_WIDTH = 1920 +COPY_MAX_HEIGHT = 1080 +#: Bitrate ceiling: min(MAXRATE_CAP_KBPS, MAXRATE_BUDGET_KBITS / duration). +#: An 8 s loop tops out near the playbook's 2.5 MB; 29 s and longer near 9 MB. +MAXRATE_CAP_KBPS = 2500 +MAXRATE_BUDGET_KBITS = 72_000 +#: The one retry runs at this fraction of the first ceiling. +RETRY_FACTOR = 0.75 +#: Wall-clock limit for one ffmpeg run, enforced by coreutils ``timeout``. +FFMPEG_TIMEOUT_SECONDS = 300 +#: If ffmpeg ignores SIGTERM at the limit, ``timeout -k`` SIGKILLs it this +#: much later, so it can't outlive its parent. +FFMPEG_KILL_AFTER_SECONDS = 10 +#: Lines of ffmpeg's stderr kept in the log when a run fails. +STDERR_TAIL_LINES = 5 +#: Limit for one ffprobe run (it takes about 0.1 s, even on 184 MB). +PROBE_TIMEOUT_SECONDS = 30 +#: A job started longer ago than this is shown as interrupted. Jobs queue on a +#: lock, so this leaves room for several ``FFMPEG_TIMEOUT_SECONDS`` runs. +STALE_JOB_MINUTES = 30 + +# color_transfer values ffprobe reports for the two HDR families. +HLG_TRANSFER = "arib-std-b67" +PQ_TRANSFER = "smpte2084" + +# HLG -> SDR (BT.709) tone mapping, applied after the downscale so it runs on +# fewer pixels. +_HLG_TONEMAP = ("zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709," + "tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv") + + +class VideoRejected(Exception): + """The upload can't be used. The message is shown to the editor.""" + + +class ConversionError(Exception): + """ffmpeg failed, timed out, or could not get the file under the cap.""" + + +@dataclass(frozen=True) +class VideoInfo: + """What :func:`probe` learned about a file's first video stream. + + ``width`` and ``height`` are as stored, before ``rotation`` (degrees, from + the display-matrix side data) is applied; use :func:`display_size`. + ``duration`` is in seconds, or None when unknown. + """ + width: int + height: int + rotation: int + duration: float | None + codec: str + pix_fmt: str | None + r_frame_rate: str | None + avg_frame_rate: str | None + color_transfer: str | None + + +@dataclass(frozen=True) +class ConversionResult: + """Outcome of :func:`convert`: ``mode`` is ``"copy"`` or ``"encode"``.""" + mode: str + size: int + maxrate_kbps: int | None + attempts: int + + +# --- Availability ---------------------------------------------------------- + + +def ffmpeg_available(): + """True if both ``ffmpeg`` and ``ffprobe`` are on PATH. + + The bind-mounted checkout can be ahead of the image during a deploy, so the + code must work without them: see ``BannerAdminForm.clean_video``. + """ + return bool(shutil.which("ffmpeg") and shutil.which("ffprobe")) + + +# --- Probing --------------------------------------------------------------- + + +def demuxer_for_header(header): + """ffmpeg demuxer name for a file's first bytes, or None if unrecognized.""" + if header[4:8] == b"ftyp": + return "mov" # ISO base media: mp4, mov, m4v + if header.startswith(b"\x1aE\xdf\xa3"): + return "matroska" # EBML: webm / mkv + return None + + +def build_probe_command(path, demuxer): + """The ffprobe argv for ``path``, with the demuxer forced.""" + return ["ffprobe", "-v", "error", "-protocol_whitelist", "file", + "-f", demuxer, "-print_format", "json", + "-show_format", "-show_streams", path] + + +def _float_or_none(value): + try: + number = float(value) + except (TypeError, ValueError): + return None + return number if number > 0 else None + + +def _rotation(stream): + """Rotation in degrees from side data (or the legacy ``rotate`` tag).""" + for side_data in stream.get("side_data_list") or []: + if "rotation" in side_data: + try: + return int(round(float(side_data["rotation"]))) + except (TypeError, ValueError): + return 0 + try: + return int((stream.get("tags") or {}).get("rotate", 0)) + except (TypeError, ValueError): + return 0 + + +def parse_probe(data): + """Build a :class:`VideoInfo` from ffprobe's JSON. + + Raises :class:`VideoRejected` when there is no real video stream (cover art + doesn't count) or it has no frame size. + """ + streams = data.get("streams") or [] + video = next( + (s for s in streams + if s.get("codec_type") == "video" + and not (s.get("disposition") or {}).get("attached_pic")), + None) + if video is None: + raise VideoRejected("This file has no video track.") + width, height = video.get("width"), video.get("height") + if not width or not height: + raise VideoRejected("This file's video track has no frame size.") + duration = (_float_or_none((data.get("format") or {}).get("duration")) + or _float_or_none(video.get("duration"))) + return VideoInfo( + width=int(width), height=int(height), rotation=_rotation(video), + duration=duration, codec=video.get("codec_name") or "", + pix_fmt=video.get("pix_fmt"), r_frame_rate=video.get("r_frame_rate"), + avg_frame_rate=video.get("avg_frame_rate"), + color_transfer=video.get("color_transfer"), + ) + + +def probe(path, demuxer): + """Run ffprobe on ``path`` and return its :class:`VideoInfo`. + + Raises :class:`VideoRejected` if ffprobe fails, times out, prints something + that isn't JSON, or finds no video stream. + """ + unreadable = "This file couldn't be read as a video." + try: + completed = subprocess.run( + build_probe_command(path, demuxer), stdin=subprocess.DEVNULL, + capture_output=True, timeout=PROBE_TIMEOUT_SECONDS) + except (subprocess.TimeoutExpired, OSError): + raise VideoRejected(unreadable) + if completed.returncode != 0: + raise VideoRejected(unreadable) + try: + data = json.loads(completed.stdout or b"") + except ValueError: + raise VideoRejected(unreadable) + return parse_probe(data) + + +# --- Checks ------------------------------------------------------------------ + + +def display_size(info): + """(width, height) as shown, after a 90 or 270 degree rotation.""" + if abs(info.rotation) % 180 == 90: + return info.height, info.width + return info.width, info.height + + +def is_portrait(info): + """True if the clip is taller than wide once its rotation is applied.""" + width, height = display_size(info) + return height > width + + +def is_hlg(info): + """True for HLG HDR (the iPhone default), which gets tone-mapped.""" + return info.color_transfer == HLG_TRANSFER + + +def check_upload(info): + """Raise :class:`VideoRejected` if the hero can't use this clip.""" + if info.duration is None: + raise VideoRejected("Couldn't read how long this clip is.") + if info.duration > MAX_DURATION_SECONDS + DURATION_TOLERANCE_SECONDS: + raise VideoRejected( + f"This clip is {info.duration:.1f} seconds long; banner videos can be " + f"at most {MAX_DURATION_SECONDS} seconds. Trim it and upload it again.") + if max(info.width, info.height) > MAX_FRAME_SIDE: + raise VideoRejected( + f"This clip's frame is {info.width}×{info.height}; the most either side " + f"can be is {MAX_FRAME_SIDE} pixels.") + if is_portrait(info): + raise VideoRejected( + "This clip is portrait (taller than wide), which can't fill the wide " + "banner without being heavily enlarged. Please upload a landscape clip.") + if info.color_transfer == PQ_TRANSFER: + raise VideoRejected( + "This clip is HDR10 (PQ), which the server can't convert. Export it as " + "SDR (or as HLG HDR) and upload it again.") + + +def can_stream_copy(info, size_bytes): + """True if the file can be served as is, after stripping audio and metadata.""" + width, height = display_size(info) + return (info.codec == "h264" + and info.pix_fmt == "yuv420p" + and not is_hlg(info) + and width <= COPY_MAX_WIDTH and height <= COPY_MAX_HEIGHT + and size_bytes <= MAX_SERVED_BYTES) + + +# --- Encoder settings ------------------------------------------------------ + + +def bitrate_ceiling_kbps(duration): + """The ``-maxrate`` in kbit/s: min(2500, 72000 / duration).""" + return int(min(MAXRATE_CAP_KBPS, MAXRATE_BUDGET_KBITS / max(duration, 1))) + + +def _fraction(text): + try: + value = Fraction(text) + except (TypeError, ValueError, ZeroDivisionError): + return None + return value if value > 0 else None + + +def output_frame_rate(r_frame_rate, avg_frame_rate): + """The ``fps`` filter value, as a string. + + Same rule as ``make_hero.sh``: use ``r_frame_rate`` when it is 60 or less, + otherwise the rounded ``avg_frame_rate`` (variable-rate phone clips report a + meaningless ``r_frame_rate``); then cap at :data:`MAX_OUTPUT_FPS`. + + >>> output_frame_rate("30000/1001", "30000/1001") + '30000/1001' + >>> output_frame_rate("90000/1", "2997/100") + '30' + """ + rate = _fraction(r_frame_rate) + if rate is None or rate > 60: + avg = _fraction(avg_frame_rate) + rate = Fraction(round(avg)) if avg is not None and round(avg) > 0 else None + if rate is None or rate > MAX_OUTPUT_FPS: + rate = Fraction(MAX_OUTPUT_FPS) + return str(rate) + + +def _ffmpeg_prefix(src, demuxer): + return ["timeout", "-k", str(FFMPEG_KILL_AFTER_SECONDS), str(FFMPEG_TIMEOUT_SECONDS), + "nice", "-n", "10", + "ffmpeg", "-v", "error", "-y", "-protocol_whitelist", "file", + "-f", demuxer, "-i", src] + + +_OUTPUT_FLAGS = ["-movflags", "+faststart", "-map_metadata", "-1", "-map_chapters", "-1"] + + +def build_copy_command(src, dst, demuxer): + """Stream copy: first video stream only, no audio, no metadata, faststart. + + ``0:V:0`` (capital V) skips attached pictures, the same rule as + :func:`parse_probe`; ``0:v:0`` can select cover art stored ahead of the + video. + """ + return [*_ffmpeg_prefix(src, demuxer), + "-map", "0:V:0", "-an", "-sn", "-dn", "-c", "copy", + *_OUTPUT_FLAGS, dst] + + +def build_encode_command(src, dst, demuxer, info, maxrate_kbps): + """One ``libx264`` pass: fit inside 1600×900, cap at 30 fps, CRF 27 with a + bitrate ceiling, ``yuv420p``, no audio, no metadata, faststart.""" + filters = [ + f"scale=w='min({OUTPUT_MAX_WIDTH},iw)':h='min({OUTPUT_MAX_HEIGHT},ih)'" + ":force_original_aspect_ratio=decrease:force_divisible_by=2", + ] + if is_hlg(info): + filters.append(_HLG_TONEMAP) + filters += ["setsar=1", + f"fps={output_frame_rate(info.r_frame_rate, info.avg_frame_rate)}", + "format=yuv420p"] + return [*_ffmpeg_prefix(src, demuxer), + "-map", "0:V:0", "-an", "-sn", "-dn", # V: not cover art, as above + "-vf", ",".join(filters), + "-c:v", "libx264", "-profile:v", "high", "-level", "4.0", + "-pix_fmt", "yuv420p", + "-crf", "27", "-maxrate", f"{maxrate_kbps}k", + "-bufsize", f"{2 * maxrate_kbps}k", "-preset", "medium", + "-g", "60", "-keyint_min", "60", "-sc_threshold", "0", "-threads", "4", + *_OUTPUT_FLAGS, dst] + + +# --- Running --------------------------------------------------------------- + + +def _stderr_tail(cmd, stderr): + """The last lines of ffmpeg's stderr, with the file paths in ``cmd`` + replaced, so the log says what went wrong without naming files.""" + text = (stderr or b"").decode("utf-8", "replace") + for arg in cmd: + if arg.startswith("/") and len(arg) > 1: + text = text.replace(arg, "") + lines = [line.strip() for line in text.splitlines() if line.strip()] + return " | ".join(lines[-STDERR_TAIL_LINES:]) + + +# 124: timeout stopped ffmpeg at the limit. 137 (128 + SIGKILL) or -9: ffmpeg +# was SIGKILLed, which is the -k kill only if the limit had been reached; +# otherwise something else killed it (the OOM killer, an operator). +_TIMED_OUT = 124 +_KILLED = {137, -9} + + +def run_ffmpeg(cmd): + """Run one ffmpeg argv (no shell). Raises :class:`ConversionError`. + + On failure the tail of ffmpeg's stderr goes to the log, paths removed; the + error itself, which the admin shows, stays short. + """ + timed_out = f"ffmpeg timed out after {FFMPEG_TIMEOUT_SECONDS} s" + began = time.monotonic() + try: + # Python's own limit stays above timeout's limit plus its -k grace, so + # timeout (not Python) ends ffmpeg; Python killing timeout first would + # leave ffmpeg running with no parent. + completed = subprocess.run( + cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + timeout=FFMPEG_TIMEOUT_SECONDS + FFMPEG_KILL_AFTER_SECONDS + 30) + except subprocess.TimeoutExpired: + raise ConversionError(timed_out) + except OSError as exc: + raise ConversionError(f"ffmpeg could not be started ({exc.strerror})") + if completed.returncode == 0: + return + _logger.warning("ffmpeg failed with status %d: %s", completed.returncode, + _stderr_tail(cmd, completed.stderr)) + elapsed = time.monotonic() - began + if completed.returncode == _TIMED_OUT or ( + completed.returncode in _KILLED and elapsed >= FFMPEG_TIMEOUT_SECONDS): + raise ConversionError(timed_out) + raise ConversionError(f"ffmpeg exited with status {completed.returncode}") + + +def _encode(src, dst, demuxer, info): + maxrate = bitrate_ceiling_kbps(info.duration or MAX_DURATION_SECONDS) + run_ffmpeg(build_encode_command(src, dst, demuxer, info, maxrate)) + size = os.path.getsize(dst) + if size <= MAX_SERVED_BYTES: + return ConversionResult("encode", size, maxrate, 1) + retry_rate = int(maxrate * RETRY_FACTOR) + _logger.info("Encode was %d bytes at %d kbit/s; retrying at %d kbit/s", + size, maxrate, retry_rate) + run_ffmpeg(build_encode_command(src, dst, demuxer, info, retry_rate)) + size = os.path.getsize(dst) + if size > MAX_SERVED_BYTES: + raise ConversionError( + f"the converted file was still {size / 1_000_000:.1f} MB, over the " + f"{MAX_SERVED_BYTES // 1_000_000} MB limit; try a shorter or calmer clip") + return ConversionResult("encode", size, retry_rate, 2) + + +def convert(src, dst, demuxer, info, src_size): + """Write a web-ready MP4 of at most :data:`MAX_SERVED_BYTES` to ``dst``. + + Stream-copies when :func:`can_stream_copy` allows it (falling back to an + encode if the copy fails), otherwise encodes. Raises + :class:`ConversionError` on failure; ``dst`` may then hold a partial file. + """ + if can_stream_copy(info, src_size): + try: + run_ffmpeg(build_copy_command(src, dst, demuxer)) + size = os.path.getsize(dst) + if size <= MAX_SERVED_BYTES: + return ConversionResult("copy", size, None, 1) + except ConversionError as exc: + _logger.info("Stream copy failed (%s); encoding instead", exc) + return _encode(src, dst, demuxer, info) diff --git a/website/views/index.py b/website/views/index.py index cc8114b5..4c549efd 100644 --- a/website/views/index.py +++ b/website/views/index.py @@ -133,13 +133,15 @@ def get_landing_page_banners(max_num_banners=5): # Exclude banners tied to a private project (#1300) so a hidden project # isn't named (with a now-404 link) in the landing carousel. Banners with # no project, or a visible project, are unaffected. - fav_banners = list(Banner.objects.filter(favorite=True, landing_page=True) + # displayable() leaves out a banner whose only media is a video still being + # converted (#1468), which would otherwise be an empty slide. + fav_banners = list(Banner.objects.displayable().filter(favorite=True, landing_page=True) .exclude(project__is_visible=False).order_by('-date_added')) random.shuffle(fav_banners) banners = fav_banners[:max_num_banners] if len(banners) < max_num_banners: - other_banners = list(Banner.objects.filter(landing_page=True) + other_banners = list(Banner.objects.displayable().filter(landing_page=True) .exclude(project__is_visible=False) .exclude(id__in=[b.id for b in banners]) # exclude banners in original list .order_by('-date_added', '?')[:max_num_banners-len(banners)]) diff --git a/website/views/project.py b/website/views/project.py index 1787f357..10d8ede1 100644 --- a/website/views/project.py +++ b/website/views/project.py @@ -65,7 +65,7 @@ def project(request, project_name): if not project.is_visible and not request.user.is_staff: raise Http404("Project is not available") - all_banners = project.banner_set.all() + all_banners = project.banner_set.displayable() # see Banner.objects.displayable (#1468) displayed_banners = ml_utils.choose_banners(all_banners) publications = (project.publication_set diff --git a/website/views/version.py b/website/views/version.py index 562ee0f5..07f6e186 100644 --- a/website/views/version.py +++ b/website/views/version.py @@ -29,7 +29,9 @@ "server": "gunicorn/23.0.0", "log_to_file": true, "log_file": "/code/media/debug.log", - "log_rotation": "ConcurrentRotatingFileHandler" + "log_rotation": "ConcurrentRotatingFileHandler", + ... + "ffmpeg": true } The ``server`` field is the WSGI server's self-reported ``SERVER_SOFTWARE`` @@ -63,6 +65,7 @@ from django.conf import settings from django.http import JsonResponse +from website.utils import video_utils from website.utils.backup_status import get_backup_status # Module logger (configured in settings.LOGGING). @@ -137,6 +140,10 @@ def version(request, format=None): ), "backup_age_hours": backup["age_hours"], "backup_count": backup["backup_count"], + # Can this server convert banner videos (#1468)? False means ffmpeg is + # missing (the checkout is ahead of the image), so banner video + # uploads over 10 MB are refused until the image is rebuilt. + "ffmpeg": video_utils.ffmpeg_available(), } response = JsonResponse(payload) response["Cache-Control"] = "no-store"