diff --git a/CLAUDE.md b/CLAUDE.md index 18a0747..5714d2d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -61,7 +61,7 @@ lib/ **Shell and navigation.** `AppShell` holds an `IndexedStack` with one nested `Navigator` per `AppTab`, with the player's `SlidingPanel` on top. The bottom `NavigationBar` collapses as the player expands, driven by `miniplayerHeightProvider`. `IndexedStack` keeps hidden tabs ticking, so `_TabTickers` turns `TickerMode` off for every tab but the shown one, and for that one too while the player is fully open (animated images and shimmers pause). `ShellLayout` (`features/shell/shell_layout.dart`, NAV-4) picks the navigation by width (`ShellNavigation.forWidth`): the bar below `kWideLayoutBreakpoint`, from there a `NavigationRail` on the left (also on phones in landscape; labels clamped to 1.3× text), extended with labels beside the icons from `kExtendedRailBreakpoint` (1240). The content sits right of the rail (which takes the side's safe area), the collapsed miniplayer at the bottom of the content above the home indicator; while expanding, the panel's left edge slides over the rail (its `MediaQuery` width is the space it has), so the expanded player covers the rail and the content never resizes. The shorts' fullscreen hides the rail like the bar. The bar shows only the tabs in `navBarConfigProvider` (`features/shell/nav_bar_config.dart`, configured in the settings, stored for all servers); `currentTabProvider` starts on the first one and falls back to it when its tab is hidden. Each `LibrarySection` (`features/library/library_page.dart`) is an `AppTab` of its own (`AppTab.section`, shown by `LibrarySectionPage`); only `LibrarySection.media` (scenes, images, galleries) are the library's text-only sub-tabs, the others are on the "You" page. A new `AppTab` needs a root page in `AppShell.rootPage` and should be hidden in `NavBarConfig.standard` (home, shorts, search, library, you). `AppTab.you` (`YouPage`, `features/you/`: shelves for history, watch later, groups and markers with "See all", then stats, performers, studios, tags, the views not in the bar, server tasks and settings; picked views open inside that tab) is `NavBarConfig.alwaysShown` and last by default; it replaced the former `all` tab, and a stored `all` becomes `you` at its place. The bar has at most `NavBarConfig.maxVisible` (5) tabs and stored bars with more are `fitted()`. The tab pages' app bars end with `ServerAvatarButton` (`features/auth/server_avatar.dart`, the active server's initial), which opens the account sheet: switch server, server tasks and settings. The settings are not a tab but a `showCupertinoSheet` over the whole app (`openSettings` in `settings_button.dart`, from the account sheet and the "You" page): closed with its X or by swiping down, with its own nested navigator, so its sub-pages push with `Navigator.of(context)`, not `openPage`. `settingsOpenProvider` tells the shorts to pause while it is open. Re-selecting the current tab (`reselectTab`) pops back to its root, or there scrolls to the top: each tab root gets its own `PrimaryScrollController` (`tabScrollControllersProvider`), so its lists must not bring a controller of their own if they should follow. To navigate, use `openPage`, `openPerformer`, `openStudio` or `openSearch` from `features/shell/navigation.dart`. They push onto the current tab's navigator and collapse the player, and they also work from inside the player, which sits outside the tab navigators. Settings open on a page of categories (`settings_page.dart`) whose sub-pages live in `settings_categories.dart`; "Remove this server" is only on the server page. `openSettings(context, ref, initialPage:)` opens the sheet with a sub-page already pushed (home's empty state opens the server tasks that way). Settings picked from a menu use `SettingsDropdownTile`, which moves the menu under the title when it would take more than half the row (large text). `test/features/text_scale_test.dart` pumps the main pages and the shell's bar/rail at 1.0×, 1.5× and 2.0× text on a 360×780 phone (plus 320×640 and a 1024×768 tablet) and fails on layout errors (A11Y-3); its `_knownOverflows` lists the ones not fixed yet. Optional tab `AppTab.subscriptions`, labelled "Favorites" (`features/subscriptions/`): favorite performers' avatars (dot = new since the last visit) and their newest scenes. `LastVisitNotifier` (`last_visit:`) is the baseline for home's "N new videos since your last visit" banner (`SceneQuery.createdAfter`); `JobFinishedListener` reports server jobs the user started once they end. Home's dice plays a random scene. Scenes are added to groups through `showAddToGroupSheet` (scene menu, player's More sheet). External links go through `openExternalUrl` (`core/utils/external_links.dart`, url_launcher; never with the API key); the description sheet has "Open in Stash" (not for the demo). -**Player.** There is a single media_kit `Player` in `playerProvider`. `nowPlayingProvider.play(scene)` opens the stream with the auth headers, starting at the resume position, and expands the panel. `PlayerPanel` is a single layout that `PlayerTransition` interpolates between the mini bar and the expanded page (video, details, "Up next") based on the panel height. The one `PlayerVideo` instance stays in place, so it is never rebuilt mid-transition. The details are built while the panel rests (collapsed or open, never mid-animation) and then kept (hidden with `Visibility(maintainState:)` while collapsed), laid out at their expanded height and reused as one widget while only the height changes, so expanding and collapsing doesn't rebuild, relayout or reload "Up next" every frame. The video area follows the video's aspect ratio (`PlayerTransition.videoAspect`; portrait videos up to `maxVideoShare` of the panel). From `PlayerTransition.splitBreakpoint` (840 dp) the expanded video takes `splitShare` (half) of the width (`columnWidth`, `expandedWidth`), with `PlayerDetails(part: info)` below it and `part: list` ("Up next" or the queue) on the right; the right `Positioned` is always in the stack so the video never moves in the tree. Phones stay portrait everywhere, the player too (4.28): `AppOrientation` (`widgets/app_orientation.dart`; `AppOrientationScope` in `MaterialApp.builder` tells it whether the window is a phone's) allows only portrait on phones, all on tablets, and the fullscreen sets its orientations through `AppOrientation.turnTo`, which waits until the window has turned (never call `SystemChrome.setPreferredOrientations` elsewhere). On a phone `PlayerVideo` listens to `heldOrientationProvider` (`held_orientation.dart`, the `stash/device_orientation` event channel: Android's `OrientationEventListener` in `MainActivity`, iOS' UIDevice orientation in `DeviceOrientationStream`; `portrait`/`turnedLeft`/`turnedRight`, physical, both respect the system's rotation lock) for as long as it lives, not only while expanded: the panel isn't expanded for a moment while the screen turns, and listening anew reported the sideways hold at once, so leaving fullscreen by its button jumped right back in. A report counts once it held for 250 ms (held at an angle, the reports flip back and forth), and not while the app is locked or away (coming back reported turns that each opened another fullscreen; `enterPlayerFullscreen` also opens only one route, `playerFullscreenOpen`). Sideways in the open player with a wide video enters fullscreen (`fullscreenByRotation`), upright leaves it, and after leaving it while sideways a new turn counts only once the phone was upright. Tablets don't enter fullscreen by turning. Fullscreen goes through `enterPlayerFullscreen`/`exitPlayerFullscreen`/`togglePlayerFullscreen` (`fullscreen_route.dart`, a copy of media_kit's route without its own transition) and `FullscreenMorph` (`fullscreen_morph.dart`, in `MaterialApp.builder`): a second `Video` of the controller moves from the player's place (`inlineVideoRect`) to the fullscreen pose, turned by `HeldOrientation.uprightAngle` in a portrait window, while the app goes black; the screen then turns underneath (both landscape sides allowed, so the system picks the held one), where the pose already matches, and the morph goes. By default (`FullscreenMorph.curtainOnly`, both platforms) the app only fades to black (`cover`/`uncover`), turns underneath and fades back in, both ways: on iOS the morph's turn still showed, and the plain fade read best. The morph (kept, tested with `curtainOnlyOverride = false`) needs a turn without the system's rotation animation, which would turn the already turned picture once more: iOS' `RunnerViewController` disables it, Android's `MainActivity` sets `ROTATION_ANIMATION_JUMPCUT` on phones (no system animation on top of the app's fade; the old frame it stretches for a moment is black). Leaving, `_onExitFullscreen` shows the pose at once (also after the system's back), turns back and moves the video home. They need a context below the `Video`, so `PlayerVideo` keeps the controls' contexts (inline and fullscreen). A portrait video's extra height covers a spacer at the top of the details and shrinks as they scroll (`PlayerTransition.extraVideoHeight`). Pinch zoom (`video_zoom.dart`) sets mpv's `video-zoom`/`video-pan-x/y`, so it applies in fullscreen too and leaves the controls alone; `NowPlayingNotifier.play` resets it for a new scene. On iOS, `RunnerViewController` (Main.storyboard) turns without UIKit's rotation animation, which stretched the video. Keep the panel's widget tree structurally stable and toggle behavior with flags. Don't pass media_kit's `NoVideoControls` to `Video`: since media_kit_video 2 it is `null`, which `Video` ignores on update, so the old controls would stay; `PlayerVideo` uses an empty builder instead. With `showControls`, `PlayerVideo` (`player_controls.dart`) wraps media_kit's `MaterialVideoControls` on both platforms, with double-tap seeking, the collapse button and the quality sheet. `sceneDetailsProvider` loads `sceneStreams`, scene markers and the file infos (`SceneFile`, shown by `FileInfoCard`) lazily per scene. Chapters appear as gaps in the controls' `PreviewSeekBar` and in `ChapterList`; there is deliberately no progress line under the expanded video. `preferredStreamProvider` stores the chosen stream label (from the HD button, or ` p` from the settings), `pickPreferredStream` matches it by format and height (the `resolution` URL parameter), and `play` only waits for the stream list when a preference is set. Playback errors: `playbackErrorProvider` counts mpv's `stream.error` only when playback hasn't moved on for 2 s (mpv also reports errors it recovers from); `_PlaybackErrorOverlay` and the mini bar offer `retry()` (`NowPlayingNotifier.reopen`) and the quality sheet. Failed casts go through `castFailureProvider` to a snack bar. Under the video, `PlayerDetails` shows title and meta (a tap opens the description sheet, `scene_description.dart`: description, tags, file info, edit scene), the channel row, one action bar (`SceneActions`: rating pill with `showRatingSheet`, O-counter pill with `showOCounterSheet` (−/+, no undo snack bar), watch later, marker, More with `showSceneMoreSheet`), performers, one line of tags (`SceneTagsRow`: as many as fit, then "+N" opening the description sheet), chapters, then Up next; sheet actions pop first and then act through the root navigator. Markers can be ranges on newer Stash (`end_seconds`): the end times come from the optional `SceneMarkerEnds`/`MarkerEnds` queries merged into the markers (a server error means unsupported and stops asking); ranges show as a tinted segment in the seek bar, "0:40–1:10" in the marker list and grid, and the add-marker sheet offers an end only when supported (`SceneDetails.markerRanges`). The list under the video is titled "Markers" (Stash has no chapters). A long press on a chapter or a markers-grid tile opens `showMarkerMenu` (`scene_actions.dart`; the grid adds play and play as loop): edit reuses `AddMarkerSheet(marker:)` and sends only changes (`StashRepository.updateMarker`, a map like the other forms; `end_seconds: null` removes the end), delete asks first (`confirmDeleteMarker`, `deleteMarker`); both reload the scene details and the marker lists. `SceneMarker`/`Marker` carry `ownTitle` and the primary `tag` for that. +**Player.** There is a single media_kit `Player` in `playerProvider`. `nowPlayingProvider.play(scene)` opens the stream with the auth headers, starting at the resume position, and expands the panel. `PlayerPanel` is a single layout that `PlayerTransition` interpolates between the mini bar and the expanded page (video, details, "Up next") based on the panel height. The one `PlayerVideo` instance stays in place, so it is never rebuilt mid-transition. The details are built while the panel rests (collapsed or open, never mid-animation) and then kept (hidden with `Visibility(maintainState:)` while collapsed), laid out at their expanded height and reused as one widget while only the height changes, so expanding and collapsing doesn't rebuild, relayout or reload "Up next" every frame. The video area follows the video's aspect ratio (`PlayerTransition.videoAspect`; portrait videos up to `maxVideoShare` of the panel). From `PlayerTransition.splitBreakpoint` (840 dp) the expanded video takes `splitShare` (half) of the width (`columnWidth`, `expandedWidth`), with `PlayerDetails(part: info)` below it and `part: list` ("Up next" or the queue) on the right; the right `Positioned` is always in the stack so the video never moves in the tree. Phones stay portrait everywhere, the player too (4.28): `AppOrientation` (`widgets/app_orientation.dart`; `AppOrientationScope` in `MaterialApp.builder` tells it whether the window is a phone's) allows only portrait on phones, all on tablets, and the fullscreen sets its orientations through `AppOrientation.turnTo`, which waits until the window has turned (never call `SystemChrome.setPreferredOrientations` elsewhere). On a phone `PlayerVideo` listens to `heldOrientationProvider` (`held_orientation.dart`, the `stash/device_orientation` event channel: Android's `OrientationEventListener` in `MainActivity`, iOS' UIDevice orientation in `DeviceOrientationStream`; `portrait`/`turnedLeft`/`turnedRight`, physical, both respect the system's rotation lock) for as long as it lives, not only while expanded: the panel isn't expanded for a moment while the screen turns, and listening anew reported the sideways hold at once, so leaving fullscreen by its button jumped right back in. A report counts once it held for 250 ms (held at an angle, the reports flip back and forth), and not while the app is locked or away (coming back reported turns that each opened another fullscreen; `enterPlayerFullscreen` also opens only one route, `playerFullscreenOpen`). Sideways in the open player with a wide video enters fullscreen (`fullscreenByRotation`), upright leaves it, and after leaving it while sideways a new turn counts only once the phone was upright. Tablets don't enter fullscreen by turning. Fullscreen goes through `enterPlayerFullscreen`/`exitPlayerFullscreen`/`togglePlayerFullscreen` (`fullscreen_route.dart`, a copy of media_kit's route without its own transition) and `FullscreenMorph` (`fullscreen_morph.dart`, in `MaterialApp.builder`): a second `Video` of the controller moves from the player's place (`inlineVideoRect`) to the fullscreen pose, turned by `HeldOrientation.uprightAngle` in a portrait window, while the app goes black; the screen then turns underneath (both landscape sides allowed, so the system picks the held one), where the pose already matches, and the morph goes. By default (`FullscreenMorph.curtainOnly`, both platforms) the app only fades to black (`cover`/`uncover`), turns underneath and fades back in, both ways: on iOS the morph's turn still showed, and the plain fade read best. The morph (kept, tested with `curtainOnlyOverride = false`) needs a turn without the system's rotation animation, which would turn the already turned picture once more: iOS' `RunnerViewController` disables it, Android's `MainActivity` sets `ROTATION_ANIMATION_JUMPCUT` on phones (no system animation on top of the app's fade; the old frame it stretches for a moment is black). Leaving, `_onExitFullscreen` shows the pose at once (also after the system's back), turns back and moves the video home. They need a context below the `Video`, so `PlayerVideo` keeps the controls' contexts (inline and fullscreen). A portrait video's extra height covers a spacer at the top of the details and shrinks as they scroll (`PlayerTransition.extraVideoHeight`). Pinch zoom (`video_zoom.dart`, 4.22/4.31) is a Flutter transform: `ZoomedVideo` (around the inline and the fullscreen `Video`) draws the video scaled 1–4× and panned, clipped to its box, and `ZoomCounter` (around the controls inside the `Video`) applies the inverse so the controls keep their size. mpv's `video-zoom` was dropped: it stays inside the video's rectangle, so the box's black bars never went. The scale grows continuously and sticks (±7 %) to 1× (the video's width or height fills the box) and to the scale where the video covers the box (`VideoZoom.coverScale`, `fill`: recomputed for every box, so it holds in fullscreen and when turning); the pan sticks to the center and the edges (`VideoZoom.panSnap`, both axes); each new snap gives a light tick (`VideoZoom.snaps`); `NowPlayingNotifier.play` resets the pinch zoom for a new scene but keeps a fill. Both widgets always build the same tree (an identity transform at no zoom), so the `Video` is never remounted. Subtitles (4.32, `captions.dart`): `SceneDetails.captions` (`captions` and `paths.caption` of `FindSceneDetails`, url `…?lang=&type=`), the top bar's subtitle button opens `showCaptionSheet`, `selectCaption` adds the file with mpv's `sub-add` (`SubtitleTrack.uri`) and `preferredCaptionProvider` (stored language) switches them on for later scenes as soon as the file's duration is known; the demo serves generated WebVTT under `/demo/caption/` (en, de). The double-tap seek feedback is a half disc (`_SeekFeedback`, `_HalfDiscClipper`) over the outer 30 % of the tapped side, its text toward the edge; it fades in with the first tap and out after the sequence (`_feedbackFading` keeps it mounted meanwhile). On iOS, `RunnerViewController` (Main.storyboard) turns without UIKit's rotation animation, which stretched the video. Keep the panel's widget tree structurally stable and toggle behavior with flags. Don't pass media_kit's `NoVideoControls` to `Video`: since media_kit_video 2 it is `null`, which `Video` ignores on update, so the old controls would stay; `PlayerVideo` uses an empty builder instead. With `showControls`, `PlayerVideo` (`player_controls.dart`) wraps media_kit's `MaterialVideoControls` on both platforms, with double-tap seeking, the collapse button and the quality sheet. `sceneDetailsProvider` loads `sceneStreams`, scene markers and the file infos (`SceneFile`, shown by `FileInfoCard`) lazily per scene. Chapters appear as gaps in the controls' `PreviewSeekBar` and in `ChapterList`; there is deliberately no progress line under the expanded video. `preferredStreamProvider` stores the chosen stream label (from the HD button, or ` p` from the settings), `pickPreferredStream` matches it by format and height (the `resolution` URL parameter), and `play` only waits for the stream list when a preference is set. Playback errors: `playbackErrorProvider` counts mpv's `stream.error` only when playback hasn't moved on for 2 s (mpv also reports errors it recovers from); `_PlaybackErrorOverlay` and the mini bar offer `retry()` (`NowPlayingNotifier.reopen`) and the quality sheet. Failed casts go through `castFailureProvider` to a snack bar. Under the video, `PlayerDetails` shows title and meta (a tap opens the description sheet, `scene_description.dart`: description, tags, file info, edit scene), the channel row, one action bar (`SceneActions`: rating pill with `showRatingSheet`, O-counter pill with `showOCounterSheet` (−/+, no undo snack bar), watch later, marker, More with `showSceneMoreSheet`), performers, one line of tags (`SceneTagsRow`: as many as fit, then "+N" opening the description sheet), chapters, then Up next; sheet actions pop first and then act through the root navigator. Markers can be ranges on newer Stash (`end_seconds`): the end times come from the optional `SceneMarkerEnds`/`MarkerEnds` queries merged into the markers (a server error means unsupported and stops asking); ranges show as a tinted segment in the seek bar, "0:40–1:10" in the marker list and grid, and the add-marker sheet offers an end only when supported (`SceneDetails.markerRanges`). The list under the video is titled "Markers" (Stash has no chapters). A long press on a chapter or a markers-grid tile opens `showMarkerMenu` (`scene_actions.dart`; the grid adds play and play as loop): edit reuses `AddMarkerSheet(marker:)` and sends only changes (`StashRepository.updateMarker`, a map like the other forms; `end_seconds: null` removes the end), delete asks first (`confirmDeleteMarker`, `deleteMarker`); both reload the scene details and the marker lists. `SceneMarker`/`Marker` carry `ownTitle` and the primary `tag` for that. **Player gestures.** The panel is our own `SlidingPanel` (`sliding_panel.dart`, replaced the unmaintained `miniplayer` package): collapsed, a tap expands it and a vertical drag follows the finger, snapping on release (`SlidingPanel.snapAfterDrag`) or dismissing below the bar; expanded, it takes no gestures, so taps belong to the video controls without a guard. media_kit's controls and the details list both claim vertical drags, so `DragToMinimize` reads raw pointer events and drives the panel through `SlidingPanelController.jumpTo`/`expand`/`collapse` (`miniplayerControllerProvider`; calls while no panel is mounted do nothing). Back while the player is open collapses it (`AppShell`'s `PopScope`). An expanded panel stays expanded when the window's height changes. That's also why the player's details have no pull-to-refresh. The player uses its own `StashVideoControls` instead of media_kit's, because media_kit's hide timer removed our seek bar mid-scrub. The controls take the fullscreen state and a toggle callback from media_kit's `VideoState`; buttons sit above the tap/double-tap gesture layer so they react without waiting for a double tap. Holding the video (`HoldDetector`, 250 ms) plays at 2× until released, and the speed button opens `showSpeedSheet` (mpv keeps the speed across files). mpv reports the position every frame, so `PreviewSeekBar` repaints its `SeekBarPainter` through a `ValueNotifier` (`progress`) and rebuilds only once a second (the spoken value). Their `PreviewSeekBar` shows sprite thumbnails (`scrubThumbnailsProvider`, parsed from Stash's WebVTT) while scrubbing. They load lazily: the controls stay mounted while hidden, so the bar reads the provider only once it is `visible` or touched, then precaches the sprite. `sceneDetailsProvider` and `scrubThumbnailsProvider` stay cached for 5 minutes without listeners (`Ref.cacheFor`), so collapsing and expanding the player doesn't refetch. On first use the controls show one-time gesture tips (`gesture_hints.dart`, `gesture_tips_seen`, resettable in Settings → Playback). In fullscreen a lock button (`TouchLockLayer`, `touch_lock.dart`) ignores all touches until its pill is held for 1 s; leaving fullscreen or a playback error unlocks. Chapters show the marker's screenshot (sprite frame as stand-in). The channel row has a favorite heart (performers; studios from Stash 0.25 through the optional `StudioFavorite` query). Channel pages put `ChannelFavoriteButton` (`FavoriteButton`, `StudioFavoriteButton`) and `ChannelRatingButton` (`features/channel/channel_rating.dart`) under the name: stars are saved through `channelRatingsProvider` (optimistic, `:`), a studio's come from the optional `StudioRating` query, and the picker is `showStarsSheet`, shared with the scenes' `showRatingSheet`. Double-tap seeking is a sequence like YouTube's: a double tap on the left/right third starts it and every further tap on that side within 700 ms extends it (5, 10, 20, 30, 40 s; `seekSequenceTotal`), counted from raw pointers so extending taps react at once; it also works while casting (tap areas over `CastingControls`) and not while locked. A tap on the other side starts a new sequence from one step; for 2 s after a seek (`_seekSettling`) a new sequence counts from the last target, since mpv (and a TV) still report the old position. Double-tap seeking is configurable per device (`seekSettingsProvider`, `seek_settings.dart`; Settings → Playback): on/off (off = single taps react without the double-tap delay), step 5/10/15/30 s, and cumulative (`SeekSettings.total`: step, then 2×step×(n−1), i.e. 5, 10, 20, 30, 40 s) or linear (one step per tap). diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index ce7cc3f..c16a0ce 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -74,7 +74,7 @@ Eine wartbare Basis, damit Features unabhängig voneinander wachsen können. | 4.19 | Als Nutzer möchte ich ein Querformat-Video durch Drehen des Handys im Vollbild sehen. | Aufgeklappter Player + Querformat-Video: Drehen ins Querformat öffnet das Vollbild, zurückdrehen beendet es (seit 4.28 über die gemeldete Haltung des Handys, mit Schwarzblende). Der Vollbild-Knopf sperrt die Ausrichtung weiter passend zum Video. iOS dreht ohne Animation, damit das Video nicht kurz verzerrt. | Next | ✅ | | 4.20 | Als Nutzer möchte ich Hochkant-Videos im Player größer sehen. | Die Videofläche folgt dem Seitenverhältnis: Hochkant-Videos bis 60 % der Bildschirmhöhe, breitere Videos bleiben 16:9. Beim Scrollen der Details schrumpft die Zusatzhöhe mit dem Finger auf 16:9. | Next | ✅ | | 4.21 | Als Nutzer möchte ich per AirPlay auf ein Apple TV streamen. | Cast-Auswahl → „AirPlay“ öffnet den System-Picker (iOS). Mit aktiver AirPlay-Route spielt ein nativer AVPlayer das Video auf dem TV (MP4/MOV direkt, sonst HLS; API-Key als `?apikey=`); die App pausiert lokal und steuert den TV wie bei Chromecast, beim Zurückwechseln aufs iPhone geht es lokal an der TV-Position weiter. Im Simulator nicht testbar. | Next | 🟡 Ungetestet auf Gerät | -| 4.22 | Als Nutzer möchte ich ins Video hineinzoomen. | Mit zwei Fingern zoomen (1–4×) und verschieben, der Punkt unter den Fingern bleibt stehen; auch im Vollbild. Der Zoom bleibt, bis man herauszoomt oder eine andere Szene startet. Gerendert von mpv (`video-zoom`/`video-pan`), die Steuerung bleibt normal groß. | Next | ✅ | +| 4.22 | Als Nutzer möchte ich ins Video hineinzoomen. | Mit zwei Fingern zoomen (1–4×) und verschieben, der Punkt unter den Fingern bleibt stehen; auch im Vollbild. Der Zoom bleibt, bis man herauszoomt oder eine andere Szene startet. Gezeichnet als Flutter-Transform des Video-Bereichs (siehe 4.31), die Steuerung bleibt normal groß. | Next | ✅ | | 4.23 | Als Nutzer möchte ich Shorts auf der Startseite sehen. | 2×2-Raster aus vier Shorts unter „Weiterschauen“. Jede Kachel hat ihre eigene, unabhängig gemischte Warteschlange: Tippen öffnet die Shorts bei diesem Short und spielt danach diese Warteschlange weiter. Keine Kachel zeigt denselben Short wie eine andere. Die Überschrift öffnet den Shorts-Tab (oder den Feed über der Startseite). | Next | ✅ | | 4.24 | Als Nutzer möchte ich Szenenmarker in den Shorts sehen, wie bei StashGifs (#42). | Shorts-Einstellungen → „Marker“: Aus (Standard), „Mit Videos“ (Videos und Marker abwechselnd) oder „Nur Marker“. Ein Marker spielt aus dem Stream der Szene in Originalauflösung, ab dem Marker bis zu seinem Ende (ohne Endzeit 20 s, höchstens bis zum Szenenende) in Schleife. Mit Tags kommen nur Marker mit einem dieser Tags (als Haupt- oder weiterer Tag), sonst zufällige Marker aller Szenen; Länge und „Nur Hochkant“ gelten für Marker nicht. Ein Marker-Short zeigt Lesezeichen-Symbol, Marker-Titel, darunter die Szene, und den Marker-Tag zuerst; „Ganzes Video“ öffnet die Szene ab dem Marker. Die Fortschrittsleiste eines Marker-Shorts umfasst nur den Ausschnitt (0:00 bis zu seiner Länge, Spulen bleibt darin; verlässt die Wiedergabe ihn doch, springt sie an den Anfang zurück); bei einem Marker mit Ende steht der Bereich in der Zeile darunter (z. B. „0:40–1:10 · 0:30“). Kacheln auf der Startseite zeigen Marker mit Lesezeichen-Abzeichen. Die Shorts eines Performers bleiben ohne Marker. | Next | ✅ (Marker jetzt als Loops, 4.27) | | 4.25 | Als Nutzer möchte ich wie bei YouTube zum vorherigen Video zurück, wenn ich im Player ein anderes Video geöffnet habe. | Ein im aufgeklappten Player gewähltes Video (z. B. aus „Up next“) merkt sich das bisherige samt Position (bis 20, jedes nur einmal). „Zurück“ (Android) bzw. ← links vom Play-Knopf der eingeblendeten Steuerung springt dorthin zurück und spielt an der gemerkten Stelle weiter, → rechts davon wieder vor (wie im Browser; ein neu gewähltes Video verwirft den Weg nach vorn). Die Pfeile erscheinen nur, wenn es etwas zum Springen gibt (die leere Seite ausgegraut); mit Warteschlange stehen dort deren Vorher/Weiter. Ohne Verlauf klappt „Zurück“ den Player ein. Videos aus Listen bei eingeklapptem Player, Wechsel innerhalb einer Warteschlange und Schließen des Players zählen nicht bzw. leeren den Verlauf. | Next | ✅ | @@ -83,3 +83,5 @@ Eine wartbare Basis, damit Features unabhängig voneinander wachsen können. | 4.28 | Als Nutzer möchte ich, dass sich auf dem Handy nur das Vollbild des Players ins Querformat dreht. | Handys (kürzeste Seite unter 600 dp) bleiben überall hochkant, auch der aufgeklappte Player. Kippen des Handys meldet das System samt Richtung (Android `OrientationEventListener`, iOS UIDevice; bei aktiver Drehsperre nicht): mit einem breiten Video im aufgeklappten Player öffnet es das Vollbild, aufrecht halten beendet es. Eine Haltung zählt erst nach 0,25 s (schräg gehalten flippte das Video sonst kurz), nicht bei gesperrter oder verlassener App, und es gibt immer nur ein Vollbild (beim Entsperren öffneten sich sonst mehrere). Nach Verlassen per Knopf im Querformat öffnet erst wieder Kippen nach einmal aufrecht halten (vorher sprang es sofort zurück ins Vollbild). Tablets drehen sich überall. | Next | 🟡 Ungetestet auf Gerät | | 4.29 | Als Nutzer möchte ich einen ruhigen Übergang ins Vollbild und Shorts, deren Knöpfe das Video wenig verdecken. | Vollbild wie bei YouTube: das Video löst sich von seinem Platz, wächst und dreht sich mit dem Handy, während die App dahinter schwarz wird; erst dann dreht sich der Bildschirm unsichtbar darunter (ohne die Dreh-Animation des Systems, die das schon gedrehte Bild noch einmal drehte; Android: harter Schnitt auf Handys, die Dreh-Animation des Systems ist aus; das kurz gestreckte alte Bild liegt unter der Schwarzblende). Verlassen (Knopf, Zurück, aufrecht halten) läuft rückwärts. Auf iOS war die Drehung trotzdem zu sehen; jetzt blendet die App auf beiden Plattformen stattdessen nach Schwarz, dreht sich darunter und blendet wieder ein (0,12 s abdunkeln, warten bis das Fenster gedreht ist und zwei Bilder gemalt sind, 0,2 s aufhellen) (der bewegte Übergang bleibt im Code abschaltbar erhalten). Per Knopf im Hochformat wächst das Video ungedreht, der Bildschirm dreht sich sichtbar. Ohne Animationen (Bedienungshilfen) springt es. Shorts: während ein Short läuft, bleiben rechts nur Performer, Bewertung und O-Zähler, oben Vollbild und Ton; Später ansehen, Ganzes Video, ⋮, Mischen und Shorts-Einstellungen gleiten beim Pausieren herein. Text unten links (Studio, Performer, Titel, Tags, Wiedergaben) und der Umschalter „Shorts \| Loops“ blenden 2 s nach jedem Wischen und nach der Rückkehr in den Tab aus und erscheinen beim Pausieren wieder. Ohne Shorts und mit Screenreader ist alles sichtbar. | Next | 🟡 Ungetestet auf Gerät | | 4.30 | Als Nutzer möchte ich Marker bearbeiten und löschen. | Langes Drücken auf einen Marker im Player (Kapitel) oder im Marker-Raster (dort auch ⋮) öffnet ein Menü: im Raster Abspielen und Als Loop abspielen, dann „Marker bearbeiten“ (dasselbe Sheet wie beim Setzen, vorausgefüllt mit Titel, Haupt-Tag und Ende; gesendet wird nur, was sich geändert hat, das Ende nur bei Servern mit Endzeiten) und „Marker löschen“ (mit Rückfrage). Kapitel, Marker-Raster und -Zähler laden danach neu. Auch in der Demo. | Next | 🟡 Ungetestet auf Gerät | +| 4.31 | Als Nutzer möchte ich, dass das Video den ganzen Bildschirm füllt, ohne schwarze Balken (GitHub #58). | Der Zwei-Finger-Zoom (4.22) wächst stufenlos mit den Fingern (1–4×) und rastet kurz bei 1× (Breite bzw. Höhe füllt den Bereich) und dort ein, wo das Video den ganzen Bereich bedeckt (±7 %, mit Haptik): keine schwarzen Balken mehr, was übersteht, wird abgeschnitten. Die Position rastet in der Mitte und an den Rändern ein (14 px, senkrecht und waagerecht). Gezeichnet als Transform des Video-Bereichs (`ZoomedVideo`), die Steuerung darin wird gegengerechnet (`ZoomCounter`) und bleibt normal groß; mpvs `video-zoom` bleibt im Rechteck des Videos und ging deshalb nicht. Das Einrasten gilt für jeden Bereich neu (Vollbild, gedrehter Bildschirm) und bleibt über andere Szenen; ein Zoom darüber wird mit der Szene zurückgesetzt. Das Doppeltipp-Feedback beim Spulen (4.11) ist eine Halbscheibe mit Kreisbogen über den äußeren 30 % der angetippten Seite, der Text zum Rand hin. | Next | 🟡 Ungetestet auf Gerät | +| 4.32 | Als Nutzer möchte ich Untertitel sehen, die Stash zur Szene hat (GitHub #57). | Hat die Szene Untertitel (`captions`, geladen über `paths.caption?lang=&type=`), erscheint oben im Player ein Untertitel-Knopf mit Auswahl (Aus oder je eine Sprache, bei mehreren Formaten mit Format). Die Wahl gilt als Sprache auch für die nächsten Szenen und wird dort eingeschaltet, sobald die Datei geladen ist, sofern es die Sprache gibt. Dargestellt von media_kit; mpv fügt die Datei per `sub-add` hinzu. Nicht für Cast. Die Demo hat Untertitel (en, de) für jede Szene. | Next | 🟡 Ungetestet auf Gerät | diff --git a/docs/RELEASE_NOTES_next.md b/docs/RELEASE_NOTES_next.md new file mode 100644 index 0000000..cb503d1 --- /dev/null +++ b/docs/RELEASE_NOTES_next.md @@ -0,0 +1,24 @@ +# StashTube 1.0.0-beta.8 + +Pre-release. The pipeline picks the version (next beta after `v1.0.0-beta.7`). + +## What's new + +- **Subtitles** – pick the captions your Stash has for a video from the new button in the player's top bar. The language is remembered for the next videos. The built-in demo has English and German subtitles to try it. +- **Zoom without black bars** – spread two fingers to fill the whole screen. The zoom grows continuously (up to 4×) and snaps at the fitted size and at full width/height, the position snaps to the center and the edges, each with a light haptic tick. Works inline, in fullscreen and after turning the phone. +- **Double tap to skip** – a half disc over the tapped side (like YouTube) with the total jump, fading in and out. +- **Playback** – videos can buffer fully before playing, position and picture are kept when you return to the app, the position is saved at once, a countdown runs before the next video of a queue, and the current frame can be saved. +- **Feedback and bugs** – Settings → About opens the GitHub issue forms. + +## Fixes and internals + +- CI: generated l10n files regenerated with the CI's Flutter version (the generated-files check failed on `develop`). +- The pinch zoom is drawn by Flutter instead of mpv (`video-zoom` stays inside the video's rectangle); the controls keep their size. + +## Issues + +Closes #57 (subtitles) and #58 (zoom/crop). + +## Not tested on a device yet + +Pinch snapping and haptics (inline, fullscreen, turning), the skip half disc, subtitles on a real server, buffering and the queue countdown. diff --git a/lib/core/api/documents/scenes.graphql b/lib/core/api/documents/scenes.graphql index ff67189..e2673c4 100644 --- a/lib/core/api/documents/scenes.graphql +++ b/lib/core/api/documents/scenes.graphql @@ -56,7 +56,8 @@ query FindScenesByIds($ids: [ID!]) { query FindSceneDetails($id: ID!) { findScene(id: $id) { id - paths { sprite vtt } + paths { sprite vtt caption } + captions { language_code caption_type } sceneStreams { url mime_type label } scene_markers { ...MarkerFields } files { path size format width height duration video_codec audio_codec frame_rate bit_rate mod_time } diff --git a/lib/core/api/documents/scenes.graphql.dart b/lib/core/api/documents/scenes.graphql.dart index 3710c60..13dd0e7 100644 --- a/lib/core/api/documents/scenes.graphql.dart +++ b/lib/core/api/documents/scenes.graphql.dart @@ -2905,6 +2905,44 @@ const documentNodeQueryFindSceneDetails = DocumentNode( directives: [], selectionSet: null, ), + FieldNode( + name: NameNode(value: 'caption'), + alias: null, + arguments: [], + directives: [], + selectionSet: null, + ), + FieldNode( + name: NameNode(value: '__typename'), + alias: null, + arguments: [], + directives: [], + selectionSet: null, + ), + ], + ), + ), + FieldNode( + name: NameNode(value: 'captions'), + alias: null, + arguments: [], + directives: [], + selectionSet: SelectionSetNode( + selections: [ + FieldNode( + name: NameNode(value: 'language_code'), + alias: null, + arguments: [], + directives: [], + selectionSet: null, + ), + FieldNode( + name: NameNode(value: 'caption_type'), + alias: null, + arguments: [], + directives: [], + selectionSet: null, + ), FieldNode( name: NameNode(value: '__typename'), alias: null, @@ -3232,6 +3270,7 @@ class Query$FindSceneDetails$findScene { Query$FindSceneDetails$findScene({ required this.id, required this.paths, + this.captions, required this.sceneStreams, required this.scene_markers, required this.files, @@ -3241,6 +3280,7 @@ class Query$FindSceneDetails$findScene { factory Query$FindSceneDetails$findScene.fromJson(Map json) { final l$id = json['id']; final l$paths = json['paths']; + final l$captions = json['captions']; final l$sceneStreams = json['sceneStreams']; final l$scene_markers = json['scene_markers']; final l$files = json['files']; @@ -3250,6 +3290,13 @@ class Query$FindSceneDetails$findScene { paths: Query$FindSceneDetails$findScene$paths.fromJson( (l$paths as Map), ), + captions: (l$captions as List?) + ?.map( + (e) => Query$FindSceneDetails$findScene$captions.fromJson( + (e as Map), + ), + ) + .toList(), sceneStreams: (l$sceneStreams as List) .map( (e) => Query$FindSceneDetails$findScene$sceneStreams.fromJson( @@ -3277,6 +3324,8 @@ class Query$FindSceneDetails$findScene { final Query$FindSceneDetails$findScene$paths paths; + final List? captions; + final List sceneStreams; final List scene_markers; @@ -3291,6 +3340,8 @@ class Query$FindSceneDetails$findScene { _resultData['id'] = l$id; final l$paths = paths; _resultData['paths'] = l$paths.toJson(); + final l$captions = captions; + _resultData['captions'] = l$captions?.map((e) => e.toJson()).toList(); final l$sceneStreams = sceneStreams; _resultData['sceneStreams'] = l$sceneStreams .map((e) => e.toJson()) @@ -3310,6 +3361,7 @@ class Query$FindSceneDetails$findScene { int get hashCode { final l$id = id; final l$paths = paths; + final l$captions = captions; final l$sceneStreams = sceneStreams; final l$scene_markers = scene_markers; final l$files = files; @@ -3317,6 +3369,7 @@ class Query$FindSceneDetails$findScene { return Object.hashAll([ l$id, l$paths, + l$captions == null ? null : Object.hashAll(l$captions.map((v) => v)), Object.hashAll(l$sceneStreams.map((v) => v)), Object.hashAll(l$scene_markers.map((v) => v)), Object.hashAll(l$files.map((v) => v)), @@ -3343,6 +3396,22 @@ class Query$FindSceneDetails$findScene { if (l$paths != lOther$paths) { return false; } + final l$captions = captions; + final lOther$captions = other.captions; + if (l$captions != null && lOther$captions != null) { + if (l$captions.length != lOther$captions.length) { + return false; + } + for (int i = 0; i < l$captions.length; i++) { + final l$captions$entry = l$captions[i]; + final lOther$captions$entry = lOther$captions[i]; + if (l$captions$entry != lOther$captions$entry) { + return false; + } + } + } else if (l$captions != lOther$captions) { + return false; + } final l$sceneStreams = sceneStreams; final lOther$sceneStreams = other.sceneStreams; if (l$sceneStreams.length != lOther$sceneStreams.length) { @@ -3392,6 +3461,7 @@ class Query$FindSceneDetails$findScene$paths { Query$FindSceneDetails$findScene$paths({ this.sprite, this.vtt, + this.caption, this.$__typename = 'ScenePathsType', }); @@ -3400,10 +3470,12 @@ class Query$FindSceneDetails$findScene$paths { ) { final l$sprite = json['sprite']; final l$vtt = json['vtt']; + final l$caption = json['caption']; final l$$__typename = json['__typename']; return Query$FindSceneDetails$findScene$paths( sprite: (l$sprite as String?), vtt: (l$vtt as String?), + caption: (l$caption as String?), $__typename: (l$$__typename as String), ); } @@ -3412,6 +3484,8 @@ class Query$FindSceneDetails$findScene$paths { final String? vtt; + final String? caption; + final String $__typename; Map toJson() { @@ -3420,6 +3494,8 @@ class Query$FindSceneDetails$findScene$paths { _resultData['sprite'] = l$sprite; final l$vtt = vtt; _resultData['vtt'] = l$vtt; + final l$caption = caption; + _resultData['caption'] = l$caption; final l$$__typename = $__typename; _resultData['__typename'] = l$$__typename; return _resultData; @@ -3429,8 +3505,9 @@ class Query$FindSceneDetails$findScene$paths { int get hashCode { final l$sprite = sprite; final l$vtt = vtt; + final l$caption = caption; final l$$__typename = $__typename; - return Object.hashAll([l$sprite, l$vtt, l$$__typename]); + return Object.hashAll([l$sprite, l$vtt, l$caption, l$$__typename]); } @override @@ -3452,6 +3529,84 @@ class Query$FindSceneDetails$findScene$paths { if (l$vtt != lOther$vtt) { return false; } + final l$caption = caption; + final lOther$caption = other.caption; + if (l$caption != lOther$caption) { + return false; + } + final l$$__typename = $__typename; + final lOther$$__typename = other.$__typename; + if (l$$__typename != lOther$$__typename) { + return false; + } + return true; + } +} + +class Query$FindSceneDetails$findScene$captions { + Query$FindSceneDetails$findScene$captions({ + required this.language_code, + required this.caption_type, + this.$__typename = 'VideoCaption', + }); + + factory Query$FindSceneDetails$findScene$captions.fromJson( + Map json, + ) { + final l$language_code = json['language_code']; + final l$caption_type = json['caption_type']; + final l$$__typename = json['__typename']; + return Query$FindSceneDetails$findScene$captions( + language_code: (l$language_code as String), + caption_type: (l$caption_type as String), + $__typename: (l$$__typename as String), + ); + } + + final String language_code; + + final String caption_type; + + final String $__typename; + + Map toJson() { + final _resultData = {}; + final l$language_code = language_code; + _resultData['language_code'] = l$language_code; + final l$caption_type = caption_type; + _resultData['caption_type'] = l$caption_type; + final l$$__typename = $__typename; + _resultData['__typename'] = l$$__typename; + return _resultData; + } + + @override + int get hashCode { + final l$language_code = language_code; + final l$caption_type = caption_type; + final l$$__typename = $__typename; + return Object.hashAll([l$language_code, l$caption_type, l$$__typename]); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other is! Query$FindSceneDetails$findScene$captions || + runtimeType != other.runtimeType) { + return false; + } + final l$language_code = language_code; + final lOther$language_code = other.language_code; + if (l$language_code != lOther$language_code) { + return false; + } + final l$caption_type = caption_type; + final lOther$caption_type = other.caption_type; + if (l$caption_type != lOther$caption_type) { + return false; + } final l$$__typename = $__typename; final lOther$$__typename = other.$__typename; if (l$$__typename != lOther$$__typename) { diff --git a/lib/data/models/scene_details.dart b/lib/data/models/scene_details.dart index 3b18da5..cfe9ba4 100644 --- a/lib/data/models/scene_details.dart +++ b/lib/data/models/scene_details.dart @@ -190,6 +190,38 @@ class SceneFile { String get name => path.split(RegExp(r'[/\\]')).last; } +/// A subtitle file Stash has for a scene (`captions`), served by +/// `paths.caption?lang=…&type=…` as WebVTT. +class SceneCaption { + const SceneCaption({required this.languageCode, required this.type, required this.url}); + + /// ISO 639 code as Stash stores it; "00" (or empty) = language unknown. + final String languageCode; + + /// The file's format ("srt", "vtt"). + final String type; + final String url; + + bool get languageKnown => languageCode.isNotEmpty && languageCode != '00'; + + /// Identifies the caption within its scene. + String get id => '$languageCode:$type'; + + static SceneCaption? build(String? base, String languageCode, String type) { + final root = nonEmpty(base); + final uri = root == null ? null : Uri.tryParse(root); + if (uri == null) return null; + final url = uri.replace(queryParameters: {...uri.queryParameters, 'lang': languageCode, 'type': type}); + return SceneCaption(languageCode: languageCode, type: type, url: url.toString()); + } + + @override + bool operator ==(Object other) => other is SceneCaption && other.url == url; + + @override + int get hashCode => url.hashCode; +} + /// Per-scene data that is only needed while the scene is playing. class SceneDetails { const SceneDetails({ @@ -199,10 +231,14 @@ class SceneDetails { this.spriteUrl, this.vttUrl, this.markerRanges = false, + this.captions = const [], }); final List streams; + /// Subtitles the server has for the scene. + final List captions; + /// The scene's files; the first is the one that plays. final List files; @@ -224,6 +260,7 @@ class SceneDetails { ? this : SceneDetails( streams: streams, + captions: captions, files: files, spriteUrl: spriteUrl, vttUrl: vttUrl, @@ -234,6 +271,10 @@ class SceneDetails { factory SceneDetails.fromGraphql(Query$FindSceneDetails$findScene s) => SceneDetails( spriteUrl: nonEmpty(s.paths.sprite), vttUrl: nonEmpty(s.paths.vtt), + captions: [ + for (final c in s.captions ?? const []) + ?SceneCaption.build(s.paths.caption, c.language_code, c.caption_type), + ], streams: [ for (final stream in s.sceneStreams) if (stream.url.isNotEmpty) SceneStream.fromGraphql(stream), diff --git a/lib/features/demo/demo_library.dart b/lib/features/demo/demo_library.dart index 0cbd1b3..079597f 100644 --- a/lib/features/demo/demo_library.dart +++ b/lib/features/demo/demo_library.dart @@ -263,6 +263,30 @@ class DemoLibrary { return out.toString(); } + /// The demo's subtitles: a line every few seconds in English and German + /// (served by the demo server at `/demo/caption/?lang=`). + static const captionLanguages = ['en', 'de']; + + String? captionVtt(String file, String lang) { + final clip = media.clips[file]; + if (clip == null || !captionLanguages.contains(lang)) return null; + String time(double s) { + final ms = (s * 1000).round(); + String two(int n) => n.toString().padLeft(2, '0'); + return '00:${two(ms ~/ 60000)}:${two(ms % 60000 ~/ 1000)}.${(ms % 1000).toString().padLeft(3, '0')}'; + } + + final out = StringBuffer('WEBVTT\n'); + const step = 4.0; + for (var i = 0; i * step < clip.duration; i++) { + final start = i * step; + final end = (start + step - 0.5).clamp(0, clip.duration).toDouble(); + final text = lang == 'de' ? 'Untertitel ${i + 1}: Das ist eine Demo.' : 'Subtitle ${i + 1}: this is a demo.'; + out.write('\n${time(start)} --> ${time(end)}\n$text\n'); + } + return out.toString(); + } + // --- Objects -------------------------------------------------------------- Map _studioObject(_Studio s) => { @@ -363,7 +387,11 @@ class DemoLibrary { 'stream': stream, 'sprite': _media('sprites/${s.file}.jpg'), 'vtt': _media('vtt/${s.file}.vtt'), + 'caption': _media('caption/${s.file}'), }, + 'captions': [ + for (final lang in captionLanguages) {'__typename': 'VideoCaption', 'language_code': lang, 'caption_type': 'vtt'}, + ], 'sceneStreams': [ {'__typename': 'SceneStreamEndpoint', 'url': stream, 'mime_type': 'video/mp4', 'label': 'Direct stream'}, ], diff --git a/lib/features/demo/demo_server.dart b/lib/features/demo/demo_server.dart index 5145f44..c440841 100644 --- a/lib/features/demo/demo_server.dart +++ b/lib/features/demo/demo_server.dart @@ -69,6 +69,11 @@ class DemoHandler { if (vtt == null) return const DemoResponse(HttpStatus.notFound); return DemoResponse(HttpStatus.ok, body: utf8.encode(vtt), contentType: type); } + if (file.startsWith('caption/')) { + final vtt = library.captionVtt(file.substring('caption/'.length), uri.queryParameters['lang'] ?? 'en'); + if (vtt == null) return const DemoResponse(HttpStatus.notFound); + return DemoResponse(HttpStatus.ok, body: utf8.encode(vtt), contentType: _types['vtt']); + } final bytes = await (_files[file] ??= _load(file)); if (bytes == null) return const DemoResponse(HttpStatus.notFound); return _ranged(bytes, type, range); diff --git a/lib/features/player/captions.dart b/lib/features/player/captions.dart new file mode 100644 index 0000000..b5f3447 --- /dev/null +++ b/lib/features/player/captions.dart @@ -0,0 +1,103 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../core/config/server_config.dart'; +import '../../data/models/scene_details.dart'; +import '../../data/providers.dart'; +import '../../l10n/l10n.dart'; +import 'player_providers.dart'; + +/// The subtitle language to switch on again for the next scenes (the ISO +/// code of the caption picked last); null = subtitles off. +class PreferredCaptionNotifier extends Notifier { + static const _key = 'caption_language'; + + @override + String? build() => ref.watch(sharedPreferencesProvider).getString(_key); + + Future set(String? language) async { + state = language; + final prefs = ref.read(sharedPreferencesProvider); + if (language == null) { + await prefs.remove(_key); + } else { + await prefs.setString(_key, language); + } + } +} + +final preferredCaptionProvider = NotifierProvider(PreferredCaptionNotifier.new); + +/// The subtitles showing on the current scene; null = none. +class ActiveCaptionNotifier extends Notifier { + @override + SceneCaption? build() => null; + + void set(SceneCaption? caption) => state = caption; +} + +final activeCaptionProvider = NotifierProvider(ActiveCaptionNotifier.new); + +/// Whether the scene has subtitles to pick from (decides if the button shows). +final hasCaptionsProvider = Provider.autoDispose.family( + (ref, sceneId) => ref.watch(sceneDetailsProvider(sceneId).select((d) => d.value?.captions.isNotEmpty ?? false)), +); + +/// "JA", or "JA · SRT" when the scene has the language in several formats; +/// "Unknown language" for Stash's "00". +String captionLabel(BuildContext context, SceneCaption caption, {bool withType = false}) { + final language = caption.languageKnown ? caption.languageCode.toUpperCase() : context.l10n.captionUnknownLanguage; + return withType ? '$language · ${caption.type.toUpperCase()}' : language; +} + +/// Bottom sheet to switch the subtitles of [sceneId] on or off. +Future showCaptionSheet(BuildContext context, String sceneId) => showModalBottomSheet( + context: context, + useRootNavigator: true, + showDragHandle: true, + isScrollControlled: true, + builder: (_) => _CaptionSheet(sceneId: sceneId), + ); + +class _CaptionSheet extends ConsumerWidget { + const _CaptionSheet({required this.sceneId}); + + final String sceneId; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final captions = ref.watch(sceneDetailsProvider(sceneId)).value?.captions ?? const []; + final active = ref.watch(activeCaptionProvider); + final languages = {for (final c in captions) c.languageCode}; + void pick(SceneCaption? caption) { + Navigator.pop(context); + ref.read(nowPlayingProvider.notifier).selectCaption(caption); + } + + return SafeArea( + child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(context).height * 0.6), + child: ListView( + shrinkWrap: true, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text(context.l10n.subtitles, style: Theme.of(context).textTheme.titleMedium), + ), + ListTile( + leading: Icon(active == null ? Icons.check : null), + title: Text(context.l10n.subtitlesOff), + onTap: () => pick(null), + ), + for (final caption in captions) + ListTile( + leading: Icon(caption == active ? Icons.check : null), + title: Text(captionLabel(context, caption, withType: languages.length < captions.length)), + onTap: () => pick(caption), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/player/fullscreen_route.dart b/lib/features/player/fullscreen_route.dart index cde8e96..29895d0 100644 --- a/lib/features/player/fullscreen_route.dart +++ b/lib/features/player/fullscreen_route.dart @@ -3,6 +3,7 @@ import 'package:media_kit_video/media_kit_video.dart'; import 'fullscreen_morph.dart'; import 'held_orientation.dart'; +import 'video_zoom.dart'; /// Like media_kit's [toggleFullscreen], with [enterPlayerFullscreen] and /// [exitPlayerFullscreen]. [context] is below the [Video] (its controls'). @@ -79,7 +80,8 @@ Future enterPlayerFullscreen(BuildContext context, {HeldOrientation? held, contextNotifier: inherited.contextNotifier, videoViewParametersNotifier: inherited.videoViewParametersNotifier, disposeNotifiers: false, - child: Video( + child: ZoomedVideo( + child: Video( controller: controller, fit: parameters.fit, fill: parameters.fill, @@ -95,6 +97,7 @@ Future enterPlayerFullscreen(BuildContext context, {HeldOrientation? held, focusNode: parameters.focusNode, onEnterFullscreen: state.widget.onEnterFullscreen, onExitFullscreen: state.widget.onExitFullscreen, + ), ), ), ), diff --git a/lib/features/player/player_controls.dart b/lib/features/player/player_controls.dart index 3fdebfe..982e8f1 100644 --- a/lib/features/player/player_controls.dart +++ b/lib/features/player/player_controls.dart @@ -24,6 +24,7 @@ import 'fullscreen_morph.dart'; import 'fullscreen_route.dart'; import 'held_orientation.dart'; import 'player_providers.dart'; +import 'video_zoom.dart'; import 'preview_seek_bar.dart'; import 'scene_actions.dart' show showMarkerMenu; import 'video_controls.dart'; @@ -208,7 +209,8 @@ class _PlayerVideoState extends ConsumerState { @override Widget build(BuildContext context) { final scene = widget.scene; - return Video( + return ZoomedVideo( + child: Video( key: playerVideoKey, controller: ref.watch(videoControllerProvider), // backgroundPlaybackProvider decides (4.12): keep the sound, or pause. @@ -230,17 +232,19 @@ class _PlayerVideoState extends ConsumerState { } else { _controlsContext = controlsContext; } - return StashVideoControls( - fullscreen: fullscreen, - onToggleFullscreen: () => - togglePlayerFullscreen(controlsContext, held: _buttonHeld, inline: inlineVideoRect), - scene: scene, - onQuality: () => showQualitySheet(context, scene.id), + return ZoomCounter( + child: StashVideoControls( + fullscreen: fullscreen, + onToggleFullscreen: () => + togglePlayerFullscreen(controlsContext, held: _buttonHeld, inline: inlineVideoRect), + scene: scene, + onQuality: () => showQualitySheet(context, scene.id), + ), ); }, ) : _noControls, - ); + )); } } diff --git a/lib/features/player/player_providers.dart b/lib/features/player/player_providers.dart index f22b711..2c68727 100644 --- a/lib/features/player/player_providers.dart +++ b/lib/features/player/player_providers.dart @@ -15,6 +15,7 @@ import '../cast/cast_media.dart'; import '../cast/cast_providers.dart'; import '../cast/cast_service.dart' show CastKind; import '../pip/pip.dart' show playbackModesProvider; +import 'captions.dart'; import 'playback_tracker.dart'; import 'sliding_panel.dart'; import 'video_zoom.dart'; @@ -434,11 +435,13 @@ class NowPlayingNotifier extends Notifier { ref.read(playerClosingProvider.notifier).set(false); if (state?.id != scene.id) { // A zoom belongs to its video; mpv would keep it for the next file. - ref.read(videoZoomProvider.notifier).reset(); + ref.read(videoZoomProvider.notifier).resetZoom(); // Prefer the position saved in this session over the (possibly stale) list data. final resume = at ?? ref.read(resumeTimesProvider)[scene.id] ?? scene.resumeTime; unawaited(ref.read(playbackTrackerProvider).start(scene.copyWith(resumeTime: resume))); ref.read(currentStreamProvider.notifier).set(null); + ref.read(activeCaptionProvider.notifier).set(null); + _restoreCaption(scene); final start = Duration(milliseconds: (resume * 1000).round()); unawaited(_openPreferredStream(scene, url, start)); if (ref.read(isCastingProvider)) unawaited(_castScene(scene, start)); @@ -450,6 +453,59 @@ class NowPlayingNotifier extends Notifier { WidgetsBinding.instance.addPostFrameCallback((_) => expand()); } + Future? _pendingCaption; + StreamSubscription? _captionWatch; + + /// Switches the subtitles on again for [scene] if the user's last pick has + /// a file in their language: as soon as the file is loaded (mpv can only + /// add subtitles to a loaded file), and only if this scene still plays. + void _restoreCaption(Scene scene) { + final language = ref.read(preferredCaptionProvider); + if (language == null) { + _pendingCaption = null; + return; + } + _pendingCaption = () async { + final details = ref.listen(sceneDetailsProvider(scene.id).future, (_, _) {}); + try { + final captions = (await details.read()).captions; + if (state?.id != scene.id) return null; + return captions.where((c) => c.languageCode == language).firstOrNull; + } catch (_) { + return null; // subtitles are optional + } finally { + details.close(); + } + }(); + if (_captionWatch != null) return; + _captionWatch = ref.read(playerProvider).stream.duration.listen((duration) async { + final pending = _pendingCaption; + if (duration <= Duration.zero || pending == null) return; + _pendingCaption = null; + final caption = await pending; + if (caption != null && ref.mounted && state != null) await _showCaption(caption); + }); + ref.onDispose(() => _captionWatch?.cancel()); + } + + Future _showCaption(SceneCaption? caption) async { + await ref.read(playerProvider).setSubtitleTrack( + caption == null + ? SubtitleTrack.no() + : SubtitleTrack.uri(caption.url, language: caption.languageCode, title: caption.type), + ); + if (ref.mounted) ref.read(activeCaptionProvider.notifier).set(caption); + } + + /// Switches the subtitles of the current scene ([caption] null: off) and + /// remembers the language for the next scenes. + Future selectCaption(SceneCaption? caption) async { + if (state == null) return; + _pendingCaption = null; + await _showCaption(caption); + if (ref.mounted) await ref.read(preferredCaptionProvider.notifier).set(caption?.languageCode); + } + /// Opens the user's preferred transcode if this scene offers it, else the /// direct file. Only waits for the stream list when a preference is set. Future _openPreferredStream(Scene scene, String directUrl, Duration start) async { @@ -633,6 +689,8 @@ class NowPlayingNotifier extends Notifier { _autoplay = null; unawaited(ref.read(playbackTrackerProvider).stop()); ref.read(videoZoomProvider.notifier).reset(); + _pendingCaption = null; + ref.read(activeCaptionProvider.notifier).set(null); ref.read(playerProvider).stop(); state = null; } diff --git a/lib/features/player/player_view.dart b/lib/features/player/player_view.dart index 13503e6..329c3cc 100644 --- a/lib/features/player/player_view.dart +++ b/lib/features/player/player_view.dart @@ -23,25 +23,10 @@ import 'player_providers.dart'; import 'player_transition.dart'; import 'scene_actions.dart'; import 'scene_description.dart'; +import 'video_zoom.dart'; import 'scene_tags_row.dart'; import '../../l10n/l10n.dart'; -/// Width / height of [scene]'s video, updated once the player knows the -/// decoded size. -final _videoAspectProvider = Provider.autoDispose.family((ref, scene) { - final player = ref.watch(playerProvider); - final subscriptions = [ - player.stream.width.listen((_) => ref.invalidateSelf()), - player.stream.height.listen((_) => ref.invalidateSelf()), - ]; - ref.onDispose(() { - for (final s in subscriptions) { - s.cancel(); - } - }); - return videoAspect(player.state, scene, sceneFirst: true); -}); - /// Content of the miniplayer panel: one layout that [PlayerTransition] /// morphs continuously from the collapsed bar into the full player page. /// @@ -134,7 +119,7 @@ class _PlayerPanelState extends ConsumerState { screenWidth: media.size.width, topInset: media.padding.top, // Portrait videos get a taller video area (4.20). - videoAspect: ref.watch(_videoAspectProvider(scene)) ?? 16 / 9, + videoAspect: ref.watch(sceneVideoAspectProvider(scene)) ?? 16 / 9, expandedWidth: columnWidth, ); diff --git a/lib/features/player/video_controls.dart b/lib/features/player/video_controls.dart index 1a5e6a3..774af2e 100644 --- a/lib/features/player/video_controls.dart +++ b/lib/features/player/video_controls.dart @@ -17,6 +17,7 @@ import '../../widgets/play_pause_icon.dart'; import '../cast/cast_providers.dart'; import '../cast/cast_ui.dart'; import '../pip/pip.dart'; +import 'captions.dart'; import 'gesture_hints.dart'; import 'player_controls.dart' show playerVideoKey; import 'player_providers.dart'; @@ -137,12 +138,18 @@ class _StashVideoControlsState extends ConsumerState { final start = _pinchStartZoom; final box = context.size; if (start == null || _pointers.length < 2 || box == null) return; - ref.read(videoZoomProvider.notifier).set(start.pinch( - factor: _distance / _pinchStartDistance, - startFocal: _pinchStartFocal, - focal: _focal, - box: box, - )); + final notifier = ref.read(videoZoomProvider.notifier); + final was = ref.read(videoZoomProvider); + final zoom = start.pinch( + factor: _distance / _pinchStartDistance, + startFocal: _pinchStartFocal, + focal: _focal, + box: box, + aspect: ref.read(videoAspectProvider), + ); + // A light tick whenever it newly sticks: to a size or the center/edges. + if (zoom.snaps & ~was.snaps != 0) Haptics.selection(); + notifier.set(zoom); } void _onPointerEnd(PointerEvent e) { @@ -183,6 +190,10 @@ class _StashVideoControlsState extends ConsumerState { /// [_seekTaps] taps jump [_seekTotal] ([SeekSettings.total]) from /// [_seekBase], the position when it started. int _seekDirection = 0; + + /// The side the feedback fades out on after the sequence ended. + int _shownDirection = 1; + bool _feedbackFading = false; int _seekTaps = 0; Duration _seekTotal = Duration.zero; Duration _seekBase = Duration.zero; @@ -366,6 +377,8 @@ class _StashVideoControlsState extends ConsumerState { ? ref.read(castPlaybackProvider).value?.position ?? Duration.zero : ref.read(playerProvider).state.position; _seekDirection = direction; + _shownDirection = direction; + _feedbackFading = false; _seekTaps = 0; _lastSeekTarget = null; _extendSeekSequence(); @@ -409,22 +422,46 @@ class _StashVideoControlsState extends ConsumerState { void _endSeekSequence() { _seekTimer?.cancel(); if (_seekDirection == 0) return; - if (mounted) setState(() => _seekDirection = 0); + if (mounted) { + final animate = !MediaQuery.disableAnimationsOf(context); + setState(() { + _seekDirection = 0; + _feedbackFading = animate; + }); + } } - /// The bubble of the running seek sequence, on its side. - Widget _seekFeedback() => IgnorePointer( - child: ExcludeSemantics( + /// The half disc of the running seek sequence, on its side; it fades in + /// with the first tap and out after the last. + Widget _seekFeedback() { + final showing = _seekDirection != 0; + final direction = showing ? _seekDirection : _shownDirection; + final animate = !MediaQuery.disableAnimationsOf(context); + return IgnorePointer( + child: ExcludeSemantics( + child: TweenAnimationBuilder( + tween: Tween(begin: animate ? 0 : 1, end: showing ? 1 : 0), + duration: animate ? const Duration(milliseconds: 180) : Duration.zero, + onEnd: () { + if (mounted && _seekDirection == 0 && _feedbackFading) setState(() => _feedbackFading = false); + }, + builder: (_, opacity, child) => Opacity(opacity: opacity, child: child), child: Align( - alignment: _seekDirection < 0 ? const Alignment(-0.6, 0) : const Alignment(0.6, 0), - child: _SeekFeedback( - forward: _seekDirection > 0, - seconds: _seekTotal.inSeconds, - taps: _seekTaps, + alignment: direction < 0 ? Alignment.centerLeft : Alignment.centerRight, + child: FractionallySizedBox( + widthFactor: _SeekFeedback.widthFactor, + heightFactor: 1, + child: _SeekFeedback( + forward: direction > 0, + seconds: _seekTotal.inSeconds, + taps: _seekTaps, + ), ), ), ), - ); + ), + ); + } /// While casting: tap areas left and right of [CastingControls]' buttons, /// so double taps seek on the TV as well. @@ -491,7 +528,7 @@ class _StashVideoControlsState extends ConsumerState { children: [ CastingControls(connection: casting, showMinimize: !fullscreen), if (seek.enabled) _castSeekZones(), - if (_seekDirection != 0) _seekFeedback(), + if (_seekDirection != 0 || _feedbackFading) _seekFeedback(), ], ); } @@ -543,7 +580,7 @@ class _StashVideoControlsState extends ConsumerState { ), ), ), - if (_seekDirection != 0) _seekFeedback(), + if (_seekDirection != 0 || _feedbackFading) _seekFeedback(), if (_rateBeforeHold != null) IgnorePointer( child: Align( @@ -612,6 +649,16 @@ class _StashVideoControlsState extends ConsumerState { ), ), ), + if (ref.watch(hasCaptionsProvider(widget.scene.id))) + IconButton( + tooltip: context.l10n.subtitles, + icon: Icon( + ref.watch(activeCaptionProvider) == null + ? Icons.closed_caption_outlined + : Icons.closed_caption, + ), + onPressed: () => _act(() => showCaptionSheet(context, widget.scene.id)), + ), IconButton( tooltip: context.l10n.quality, icon: const Icon(Icons.hd_outlined), @@ -915,11 +962,16 @@ class _TimeLabel extends StatelessWidget { ); } -/// The bubble of a seek sequence: the total jump, with a ripple and arrows -/// that run again on every tap ([taps]); still with reduced motion. +/// The feedback of a seek sequence, like YouTube's: a half disc that covers +/// the side that was tapped, with the total jump and arrows that run again +/// on every tap ([taps]); still with reduced motion. Fills the space it is +/// given (the controls give it the outer 30 % of their width). class _SeekFeedback extends StatelessWidget { const _SeekFeedback({required this.forward, required this.seconds, required this.taps}); + /// The share of the video's width it covers, from the tapped edge. + static const widthFactor = 0.3; + final bool forward; final int seconds; final int taps; @@ -938,52 +990,70 @@ class _SeekFeedback extends StatelessWidget { final lit = animate ? (1 - ((t * 3) - i - 0.5).abs()).clamp(0.0, 1.0) : 1.0; return Opacity( opacity: 0.35 + 0.65 * lit, - child: const Icon(Icons.play_arrow, color: Colors.white, size: 18), + child: const Icon(Icons.play_arrow, color: Colors.white, size: 28), ); } final arrows = [for (var i = 0; i < 3; i++) arrow(i)]; - return Stack( - alignment: Alignment.center, - children: [ - if (animate) - Opacity( - opacity: (1 - t) * 0.6, - child: Transform.scale( - scale: 1 + t * 0.6, - child: DecoratedBox( - decoration: BoxDecoration(color: scrim, shape: BoxShape.circle), - child: const SizedBox.square(dimension: 96), + return ClipPath( + clipper: _HalfDiscClipper(onLeft: !forward), + child: ColoredBox( + // A tap flashes the disc a little brighter, which fades out. + color: Color.alphaBlend(Colors.white.withValues(alpha: animate ? (1 - t) * 0.12 : 0), scrim), + // Toward the outer edge, away from the middle of the video. + child: Align( + alignment: Alignment(forward ? 0.3 : -0.3, 0), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Back: the arrows point left and run right to left. + Transform.flip( + flipX: !forward, + child: Row(mainAxisSize: MainAxisSize.min, children: arrows), ), - ), - ), - DecoratedBox( - decoration: BoxDecoration(color: scrim, shape: BoxShape.circle), - child: Padding( - padding: const EdgeInsets.all(AppSpacing.l), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Back: the arrows point left and run right to left. - Transform.flip( - flipX: !forward, - child: Row(mainAxisSize: MainAxisSize.min, children: arrows), - ), - Text( - context.l10n.durationSeconds(seconds), - style: const TextStyle(color: Colors.white, fontSize: AppTextSize.overlayLabel), - ), - ], - ), + const SizedBox(height: AppSpacing.xs), + Text( + context.l10n.durationSeconds(seconds), + style: const TextStyle(color: Colors.white, fontSize: AppTextSize.overlayBody), + ), + ], ), ), - ], + ), ); }, ); } } +/// The seek feedback's shape: the outer edge of the box, a circular arc +/// for the inner one that meets the top and bottom 25 % in and bulges to the +/// full width in the middle. +class _HalfDiscClipper extends CustomClipper { + const _HalfDiscClipper({required this.onLeft}); + + final bool onLeft; + + @override + Path getClip(Size size) { + final w = size.width; + final h = size.height; + final sagitta = w * 0.25; + final radius = (h * h / 4 + sagitta * sagitta) / (2 * sagitta); + // Mirrored for the right side: x' = w - x. + double x(double v) => onLeft ? v : w - v; + return Path() + ..moveTo(x(0), 0) + ..lineTo(x(w - sagitta), 0) + ..arcToPoint(Offset(x(w - sagitta), h), radius: Radius.circular(radius), clockwise: onLeft) + ..lineTo(x(0), h) + ..close(); + } + + @override + bool shouldReclip(_HalfDiscClipper old) => old.onLeft != onLeft; +} + /// Playback speeds offered in [showSpeedSheet]. const playbackSpeeds = [0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0]; diff --git a/lib/features/player/video_zoom.dart b/lib/features/player/video_zoom.dart index bf3208d..9fca3b9 100644 --- a/lib/features/player/video_zoom.dart +++ b/lib/features/player/video_zoom.dart @@ -1,19 +1,21 @@ import 'dart:math' as math; -import 'dart:ui'; -import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:media_kit/media_kit.dart'; +import '../../data/models/scene.dart'; +import 'player_controls.dart' show videoAspect; import 'player_providers.dart'; -/// Pinch zoom of the player's video (4.22): a scale plus a pan, both -/// relative to the video, so it looks the same in the small player and in -/// fullscreen. Rendered by mpv (`video-zoom`, `video-pan-x/y`), so the -/// controls on top keep their size. +/// Pinch zoom of the player's video (4.22, 4.31): a scale plus a pan, drawn +/// by [ZoomedVideo] as a transform of the video's box. The video grows +/// continuously from "fits inside" (1×) up to 4× and snaps briefly where it +/// fills the whole box ([fill]: no black bars, whatever the box is), like +/// YouTube's. The controls inside the box are counter-transformed +/// ([ZoomCounter]) so they keep their size. @immutable class VideoZoom { - const VideoZoom({this.scale = 1, this.panX = 0, this.panY = 0}); + const VideoZoom({this.scale = 1, this.panX = 0, this.panY = 0, this.fill = false, this.snaps = 0}); static const none = VideoZoom(); static const maxScale = 4.0; @@ -21,69 +23,206 @@ class VideoZoom { /// Below this a pinch snaps back to no zoom. static const snapBack = 1.05; + /// A pinch within this share of the fit scale (1: the video's height or + /// width fills the box) or the fill scale (both do) sticks to it. + static const fillSnap = 0.07; + + /// The pan sticks to the center and to the edges within this many pixels. + static const panSnap = 14.0; + final double scale; - /// Shift of the video in fractions of its scaled size (mpv's unit). + /// Shift of the video in fractions of the box. final double panX; final double panY; - bool get isZoomed => scale > 1; + /// At the scale where the video covers the whole box (worked out again + /// for every box: inline, fullscreen, turned screen). + final bool fill; + + /// What a pinch just stuck to, for a haptic tick when something new does + /// ([snapScale], [snapPanX], [snapPanY]); not part of the zoom itself. + final int snaps; + static const snapScale = 1; + static const snapPanX = 2; + static const snapPanY = 4; + + bool get isZoomed => scale > 1 || fill; + + /// The scale at which a video of [aspect] (width / height) covers [box]. + static double coverScale(Size box, double? aspect) { + if (aspect == null || aspect <= 0 || box.isEmpty) return 1; + final boxAspect = box.width / box.height; + return math.min(maxScale, boxAspect > aspect ? boxAspect / aspect : aspect / boxAspect); + } + + /// The scale shown in [box]. + double scaleIn(Size box, double? aspect) => fill ? math.max(1, coverScale(box, aspect)) : scale; + + /// How far the video, fitted into [box], may be moved at [scale] before + /// the box shows empty space (none while it is smaller than the box). + static Offset panLimit(Size box, double? aspect, double scale) { + final boxAspect = box.width / box.height; + final fitted = aspect == null || aspect <= 0 + ? box + : (boxAspect > aspect ? Size(box.height * aspect, box.height) : Size(box.width, box.width / aspect)); + return Offset( + math.max(0, (fitted.width * scale - box.width) / 2), + math.max(0, (fitted.height * scale - box.height) / 2), + ); + } + + /// The transform that draws the zoomed video in a box of [box]. + Matrix4 matrixIn(Size box, double? aspect) { + final s = scaleIn(box, aspect); + final limit = panLimit(box, aspect, s); + final center = box.center(Offset.zero); + final dx = (panX * box.width * s).clamp(-limit.dx, limit.dx); + final dy = (panY * box.height * s).clamp(-limit.dy, limit.dy); + return Matrix4.identity() + ..translateByDouble(center.dx + dx, center.dy + dy, 0, 1) + ..scaleByDouble(s, s, 1, 1) + ..translateByDouble(-center.dx, -center.dy, 0, 1); + } /// The zoom after a pinch that started at [startFocal] with this zoom and /// is now at [focal] with the fingers [factor] times as far apart, in a - /// video box of [box]. The point under the fingers stays under them, and - /// the video always covers the box. - VideoZoom pinch({required double factor, required Offset startFocal, required Offset focal, required Size box}) { + /// video box of [box]. The point under the fingers stays under them; near + /// the scale that fills the box it sticks to it. + VideoZoom pinch({ + required double factor, + required Offset startFocal, + required Offset focal, + required Size box, + double? aspect, + }) { final center = box.center(Offset.zero); - final newScale = (scale * factor).clamp(1.0, maxScale); - // Pan as a translation of the video's center, in box pixels. - final start = Offset(panX * box.width * scale, panY * box.height * scale); + final startScale = scaleIn(box, aspect); + final cover = coverScale(box, aspect); + final raw = (startScale * factor).clamp(1.0, maxScale); + final snapped = cover > 1.02 && (raw - cover).abs() <= cover * fillSnap; + final snappedFit = !snapped && raw <= 1 + fillSnap && raw > 1; + final newScale = snapped ? cover : (raw <= 1 + fillSnap ? 1.0 : raw); + final startLimit = panLimit(box, aspect, startScale); + final start = Offset( + (panX * box.width * startScale).clamp(-startLimit.dx, startLimit.dx), + (panY * box.height * startScale).clamp(-startLimit.dy, startLimit.dy), + ); // The video point under the fingers when the pinch started... - final point = (startFocal - center - start) / scale; + final point = (startFocal - center - start) / startScale; // ...is moved to where the fingers are now. final translation = focal - center - point * newScale; - final maxX = box.width * (newScale - 1) / 2; - final maxY = box.height * (newScale - 1) / 2; + final limit = panLimit(box, aspect, newScale); + final (px, snapX) = _snapPan(translation.dx, limit.dx); + final (py, snapY) = _snapPan(translation.dy, limit.dy); return VideoZoom( scale: newScale, - panX: translation.dx.clamp(-maxX, maxX) / (box.width * newScale), - panY: translation.dy.clamp(-maxY, maxY) / (box.height * newScale), + panX: px / (box.width * newScale), + panY: py / (box.height * newScale), + fill: snapped, + snaps: (snapped || snappedFit ? snapScale : 0) | (snapX ? snapPanX : 0) | (snapY ? snapPanY : 0), ); } + /// [value] kept within ±[limit], sticking to the center and to the edges + /// (and whether it sticks, with a limit to stick to at all). + static (double, bool) _snapPan(double value, double limit) { + final v = value.clamp(-limit, limit); + if (limit <= 0) return (0, false); + if (v.abs() <= panSnap) return (0, true); + if ((v - limit).abs() <= panSnap) return (limit, true); + if ((v + limit).abs() <= panSnap) return (-limit, true); + return (v, false); + } + /// What a pinch ends with: no zoom when barely zoomed. - VideoZoom settled() => scale < snapBack ? none : this; + VideoZoom settled() => scale < snapBack && !fill ? none : this; @override bool operator ==(Object other) => - other is VideoZoom && other.scale == scale && other.panX == panX && other.panY == panY; + other is VideoZoom && other.scale == scale && other.panX == panX && other.panY == panY && other.fill == fill; @override - int get hashCode => Object.hash(scale, panX, panY); + int get hashCode => Object.hash(scale, panX, panY, fill); } /// The current zoom; kept until the user zooms out or another scene starts -/// (`NowPlayingNotifier.play` resets it, as mpv keeps it across files). +/// (`NowPlayingNotifier.play` resets the pinch zoom, the fill stays). class VideoZoomNotifier extends Notifier { @override VideoZoom build() => VideoZoom.none; void set(VideoZoom zoom) { - if (zoom == state) return; - state = zoom; - _apply(ref.read(playerProvider), zoom); + if (zoom != state) state = zoom; } void reset() => set(VideoZoom.none); - static void _apply(Player player, VideoZoom zoom) { - final platform = player.platform; - if (platform is! NativePlayer) return; - // mpv's zoom is a power of two. - platform.setProperty('video-zoom', '${math.log(zoom.scale) / math.ln2}'); - platform.setProperty('video-pan-x', '${zoom.panX}'); - platform.setProperty('video-pan-y', '${zoom.panY}'); - } + /// Another scene: no pinch zoom, but a fill stays. + void resetZoom() => set(state.fill ? const VideoZoom(fill: true) : VideoZoom.none); } final videoZoomProvider = NotifierProvider(VideoZoomNotifier.new); + +/// Width / height of the playing video, updated once the player knows the +/// decoded size; null without a scene. +final videoAspectProvider = Provider.autoDispose((ref) { + final scene = ref.watch(nowPlayingProvider); + if (scene == null) return null; + return _aspectOf(ref, scene); +}); + +/// The same for a given [scene]. +final sceneVideoAspectProvider = Provider.autoDispose.family(_aspectOf); + +double? _aspectOf(Ref ref, Scene scene) { + final player = ref.watch(playerProvider); + final subscriptions = [ + player.stream.width.listen((_) => ref.invalidateSelf()), + player.stream.height.listen((_) => ref.invalidateSelf()), + ]; + ref.onDispose(() { + for (final s in subscriptions) { + s.cancel(); + } + }); + return videoAspect(player.state, scene, sceneFirst: true); +} + +/// Draws [child] (the `Video`) zoomed by [videoZoomProvider], clipped to +/// its box. +class ZoomedVideo extends ConsumerWidget { + const ZoomedVideo({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final zoom = ref.watch(videoZoomProvider); + final aspect = ref.watch(videoAspectProvider); + return LayoutBuilder( + // Always the same widgets, so the Video underneath is never rebuilt + // from scratch when a zoom starts or ends. + builder: (context, constraints) => + ClipRect(child: Transform(transform: zoom.matrixIn(constraints.biggest, aspect), child: child)), + ); + } +} + +/// Inside a [ZoomedVideo]'s `Video`: undoes the zoom for the controls, so +/// they keep their size and place. +class ZoomCounter extends ConsumerWidget { + const ZoomCounter({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final zoom = ref.watch(videoZoomProvider); + final aspect = ref.watch(videoAspectProvider); + return LayoutBuilder( + builder: (context, constraints) => + Transform(transform: Matrix4.inverted(zoom.matrixIn(constraints.biggest, aspect)), child: child), + ); + } +} diff --git a/lib/features/whats_new/whats_new.dart b/lib/features/whats_new/whats_new.dart index 6264efe..076dc49 100644 --- a/lib/features/whats_new/whats_new.dart +++ b/lib/features/whats_new/whats_new.dart @@ -18,6 +18,19 @@ typedef ChangelogItem = ({IconData icon, String text}); /// its texts in both ARB files, one change per line, the most relevant /// first, and an icon per line. List changelog(AppLocalizations l) => [ + ( + id: 2, + title: l.whatsNew2Title, + items: _items(l.whatsNew2, const [ + Icons.closed_caption_outlined, // subtitles + Icons.zoom_out_map, // zoom without black bars + Icons.fast_forward_outlined, // skip feedback + Icons.downloading_outlined, // buffering + Icons.timer_outlined, // countdown + Icons.photo_camera_outlined, // save frame + ]), + more: const [], + ), ( id: 1, title: l.whatsNew1Title, diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index dd00d8f..3b00349 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -406,6 +406,9 @@ "later": "Später", "exitFullscreen": "Vollbild beenden", "fullscreen": "Vollbild", + "subtitles": "Untertitel", + "subtitlesOff": "Aus", + "captionUnknownLanguage": "Unbekannte Sprache", "clearField": "Leeren", "searchStudios": "Studios suchen", "searchPerformers": "Performer suchen", @@ -745,6 +748,8 @@ "whatsNewTitle": "Neu in StashTube", "whatsNewDone": "Verstanden", "whatsNewSubtitle": "Was die letzten Updates gebracht haben", + "whatsNew2Title": "Untertitel, Zoom ohne schwarze Balken und mehr", + "whatsNew2": "Untertitel: Wähle die Untertitel, die dein Stash zu einem Video hat; die Sprache gilt auch für die nächsten.\nMit zwei Fingern auf den ganzen Bildschirm ziehen, ohne schwarze Balken; es rastet bei voller Breite und in der Mitte ein, mit leichtem Tick.\nDoppeltippen zum Spulen zeigt eine Halbscheibe über der angetippten Seite, die ein- und ausblendet.\nVideos können vor dem Abspielen ganz puffern und behalten Position und Bild, wenn du in die App zurückkommst.\nEin Countdown, bevor das nächste Video der Warteschlange startet.\nDas aktuelle Bild als Foto speichern.", "whatsNew1Title": "Loops, eine neue Player-Seite und mehr", "whatsNew1": "Neue Navigation: Start · Shorts · Suche · Bibliothek · Du.\nLoops: Szenenmarker, die sich von selbst wiederholen. Umschalten oben im Shorts-Tab.\nNeue Player-Seite: Bewertung, O-Zähler, Später ansehen, Marker und Mehr in einer Leiste.\nSuchvorschläge schon beim Tippen.\nDoppeltippen zum Spulen summiert sich wie bei YouTube: 5, 10, 20, 30 Sekunden …\nZurück und vor zwischen geöffneten Videos, mit Pfeilen neben Play.\nDarsteller- und Studioseiten mit Tabs: Videos, Shorts, Marker, Bilder, Galerien, Info.\nFavoriten: die neuesten Videos deiner Lieblingsdarsteller.", "whatsNew1More": "Der Du-Tab bündelt Verlauf, Später ansehen, Gruppen und Marker.\nSchrittweite und Zählung beim Spulen unter Einstellungen → Wiedergabe.\nSterne und Favoriten für Darsteller und Studios.\nDarsteller, Studios und Gruppen anlegen.\n„Ganzes Video“ aus einem Short spielt dort weiter, wo das Short war.\nAuf dem Tablet steht das Video neben „Als Nächstes“.\nBild-im-Bild öffnet im Format des Videos.\nServer-Aufgaben: Scannen, Generieren, Auto-Tag und Aufräumen.\nEine Prüfung fehlender Vorschauen.\nEine Benachrichtigung, wenn eine Server-Aufgabe fertig ist (optional).\nMarker mit Start und Ende bei neueren Stash-Versionen.\n„Neu seit deinem letzten Besuch“ auf der Startseite.\nVerständliche Wiedergabefehler mit „Erneut versuchen“ und „Qualität wechseln“.\nEin Hinweis, wenn der Server nicht erreichbar ist; geladene Listen bleiben.\nEinfacherer Login: Zugangsdaten erst, wenn der Server sie verlangt.\nBilddetails hinter dem (i)-Knopf; nach unten wischen schließt ein Bild.\nDer Würfel auf der Startseite spielt eine zufällige Szene.\nDie Sehzeit als Diagramm in der Statistik.\nEine Touch-Sperre im Vollbild.\nAuf dem Handy bleibt die App hochkant; Kippen mit einem breiten Video dreht es ins Vollbild.\nWährend ein Short läuft, zeigt er nur die wichtigsten Knöpfe und blendet seinen Text aus; Pausieren zeigt den Rest.\nMarker per langem Drücken bearbeiten oder löschen.\nHochkant-Szenen erscheinen ganz in den Vorschaubildern, oder gefüllt (Einstellungen).\nEine Einführung in die App (Einstellungen → Über).\nEinstellungen nach Kategorien geordnet.\nFeedback und Fehler direkt aus Einstellungen → Über.", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 6cdafb5..d5bcf43 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -967,6 +967,9 @@ "later": "Later", "exitFullscreen": "Exit fullscreen", "fullscreen": "Fullscreen", + "subtitles": "Subtitles", + "subtitlesOff": "Off", + "captionUnknownLanguage": "Unknown language", "clearField": "Clear", "searchStudios": "Search studios", "searchPerformers": "Search performers", @@ -1535,6 +1538,8 @@ "whatsNewTitle": "What's new", "whatsNewDone": "Got it", "whatsNewSubtitle": "What the latest updates brought", + "whatsNew2Title": "Subtitles, zoom without black bars and more", + "whatsNew2": "Subtitles: pick the captions your Stash has for a video; the language is remembered for the next ones.\nPinch to fill the whole screen without black bars; it snaps at full width and in the center, with a light tick.\nDouble tap to skip shows a half disc over the tapped side that fades in and out.\nVideos can buffer fully before they play, and keep position and picture when you come back to the app.\nA countdown before the next video of a queue starts.\nSave the current frame as an image.", "whatsNew1Title": "Loops, a new watch page and more", "whatsNew1": "New navigation: Home · Shorts · Search · Library · You.\nLoops: scene markers that repeat on their own. Switch at the top of the Shorts tab.\nA new watch page: rating, O-counter, watch later, marker and more in one bar.\nSearch suggestions while you type.\nDouble tap to skip adds up like on YouTube: 5, 10, 20, 30 seconds …\nBack and forward between the videos you opened, with arrows beside play.\nPerformer and studio pages with tabs: videos, shorts, markers, images, galleries, about.\nFavorites: the newest videos of your favorite performers.", "whatsNew1More": "The You tab gathers history, watch later, groups and markers.\nSkip step and counting can be set in Settings → Playback.\nStars and favorites for performers and studios.\nCreate performers, studios and groups.\n\"Full video\" from a short continues where the short was.\nOn tablets the video sits beside \"Up next\".\nPicture-in-picture opens in the video's shape.\nServer tasks: scan, generate, auto tag and clean.\nA check for missing previews.\nA notification when a server task finishes (optional).\nMarkers with a start and an end on newer Stash versions.\n\"New since your last visit\" on the home page.\nClear playback errors with \"Try again\" and \"Change quality\".\nA banner when the server can't be reached; loaded lists stay.\nA simpler login: credentials only when the server asks for them.\nImage details behind the (i) button; swipe down to close an image.\nThe dice on the home page plays a random scene.\nWatch time as a chart in the stats.\nA touch lock in fullscreen.\nOn phones the app stays upright; tilting the phone with a wide video turns it into fullscreen.\nWhile a short plays, only its main buttons show and its text fades out; pause for the rest.\nEdit or delete markers with a long press.\nPortrait scenes show whole in thumbnails, or filled (settings).\nA tour of the app (Settings → About).\nSettings sorted into categories.\nFeedback and bugs straight from Settings → About.", diff --git a/lib/l10n/gen/app_localizations.dart b/lib/l10n/gen/app_localizations.dart index 66f9f1e..4cb81d4 100644 --- a/lib/l10n/gen/app_localizations.dart +++ b/lib/l10n/gen/app_localizations.dart @@ -2354,6 +2354,24 @@ abstract class AppLocalizations { /// **'Fullscreen'** String get fullscreen; + /// No description provided for @subtitles. + /// + /// In en, this message translates to: + /// **'Subtitles'** + String get subtitles; + + /// No description provided for @subtitlesOff. + /// + /// In en, this message translates to: + /// **'Off'** + String get subtitlesOff; + + /// No description provided for @captionUnknownLanguage. + /// + /// In en, this message translates to: + /// **'Unknown language'** + String get captionUnknownLanguage; + /// No description provided for @clearField. /// /// In en, this message translates to: @@ -4358,6 +4376,18 @@ abstract class AppLocalizations { /// **'What the latest updates brought'** String get whatsNewSubtitle; + /// No description provided for @whatsNew2Title. + /// + /// In en, this message translates to: + /// **'Subtitles, zoom without black bars and more'** + String get whatsNew2Title; + + /// No description provided for @whatsNew2. + /// + /// In en, this message translates to: + /// **'Subtitles: pick the captions your Stash has for a video; the language is remembered for the next ones.\nPinch to fill the whole screen without black bars; it snaps at full width and in the center, with a light tick.\nDouble tap to skip shows a half disc over the tapped side that fades in and out.\nVideos can buffer fully before they play, and keep position and picture when you come back to the app.\nA countdown before the next video of a queue starts.\nSave the current frame as an image.'** + String get whatsNew2; + /// No description provided for @whatsNew1Title. /// /// In en, this message translates to: diff --git a/lib/l10n/gen/app_localizations_de.dart b/lib/l10n/gen/app_localizations_de.dart index 3058e61..f99349a 100644 --- a/lib/l10n/gen/app_localizations_de.dart +++ b/lib/l10n/gen/app_localizations_de.dart @@ -1,6 +1,5 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; - import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1501,6 +1500,15 @@ class AppLocalizationsDe extends AppLocalizations { @override String get fullscreen => 'Vollbild'; + @override + String get subtitles => 'Untertitel'; + + @override + String get subtitlesOff => 'Aus'; + + @override + String get captionUnknownLanguage => 'Unbekannte Sprache'; + @override String get clearField => 'Leeren'; @@ -2643,6 +2651,13 @@ class AppLocalizationsDe extends AppLocalizations { @override String get whatsNewSubtitle => 'Was die letzten Updates gebracht haben'; + @override + String get whatsNew2Title => 'Untertitel, Zoom ohne schwarze Balken und mehr'; + + @override + String get whatsNew2 => + 'Untertitel: Wähle die Untertitel, die dein Stash zu einem Video hat; die Sprache gilt auch für die nächsten.\nMit zwei Fingern auf den ganzen Bildschirm ziehen, ohne schwarze Balken; es rastet bei voller Breite und in der Mitte ein, mit leichtem Tick.\nDoppeltippen zum Spulen zeigt eine Halbscheibe über der angetippten Seite, die ein- und ausblendet.\nVideos können vor dem Abspielen ganz puffern und behalten Position und Bild, wenn du in die App zurückkommst.\nEin Countdown, bevor das nächste Video der Warteschlange startet.\nDas aktuelle Bild als Foto speichern.'; + @override String get whatsNew1Title => 'Loops, eine neue Player-Seite und mehr'; diff --git a/lib/l10n/gen/app_localizations_en.dart b/lib/l10n/gen/app_localizations_en.dart index fe7d89a..36d5fa7 100644 --- a/lib/l10n/gen/app_localizations_en.dart +++ b/lib/l10n/gen/app_localizations_en.dart @@ -1,6 +1,5 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; - import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1497,6 +1496,15 @@ class AppLocalizationsEn extends AppLocalizations { @override String get fullscreen => 'Fullscreen'; + @override + String get subtitles => 'Subtitles'; + + @override + String get subtitlesOff => 'Off'; + + @override + String get captionUnknownLanguage => 'Unknown language'; + @override String get clearField => 'Clear'; @@ -2632,6 +2640,13 @@ class AppLocalizationsEn extends AppLocalizations { @override String get whatsNewSubtitle => 'What the latest updates brought'; + @override + String get whatsNew2Title => 'Subtitles, zoom without black bars and more'; + + @override + String get whatsNew2 => + 'Subtitles: pick the captions your Stash has for a video; the language is remembered for the next ones.\nPinch to fill the whole screen without black bars; it snaps at full width and in the center, with a light tick.\nDouble tap to skip shows a half disc over the tapped side that fades in and out.\nVideos can buffer fully before they play, and keep position and picture when you come back to the app.\nA countdown before the next video of a queue starts.\nSave the current frame as an image.'; + @override String get whatsNew1Title => 'Loops, a new watch page and more'; diff --git a/test/data/scene_caption_test.dart b/test/data/scene_caption_test.dart new file mode 100644 index 0000000..64a092e --- /dev/null +++ b/test/data/scene_caption_test.dart @@ -0,0 +1,20 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stash_app_mobile/data/models/scene_details.dart'; + +void main() { + test('a caption url adds language and type to the server path', () { + final c = SceneCaption.build('http://s:9999/scene/7/caption', 'ja', 'srt')!; + expect(Uri.parse(c.url).path, '/scene/7/caption'); + expect(Uri.parse(c.url).queryParameters, {'lang': 'ja', 'type': 'srt'}); + expect(c.id, 'ja:srt'); + expect(c.languageKnown, isTrue); + }); + + test('keeps existing query parameters, and no path means no caption', () { + final c = SceneCaption.build('http://s/scene/7/caption?x=1', '00', 'vtt')!; + expect(Uri.parse(c.url).queryParameters, {'x': '1', 'lang': '00', 'type': 'vtt'}); + expect(c.languageKnown, isFalse); + expect(SceneCaption.build(null, 'ja', 'srt'), isNull); + expect(SceneCaption.build('', 'ja', 'srt'), isNull); + }); +} diff --git a/test/features/demo_test.dart b/test/features/demo_test.dart index 3e05ad0..5b01bdb 100644 --- a/test/features/demo_test.dart +++ b/test/features/demo_test.dart @@ -364,6 +364,17 @@ void main() { expect((await repo.findGroup('1')).sceneCount, filmCount - 1); }); + test('scenes have subtitles in two languages that the server serves', () async { + final details = await repo.findSceneDetails('1'); + expect(details.captions.map((c) => c.languageCode), ['en', 'de']); + final response = await handler.handle('GET', Uri.parse(details.captions.last.url)); + expect(response.status, HttpStatus.ok); + final text = utf8.decode(response.body!); + expect(text, startsWith('WEBVTT')); + expect(text, contains('Untertitel 1')); + expect((await handler.handle('GET', Uri.parse('${ServerConfig.demoUrl}/demo/caption/none?lang=en'))).status, 404); + }); + test('media with byte ranges, for the player', () async { final uri = Uri.parse('${ServerConfig.demoUrl}/demo/scenes/riverside.mp4'); final whole = await handler.handle('GET', uri); diff --git a/test/features/player/seek_sequence_test.dart b/test/features/player/seek_sequence_test.dart index 3b36582..00c251e 100644 --- a/test/features/player/seek_sequence_test.dart +++ b/test/features/player/seek_sequence_test.dart @@ -110,10 +110,8 @@ void main() { bool controlsVisible(WidgetTester tester) => tester.widget(find.byType(AnimatedOpacity).last).opacity == 1; - // The bubble and, while it animates, the ripple behind it. - Finder circles() => find.byWidgetPredicate( - (w) => w is DecoratedBox && w.decoration is BoxDecoration && (w.decoration as BoxDecoration).shape == BoxShape.circle, - ); + // The half disc over the tapped side. + Finder halfDisc() => find.byWidgetPredicate((w) => w is ClipPath && w.clipper.runtimeType.toString() == '_HalfDiscClipper'); Rect area(WidgetTester tester) => tester.getRect(find.byType(StashVideoControls)); Offset right(WidgetTester tester) => Offset(area(tester).right - 20, area(tester).center.dy); @@ -149,7 +147,9 @@ void main() { expect(player.seeks, isEmpty, reason: 'a single tap does not seek'); await tap(tester, right(tester)); expect(find.text('5 seconds'), findsOneWidget); - expect(circles(), findsNWidgets(2), reason: 'the bubble and its ripple'); + expect(halfDisc(), findsOneWidget); + expect(tester.getSize(halfDisc()).width, closeTo(area(tester).width * 0.3, 1), reason: 'covers the outer 30 % of the video'); + expect(tester.getTopLeft(halfDisc()).dx, closeTo(area(tester).right - area(tester).width * 0.3, 1), reason: 'on the tapped side'); for (var i = 0; i < 4; i++) { await tap(tester, right(tester)); } @@ -158,7 +158,10 @@ void main() { expect(controlsVisible(tester), isFalse, reason: 'the taps of a sequence do not toggle the controls'); await tester.pump(StashVideoControls.seekSequenceWindow); - expect(find.text('40 seconds'), findsNothing, reason: 'the bubble goes after the last tap'); + expect(find.text('40 seconds'), findsOneWidget, reason: 'it fades out first'); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(const Duration(milliseconds: 200)); + expect(find.text('40 seconds'), findsNothing, reason: 'the half disc goes after the last tap'); expect(controlsVisible(tester), isFalse); }); @@ -223,6 +226,7 @@ void main() { await tap(tester, right(tester)); await tap(tester, right(tester)); await tap(tester, middle(tester)); + await tester.pump(const Duration(milliseconds: 300)); // fades out expect(find.text('5 seconds'), findsNothing); await tester.pump(kDoubleTapTimeout); expect(controlsVisible(tester), isTrue); @@ -260,12 +264,12 @@ void main() { await tester.pump(StashVideoControls.seekSequenceWindow); }); - testWidgets('with reduced motion the bubble shows without the ripple', (tester) async { + testWidgets('with reduced motion the half disc shows too', (tester) async { await pump(tester, reduceMotion: true); await tap(tester, right(tester)); await tap(tester, right(tester)); expect(find.text('5 seconds'), findsOneWidget); - expect(circles(), findsOneWidget, reason: 'the bubble, no ripple'); + expect(halfDisc(), findsOneWidget); await tester.pump(StashVideoControls.seekSequenceWindow); }); @@ -333,7 +337,7 @@ void main() { await tester.tapAt(right(tester)); await tester.pump(); expect(player.seeks, isEmpty); - expect(circles(), findsNothing); + expect(halfDisc(), findsNothing); await tester.pump(const Duration(seconds: 4)); }); diff --git a/test/features/video_controls_test.dart b/test/features/video_controls_test.dart index 905b928..77fdc03 100644 --- a/test/features/video_controls_test.dart +++ b/test/features/video_controls_test.dart @@ -188,13 +188,17 @@ void main() { expect(player.rates, [1.5]); }); - testWidgets('pinching zooms into the video, and the zoom stays after letting go', (tester) async { + testWidgets('pinching zooms into the video continuously, and the zoom stays after letting go', (tester) async { await pump(tester); final container = ProviderScope.containerOf(tester.element(find.byType(StashVideoControls))); final center = tester.getCenter(find.byType(StashVideoControls)); final a = await tester.startGesture(center - const Offset(40, 0)); final b = await tester.startGesture(center + const Offset(40, 0)); await tester.pump(); + await a.moveTo(center - const Offset(60, 0)); + await b.moveTo(center + const Offset(60, 0)); + await tester.pump(); + expect(container.read(videoZoomProvider).scale, closeTo(1.5, 0.01), reason: 'follows the fingers'); await a.moveTo(center - const Offset(80, 0)); await b.moveTo(center + const Offset(80, 0)); await tester.pump(); @@ -207,6 +211,19 @@ void main() { expect(container.read(videoZoomProvider).scale, closeTo(2, 0.01)); }); + testWidgets('zooming the video leaves the controls where and as big as they were', (tester) async { + await pump(tester); + await tapVideo(tester); + final before = tester.getRect(find.byTooltip('Fullscreen')); + final container = ProviderScope.containerOf(tester.element(find.byType(StashVideoControls))); + container.read(videoZoomProvider.notifier).set(const VideoZoom(scale: 2, panX: 0.1)); + await tester.pump(); + final after = tester.getRect(find.byTooltip('Fullscreen')); + expect(after.center.dx, closeTo(before.center.dx, 0.01)); + expect(after.center.dy, closeTo(before.center.dy, 0.01)); + expect(after.size, before.size); + }); + group('playback error', () { const error = PlaybackError('Failed to open', position: Duration(seconds: 12)); const streams = [ diff --git a/test/features/video_zoom_test.dart b/test/features/video_zoom_test.dart index 1297226..be943c8 100644 --- a/test/features/video_zoom_test.dart +++ b/test/features/video_zoom_test.dart @@ -1,14 +1,16 @@ import 'dart:ui'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:stash_app_mobile/features/player/video_zoom.dart'; void main() { const box = Size(400, 225); const center = Offset(200, 112.5); + const wide = 16 / 9; test('pinching at the center zooms without panning', () { - final z = VideoZoom.none.pinch(factor: 2, startFocal: center, focal: center, box: box); + final z = VideoZoom.none.pinch(factor: 2, startFocal: center, focal: center, box: box, aspect: wide); expect(z.scale, 2); expect(z.panX, 0); expect(z.panY, 0); @@ -16,22 +18,100 @@ void main() { test('the point under the fingers stays under them', () { const focal = Offset(300, 112.5); // 100 px right of the center - final z = VideoZoom.none.pinch(factor: 2, startFocal: focal, focal: focal, box: box); + final z = VideoZoom.none.pinch(factor: 2, startFocal: focal, focal: focal, box: box, aspect: wide); // The video moves 100 px left, so its point at +100 px is now at +100 px. expect(z.panX * box.width * z.scale, closeTo(-100, 0.001)); }); test('the video always covers the box and zoom stays between 1x and 4x', () { - final far = VideoZoom.none.pinch(factor: 2, startFocal: center, focal: center + const Offset(1000, 0), box: box); + final far = VideoZoom.none.pinch( + factor: 2, startFocal: center, focal: center + const Offset(1000, 0), box: box, aspect: wide); expect(far.panX * box.width * far.scale, closeTo(box.width / 2, 0.001), reason: 'at most half the overflow'); - expect(VideoZoom.none.pinch(factor: 10, startFocal: center, focal: center, box: box).scale, VideoZoom.maxScale); - expect(VideoZoom.none.pinch(factor: 0.5, startFocal: center, focal: center, box: box).scale, 1); + expect(VideoZoom.none.pinch(factor: 10, startFocal: center, focal: center, box: box, aspect: wide).scale, + VideoZoom.maxScale); + expect(VideoZoom.none.pinch(factor: 0.5, startFocal: center, focal: center, box: box, aspect: wide).scale, 1); }); test('a pinch continues from the current zoom and snaps back when barely zoomed', () { - final twice = VideoZoom.none.pinch(factor: 2, startFocal: center, focal: center, box: box); - expect(twice.pinch(factor: 1.5, startFocal: center, focal: center, box: box).scale, 3); + final twice = VideoZoom.none.pinch(factor: 2, startFocal: center, focal: center, box: box, aspect: wide); + expect(twice.pinch(factor: 1.5, startFocal: center, focal: center, box: box, aspect: wide).scale, 3); expect(const VideoZoom(scale: 1.03).settled(), VideoZoom.none); expect(twice.settled(), twice); }); + + group('fill: the whole box without black bars', () { + // A 16:9 video on a 20:9 screen: it covers the box at 20/16 = 1.25x. + const screen = Size(2000, 900); + + test('the cover scale depends on the box, in both directions', () { + expect(VideoZoom.coverScale(screen, wide), closeTo((20 / 9) / (16 / 9), 0.001)); + expect(VideoZoom.coverScale(const Size(1600, 900), 9 / 16), closeTo(3.16, 0.01)); + expect(VideoZoom.coverScale(const Size(2400, 900), 9 / 16), VideoZoom.maxScale); + expect(VideoZoom.coverScale(const Size(1600, 900), wide), closeTo(1, 0.001)); + }); + + test('the width grows continuously with the pinch and sticks to the full width', () { + final cover = VideoZoom.coverScale(screen, wide); + VideoZoom pinch(double factor) => + VideoZoom.none.pinch(factor: factor, startFocal: screen.center(Offset.zero), focal: screen.center(Offset.zero), box: screen, aspect: wide); + expect(pinch(1.1).scale, closeTo(1.1, 0.001)); + expect(pinch(1.1).fill, isFalse); + // Within a few percent of the full width it snaps to it... + expect(pinch(cover * 0.97).scale, closeTo(cover, 0.001)); + expect(pinch(cover * 0.97).fill, isTrue); + expect(pinch(cover * 1.03).fill, isTrue); + // ...and zooms on beyond. + expect(pinch(cover * 1.5).scale, closeTo(cover * 1.5, 0.001)); + expect(pinch(cover * 1.5).fill, isFalse); + }); + + test('it also sticks to the fitted size, and the pan to the center and the edges', () { + VideoZoom pinch(double factor, {Offset shift = Offset.zero}) => VideoZoom.none.pinch( + factor: factor, startFocal: screen.center(Offset.zero), focal: screen.center(Offset.zero) + shift, box: screen, aspect: wide); + expect(pinch(1.05).scale, 1, reason: 'full height: back to the fitted size'); + expect(pinch(1.15).scale, closeTo(1.15, 0.001)); + // Fingers that drift a few pixels up or down don't move the picture... + expect(pinch(2, shift: const Offset(0, 9)).panY, 0); + expect(pinch(2, shift: const Offset(9, 0)).panX, 0); + // ...but a real move does, and sticks to the edge when close to it. + final moved = pinch(2, shift: const Offset(0, 100)); + expect(moved.panY * screen.height * moved.scale, closeTo(100, 0.001)); + final limit = VideoZoom.panLimit(screen, wide, 2); + final nearEdge = pinch(2, shift: Offset(0, limit.dy - 8)); + expect(nearEdge.panY * screen.height * 2, closeTo(limit.dy, 0.001)); + }); + + test('it reports what it sticks to, for the haptic tick', () { + VideoZoom pinch(double factor, {Offset shift = Offset.zero}) => VideoZoom.none.pinch( + factor: factor, startFocal: screen.center(Offset.zero), focal: screen.center(Offset.zero) + shift, box: screen, aspect: wide); + expect(pinch(1.05).snaps & VideoZoom.snapScale, isNonZero, reason: 'the fitted size'); + expect(pinch(1.24).snaps & VideoZoom.snapScale, isNonZero, reason: 'the full width'); + expect(pinch(1.15).snaps & VideoZoom.snapScale, isZero); + expect(pinch(2, shift: const Offset(0, 9)).snaps & VideoZoom.snapPanY, isNonZero); + expect(pinch(2, shift: const Offset(0, 100)).snaps & VideoZoom.snapPanY, isZero); + }); + + test('a fill is worked out again for another box', () { + const filled = VideoZoom(scale: 1.25, fill: true); + expect(filled.scaleIn(screen, wide), closeTo(1.25, 0.001)); + expect(filled.scaleIn(const Size(1600, 900), wide), closeTo(1, 0.001), reason: 'it fills that box already'); + expect(filled.scaleIn(const Size(900, 1600), wide), closeTo(3.16, 0.01)); + }); + + test('a new scene keeps the fill but not a pinch zoom', () { + final container = _container(); + container.read(videoZoomProvider.notifier).set(const VideoZoom(scale: 2, panX: 0.1)); + container.read(videoZoomProvider.notifier).resetZoom(); + expect(container.read(videoZoomProvider), VideoZoom.none); + container.read(videoZoomProvider.notifier).set(const VideoZoom(scale: 1.25, fill: true)); + container.read(videoZoomProvider.notifier).resetZoom(); + expect(container.read(videoZoomProvider), const VideoZoom(fill: true)); + }); + }); +} + +ProviderContainer _container() { + final c = ProviderContainer(); + addTearDown(c.dispose); + return c; } diff --git a/test/features/whats_new_test.dart b/test/features/whats_new_test.dart index 0818651..2771c5f 100644 --- a/test/features/whats_new_test.dart +++ b/test/features/whats_new_test.dart @@ -61,17 +61,13 @@ void main() { testWidgets('after an update: shown once', (tester) async { final c = await pump(tester); expect(find.text(l.whatsNewTitle), findsOneWidget); - expect(find.text(l.whatsNew1Title), findsOneWidget); + expect(find.text(l.whatsNew2Title), findsOneWidget); + expect(find.text(l.whatsNew1Title), findsNothing, reason: 'seen with an earlier release'); expect(find.byIcon(Icons.auto_awesome), findsNothing); - expect(find.byIcon(Icons.loop), findsOneWidget, reason: 'the loops item has its icon'); + expect(find.byIcon(Icons.closed_caption_outlined), findsOneWidget, reason: 'the subtitles item has its icon'); final entry = changelog(l).first; - expect(find.text(entry.more.first.text), findsNothing, reason: 'the rest behind "show more"'); - await tester.ensureVisible(find.text(l.whatsNewShowMore(entry.more.length))); - await tester.pumpAndSettle(); - await tester.tap(find.text(l.whatsNewShowMore(entry.more.length))); - await tester.pumpAndSettle(); - expect(find.text(entry.more.first.text, skipOffstage: false), findsOneWidget); - expect(find.text(l.whatsNewShowLess, skipOffstage: false), findsOneWidget); + expect(entry.more, isEmpty); + expect(find.text(l.whatsNewShowMore(1)), findsNothing, reason: 'nothing behind "show more"'); expect(c.read(whatsNewSeenProvider), latestChangelogId(l)); expect(prefs.getInt('whats_new_seen'), latestChangelogId(l), reason: 'stored'); diff --git a/test/fixtures.dart b/test/fixtures.dart index d004bd5..1ac9b76 100644 --- a/test/fixtures.dart +++ b/test/fixtures.dart @@ -187,7 +187,8 @@ ActivityStats activityFrom([Json fields = const {}]) => Json sceneDetailsJson([Json fields = const {}]) => typed('Scene', { 'id': '1', - 'paths': const {'sprite': null, 'vtt': null}, + 'paths': const {'sprite': null, 'vtt': null, 'caption': null}, + 'captions': const [], 'sceneStreams': const [], 'scene_markers': const [], 'files': const [],