feat: initial Cutdex application
Add the Flutter video editing application with project management, media import, timeline editing, preview, AI assistance, diagnostics and settings. Include shared UI and native host packages, platform runners, application tests and release tooling. Provide usage and contribution guides, the MIT license and third-party notices. Exclude local credentials, build outputs and validation data.
This commit is contained in:
commit
27e77fff39
718 files changed
+183958
No files matched your search
@@ -0,0 +1,418 @@
|
||||
# Application integration tests
|
||||
|
||||
`integration_test/` contains opt-in tests for the real application and native
|
||||
backends. `test_driver/integration_test.dart` is the host driver used by
|
||||
`flutter drive` for Profile measurements. Both directories contain test source;
|
||||
media, models, reports and credentials are supplied locally and stay outside
|
||||
version control. Normal release builds use `lib/main.dart`.
|
||||
|
||||
## Desktop plugin registration
|
||||
|
||||
`native_desktop_plugins_test.dart` checks the real application's registration of
|
||||
window chrome, dynamically configured file destinations, and the macOS fullscreen
|
||||
channel. It requires no media or models and does not simulate Finder/Explorer drops.
|
||||
|
||||
```sh
|
||||
flutter test integration_test/native_desktop_plugins_test.dart -d macos --flavor development
|
||||
```
|
||||
|
||||
Use `-d windows` on Windows. Rebuild the normal application entry point afterwards.
|
||||
|
||||
## Desktop processing
|
||||
|
||||
`processing_e2e_test.dart` checks Cutdex's connection to real desktop processing:
|
||||
app resource configuration, applying results to the timeline, and cancellation or
|
||||
closing the owning session.
|
||||
|
||||
Provide an external processing package, installed models in the app's resource
|
||||
directory, and a short speech fixture. A local Dart-define JSON specifies
|
||||
`CUTDEX_PROCESSING_ROOT` and `CUTDEX_ASR_FIXTURE`:
|
||||
|
||||
```sh
|
||||
flutter test integration_test/processing_e2e_test.dart -d macos --flavor development \
|
||||
--dart-define-from-file=/absolute/path/to/processing-e2e.json
|
||||
```
|
||||
|
||||
Use `-d windows` on Windows. The test skips without a configured source. It does not
|
||||
download models. Check that completed results appear in the timeline and that
|
||||
cancelled tasks do not apply results to a closed session.
|
||||
|
||||
## Editing diagnostics and logging measurements
|
||||
|
||||
`edit_diagnostics_test.dart` mounts the production timeline toolbar, speed slider
|
||||
and native preview. Supply a video with audio of at least 25 seconds; generated
|
||||
H.264/AAC test media is suitable. The test creates isolated projects, an in-memory
|
||||
application database, per-run diagnostic storage, exports and `results.json` under
|
||||
the output directory. It never opens a user project or changes the source media.
|
||||
|
||||
Four controlled failures are injected at the authoritative commit boundary:
|
||||
split, left/right trim and speed adjustment. Each failure must export the original
|
||||
stack, operation ID, clip/timeline/project IDs and unchanged before/after versions.
|
||||
Recovery then repeats the same UI path without the injected failure. These are
|
||||
fault-injection checks with real media and native playback, not evidence that the
|
||||
native backend itself produced these failures.
|
||||
|
||||
```sh
|
||||
flutter drive --profile -d macos --flavor production \
|
||||
--driver=test_driver/integration_test.dart \
|
||||
--target=integration_test/edit_diagnostics_test.dart \
|
||||
--dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/generated-720p30.mp4 \
|
||||
--dart-define=CUTDEX_TEST_REPORT=/absolute/path/to/output/profile
|
||||
```
|
||||
|
||||
After a native-decoder warmup, six measured runs alternate the same-build
|
||||
application diagnostic recording off/on (three pairs, alternating pair order). Each run uses
|
||||
the toolbar to split and trim with undo, drags the speed slider, plays the edited
|
||||
clip, and restores 1×. Reports include Flutter build/raster frame percentiles,
|
||||
frames over 16.67 ms, synchronous diagnostic-call costs and durable log
|
||||
appends/bytes. Bounded 16 ms pumps collect rendering samples during playback.
|
||||
Flutter frame timings do not measure the independently rendered native video or
|
||||
physical display refresh. No latency/FPS guarantee follows from this small sample.
|
||||
|
||||
macOS 14.4+ can separately measure the mounted sample-buffer renderer's delivered
|
||||
and dropped frames in an opt-in **Debug** run. Keep its window visible and
|
||||
unoccluded throughout the observation; the test checks both conditions. This
|
||||
native diagnostics channel is compiled only in Debug, so its frame statistics
|
||||
must not be presented as Profile measurements.
|
||||
|
||||
```sh
|
||||
CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1 flutter drive --debug -d macos --flavor development \
|
||||
--driver=test_driver/integration_test.dart \
|
||||
--target=integration_test/edit_diagnostics_test.dart \
|
||||
--dart-define=CUTDEX_DIAGNOSTIC_CADENCE=true \
|
||||
--dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/generated-720p30.mp4 \
|
||||
--dart-define=CUTDEX_TEST_REPORT=/absolute/path/to/output/native-debug
|
||||
```
|
||||
|
||||
Retain failed reports and their logs. Rebuild `lib/main.dart` for each tested
|
||||
flavor afterwards, since integration entry points are not distribution builds.
|
||||
|
||||
## Windows
|
||||
|
||||
Run against the original files in a separate output directory. The Windows
|
||||
test mounts the real editor panels, imports through the production workspace,
|
||||
and exercises the play/pause and split controls and speed slider. It also checks
|
||||
independent scale/rotation/position transforms, multi-channel keyframe interpolation,
|
||||
mask animation and stack ordering, audio edits, exported pixels and PCM, and exact
|
||||
saved project data after close/reopen. Segmented speed changes also check the
|
||||
source clock, source duration and undo. No playback backend is mocked. ISO import is accepted only
|
||||
when the native backend can probe an unprotected video stream.
|
||||
|
||||
```powershell
|
||||
flutter test integration_test/windows_real_media_test.dart -d windows `
|
||||
--dart-define=CUTDEX_VALIDATION_SOURCE='D:\validation\media-originals' `
|
||||
--dart-define=CUTDEX_VALIDATION_ROOT='D:\validation\windows-editing'
|
||||
```
|
||||
|
||||
`CUTDEX_VALIDATION_FILTER` optionally selects filenames containing any of the
|
||||
comma-separated substrings.
|
||||
`CUTDEX_VALIDATION_PREVIEW_SECONDS` sets each full-source playback observation
|
||||
(default 2); use 30 for a longer frame-delivery audit. Reports include dropped
|
||||
native frames, delivered frames per second and the maximum frame gap. These
|
||||
measure native preview delivery, not physical monitor refresh or speaker sound.
|
||||
`CUTDEX_VALIDATION_SOURCE_ROOTS` accepts semicolon-separated source directories
|
||||
when validating multiple collections. For Flutter performance measurements use
|
||||
`flutter drive --profile -d windows --flavor production
|
||||
--driver=test_driver/integration_test.dart
|
||||
--target=integration_test/windows_real_media_test.dart` with the same Dart
|
||||
defines: `flutter test` forces Debug mode. Playback observations additionally
|
||||
record process/time boundaries and Flutter build/raster timings for correlation
|
||||
with actual Windows audio-session peaks. Native textures can redraw without Dart
|
||||
frames, so the observation uses live frames and a continuous 16 ms viewport
|
||||
refresh to collect build/raster timings. Rendering timings measure framework
|
||||
work, rather than proving the physical display refreshed every source frame.
|
||||
The test scans subdirectories, creates one timeline per source, records each
|
||||
stage in `results.json`, and checks that source size and modification time stay
|
||||
unchanged. Full-duration preview checks sample 60 seconds, quarter, middle and end;
|
||||
editing checks use short clips. Exports use the selected video and audio tracks.
|
||||
Frame counters verify native frame delivery,
|
||||
without measuring physical display latency or judging speaker output. Keep the
|
||||
output outside the media directory and rebuild the normal `lib/main.dart`
|
||||
application after running an integration target.
|
||||
|
||||
The harness opens another project at the editor's 50-timeline limit. For a
|
||||
source with independently confirmed undecodable audio, a filtered diagnostic
|
||||
can set `CUTDEX_VALIDATION_FULL_PREVIEW_AUDIO=false` to check full-source video
|
||||
preview separately. The short editing clip still includes audio. Record the
|
||||
failed audio interval alongside this diagnostic; do not report it as successful
|
||||
full-source audio playback.
|
||||
|
||||
`CUTDEX_VALIDATION_FULL_PREVIEW_MUTE=true` keeps the full-source audio layer
|
||||
but sets its gain to zero and verifies the native
|
||||
muted-audio path. Short-clip audio edits still run normally. Constant mute must
|
||||
avoid decoding unreadable audio; keyed volume curves remain eligible to play.
|
||||
|
||||
`CUTDEX_VALIDATION_MUTE_DAMAGED_ASF=true` restricts that full-source mute diagnostic
|
||||
to ASF files in this corpus. Use it only alongside independent evidence of source
|
||||
audio damage. The report identifies every muted source; all selected editing
|
||||
clips still include audio. An accepted play command alone is insufficient:
|
||||
checks wait for clock/frame progress and inspect delayed playback errors.
|
||||
|
||||
`CUTDEX_VALIDATION_LONG_SPEED_ONLY=true` imports a full-length clip (the common
|
||||
audio/video duration minus 100 ms), applies exact 2×, 0.5× and 1× edits, and observes
|
||||
playback from the start and across the 30.72-second preview-window boundary. It
|
||||
checks unchanged source timing, timeline duration and exact project data after
|
||||
close/reopen. This diagnostic skips the short-clip transform/mask/export matrix;
|
||||
run the normal matrix separately. It samples full-length edited clips and does
|
||||
not play or export every frame of the original movies.
|
||||
|
||||
## Windows seek measurements
|
||||
|
||||
`windows_seek_latency_test.dart` measures real Profile preview requests and continuous
|
||||
playhead dragging with any playable video at least five seconds long. It probes the
|
||||
source duration and scales the seek points and drag spans to that duration. Provide
|
||||
`CUTDEX_SEEK_SOURCE` and `CUTDEX_SEEK_REPORT`; run it with the shared
|
||||
`test_driver/integration_test.dart` entry point using `flutter drive --profile`.
|
||||
|
||||
```powershell
|
||||
flutter drive --profile --flavor production -d windows `
|
||||
--driver=test_driver/integration_test.dart `
|
||||
--target=integration_test/windows_seek_latency_test.dart `
|
||||
--dart-define=CUTDEX_SEEK_SOURCE='D:/validation/media-originals/video.mp4' `
|
||||
--dart-define=CUTDEX_SEEK_REPORT='D:/validation/results/editor-seek.json'
|
||||
```
|
||||
|
||||
The report records request acknowledgment, pump timing, observed native positions
|
||||
and the final release position. It does not measure physical display latency or
|
||||
independently verify pixels/audio. For before/after comparisons, preserve both
|
||||
complete builds, use identical media and run serially without concurrent builds
|
||||
or exports. This test target is for measurement, not application distribution.
|
||||
|
||||
## Windows audio samples
|
||||
|
||||
`windows_audio_media_test.dart` validates original audio files with the production
|
||||
source preview, import service, editor widgets and Windows runtime. It creates
|
||||
isolated projects and settings, checks source SHA-256 after each file, and writes
|
||||
an incremental `results.json` report. The source should contain audio-only files
|
||||
longer than ten seconds, with audible content in the 2–6 second edit interval.
|
||||
|
||||
```powershell
|
||||
flutter test integration_test/windows_audio_media_test.dart -d windows `
|
||||
--dart-define=CUTDEX_VALIDATION_SOURCE=D:/validation/audio-originals `
|
||||
--dart-define=CUTDEX_VALIDATION_ROOT=D:/validation/audio-results
|
||||
```
|
||||
|
||||
Each file exercises full-source waveform decoding, preview seeks near the start,
|
||||
middle and end, playback/pause, import, editor scrubbing, split/undo/redo, speed
|
||||
slider, gain/mute, audio gain keyframes and saved keyframe records. Six native
|
||||
H.264/AAC exports check baseline duration, 2×/0.5× duration, -6 dB RMS ratio,
|
||||
silence and the keyframe fade envelope. The visual output is a black canvas for
|
||||
audio-only timelines. Masks and position keyframes use the video validation test.
|
||||
|
||||
`CUTDEX_VALIDATION_FILTER` selects comma-separated filename substrings.
|
||||
`CUTDEX_VALIDATION_METADATA_ONLY=true` runs just the probe and full waveform
|
||||
checks for faster diagnosis. Speaker sound is not measured by these assertions.
|
||||
Keep downloaded external samples outside the repository and retain their source
|
||||
URLs, hashes and license attribution. Rebuild `lib/main.dart` for distribution
|
||||
after integration testing.
|
||||
|
||||
## Android physical device
|
||||
|
||||
`android_real_media_test.dart` owns the editing workflow. Helpers in `support/`
|
||||
handle incremental reports (`real_media_report.dart`), full-length preview
|
||||
measurements (`android_preview_measurement.dart`) and edited-export pixel/audio
|
||||
checks (`real_media_export_checks.dart`).
|
||||
|
||||
The suite first checks the application's real device-information and version
|
||||
channels, then runs the media workflow. Its editor harness stacks the preview and
|
||||
properties on narrow phone displays. It uses an isolated in-memory settings
|
||||
database and creates a separate project.
|
||||
|
||||
Use the debug development app's private directory to avoid scoped-storage and
|
||||
device-specific restrictions on directories created by `adb push`. Install the
|
||||
normal APK before copying fixtures; `-d` permits a debug version-code downgrade
|
||||
after installing an ABI split, without deleting the app's data. Keep complete
|
||||
originals on the host. On a POSIX shell:
|
||||
|
||||
```sh
|
||||
flutter build apk --debug --flavor development
|
||||
adb -s DEVICE_SERIAL install -r -d build/app/outputs/flutter-apk/app-development-debug.apk
|
||||
adb -s DEVICE_SERIAL shell run-as com.example.cutdex.dev mkdir -p files/real-media files/real-validation
|
||||
adb -s DEVICE_SERIAL shell -T run-as com.example.cutdex.dev tee files/real-media/source.mp4 \
|
||||
< /absolute/path/to/source.mp4 > /dev/null
|
||||
flutter test integration_test/android_real_media_test.dart -d DEVICE_SERIAL \
|
||||
--flavor development --no-uninstall \
|
||||
--dart-define=CUTDEX_VALIDATION_SOURCE=/data/user/0/com.example.cutdex.dev/files/real-media \
|
||||
--dart-define=CUTDEX_VALIDATION_ROOT=/data/user/0/com.example.cutdex.dev/files/real-validation
|
||||
```
|
||||
|
||||
Keep `--no-uninstall`: uninstalling also removes copied fixtures and validation
|
||||
reports. With `flutter drive`, use `--debug --keep-app-running` to retain them.
|
||||
An optional
|
||||
`CUTDEX_VALIDATION_FILTER` selects filenames containing any comma-separated
|
||||
substring. `CUTDEX_VALIDATION_SAMPLE_START` selects the edit sample start in
|
||||
seconds (default 60); use a visibly nonblack scene for pixel comparisons.
|
||||
`CUTDEX_VALIDATION_PREVIEW_WIDTH` / `CUTDEX_VALIDATION_PREVIEW_HEIGHT` set the
|
||||
native preview render size and project canvas (defaults 640 / 360). Set 1920 /
|
||||
1080 for a full-HD preview run. `CUTDEX_VALIDATION_OBSERVATION_SECONDS` sets each
|
||||
full-source playback window (default 2); use 30 for a longer observation. The
|
||||
tail window leaves enough media for the configured observation. Reports include
|
||||
seek latency, surface presentations per second and timeline progress. Maximum
|
||||
frame gap is cumulative over the session. These counters do not measure unique
|
||||
decoded pictures, physical display refresh or speaker synchronization. Exports
|
||||
remain short 320×180 functional checks regardless of preview size.
|
||||
`CUTDEX_VALIDATION_PREVIEW_ONLY=true` runs probing and the three full-source
|
||||
preview windows, then checks the source file and closes the controller. This
|
||||
diagnostic skips editing and exports; its report must not be counted as an
|
||||
editing validation run. `CUTDEX_VALIDATION_CONCURRENT_IO` records whether fixture
|
||||
transfer is running alongside playback so that such runs can be excluded from
|
||||
controlled performance comparisons.
|
||||
Incomplete `.xltd` downloads and torrent descriptors are excluded.
|
||||
|
||||
The test verifies full-duration preview seeks at the start, middle and end,
|
||||
then imports each original, selects eight seconds and exercises playback,
|
||||
scrubbing, splitting, undo/redo and the 2×/0.5×/normal speed slider. It uses the
|
||||
editor command service for audio gain/mute, transform keyframes and rectangular,
|
||||
elliptical, feathered and inverted masks. Native exports verify duration, masked
|
||||
pixels and the RMS ratio for -6 dB audio; additional audio streams are exported
|
||||
and decoded separately. Each completed stage updates `results.json`.
|
||||
An additional export keeps transform keyframes without masks so that native
|
||||
composition is checked independently of masked rendering. Compare its one-second
|
||||
frame with the baseline shifted by the authored position, as well as its gain.
|
||||
Preview controllers are closed between sources to bound memory.
|
||||
Full-source playback allows up to ten seconds for frame progress and records
|
||||
observation time and slow playback separately. Short clips that reach their
|
||||
natural end during polling are accepted only with both clock and frame progress.
|
||||
|
||||
Frame counters measure delivery to the native surface writer. The short samples
|
||||
do not constitute watching the entire movie, measuring physical display latency,
|
||||
or independently judging audible sound through the tablet speakers.
|
||||
|
||||
Restore the normal development APK with target `lib/main.dart` after testing,
|
||||
using `adb install -r` to preserve fixtures and reports.
|
||||
|
||||
## macOS
|
||||
|
||||
Run the real macOS editor and native playback backend against a local media
|
||||
directory. This opt-in test creates a separate project and one timeline per
|
||||
video source, references originals without copying them, and writes an incremental
|
||||
JSON report into the output directory. It does not restore or edit an existing
|
||||
project. The test uses an in-memory recent-project registry and does not write
|
||||
to the normal application database. Without the required Dart defines, it skips.
|
||||
|
||||
```sh
|
||||
flutter test integration_test/downloads_workflow_test.dart -d macos \
|
||||
--flavor development \
|
||||
--dart-define=CUTDEX_VALIDATION_SOURCE=/absolute/path/to/media \
|
||||
--dart-define=CUTDEX_VALIDATION_ROOT=/absolute/path/to/output
|
||||
```
|
||||
|
||||
`CUTDEX_VALIDATION_FILTER` optionally selects filenames containing a substring
|
||||
for diagnosis. Omit it for the complete directory run. Set
|
||||
`--dart-define=CUTDEX_VALIDATION_DIRECT_DROP=true` to exercise external
|
||||
file-drop messages directly on the timeline, including import into the media
|
||||
library, instead of importing first and dragging a library tile.
|
||||
|
||||
The test sends the same native file-drop messages as Finder to the actual
|
||||
media panel, then uses pointer gestures to drag each tile into the timeline.
|
||||
It exercises the play/pause controls, split toolbar, 2× and 0.5× speed slider,
|
||||
and detach audio context menu, checks native playback after edits, and verifies
|
||||
saved timeline structure. File-drop messages are injected; this test does not
|
||||
drive Finder itself. Only the AppKit menu bridge is disabled inside the test,
|
||||
to exercise the application's existing Flutter context-menu fallback. No
|
||||
playback or import backend is mocked. Verify AppKit menu selection separately
|
||||
in the normally launched application.
|
||||
|
||||
Playback checks are short samples around edits. They verify the transport clock
|
||||
and errors, but do not measure sustained frame cadence or physical display
|
||||
latency. Use `downloads_preview_cadence_test.dart` for mounted renderer frame cadence
|
||||
and pause delivery checks. It requires macOS 14.4+, the host environment variable
|
||||
`CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1`, the same source/output Dart defines, and
|
||||
a visible window activated through macOS accessibility.
|
||||
|
||||
## iPhone native media validation
|
||||
|
||||
`ios_device_test.dart` runs seven shared regressions in one installation: real-media
|
||||
playback with audio, nested/reverse/freeze/transition composition, image/canvas
|
||||
composition, grouped keyframes and export, painted thumbnails, repeated canvas
|
||||
drags, and the full application playback/editing lifecycle. The application test
|
||||
uses the phone's Cut navigation destination when present. Desktop packaged-worker
|
||||
capability fixtures, Finder drops, and macOS display-cadence diagnostics are outside
|
||||
this iPhone suite; it does not validate model inference or physical display latency.
|
||||
|
||||
Use an unlocked developer-enabled iPhone and a valid signing team. Select the iOS
|
||||
`Runner` scheme explicitly because the default `development` flavor belongs to the
|
||||
other platforms. First install the test host using the shared empty-timeline test:
|
||||
|
||||
```sh
|
||||
flutter test integration_test/preview_startup_test.dart -d <iphone-udid> \
|
||||
--flavor Runner --no-uninstall \
|
||||
--plain-name 'opening a timeline initializes native preview through App providers'
|
||||
```
|
||||
|
||||
Copy a synthetic or nonpersonal H.264 Rec.709 + AAC fixture at least 30 seconds long
|
||||
into the installed app's sandbox. Keeping the app installed preserves this fixture
|
||||
through subsequent test builds:
|
||||
|
||||
```sh
|
||||
xcrun devicectl device copy to --device <iphone-udid> \
|
||||
--source /absolute/path/to/source.mp4 \
|
||||
--destination Documents/cutdex-validation-source.mp4 \
|
||||
--domain-type appDataContainer --domain-identifier com.example.cutdex
|
||||
flutter test integration_test/ios_device_test.dart -d <iphone-udid> \
|
||||
--flavor Runner --no-uninstall --reporter expanded \
|
||||
--dart-define=CUTDEX_TEST_SOURCE_DOCUMENT=cutdex-validation-source.mp4 \
|
||||
--dart-define=CUTDEX_TEST_OUTPUT=ios-keyframes
|
||||
```
|
||||
|
||||
The shared fixture helper also preserves `CUTDEX_TEST_SOURCE` for host paths and
|
||||
`CUTDEX_TEST_SOURCE_BASE64` for small embedded fixtures. Large Base64 defines can
|
||||
exceed Xcode's command/environment size limit; use the sandbox copy for full videos.
|
||||
Temporary embedded fixtures are deleted after the owning test. The explicitly
|
||||
copied sandbox fixture and optional keyframe artifacts remain available for inspection.
|
||||
`KEYFRAME_ARTIFACTS`, `THUMBNAIL_TIMING`, `DRAG_TIMING`, and `ACCEPTANCE` lines record
|
||||
artifact locations and completed phases in the test log.
|
||||
|
||||
The app and native dependency require iOS 17. If a stale generated
|
||||
`ios/Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage/Package.swift`
|
||||
still declares iOS 15, align its generated platform declaration to iOS 17 before
|
||||
retrying. This derived file is ignored; preserve the project's iOS 17 deployment
|
||||
settings rather than lowering the native package's supported platform.
|
||||
|
||||
## Arbitrary media timebases on macOS
|
||||
|
||||
`media_timebase_drop_test.dart` uses the native probe and the same drop target as
|
||||
Finder and project assets. It checks provisional placement, committing, exact
|
||||
saved timeline ticks, playback and long-distance seeks, a three-second native
|
||||
video/audio export, and undo after trimming. The source must have at least three
|
||||
seconds of usable video. Supply a file outside the repository with
|
||||
`CUTDEX_TEST_SOURCE`; `CUTDEX_TEST_OUTPUT` optionally preserves the export.
|
||||
|
||||
```sh
|
||||
flutter test integration_test/media_timebase_drop_test.dart -d macos \
|
||||
--flavor production \
|
||||
--dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/source.mp4 \
|
||||
--dart-define=CUTDEX_TEST_OUTPUT=/absolute/path/to/export.mp4
|
||||
```
|
||||
|
||||
The production scheme uses a separate build product from the default development
|
||||
scheme, so a running development App does not need to be replaced for this test.
|
||||
|
||||
## Android system document import
|
||||
|
||||
`android_document_import_test.dart` opens the real system picker. Use a generated
|
||||
H.264/AAC MP4 fixture in Downloads and select only that fixture. The test checks
|
||||
streamed import into managed project storage, duplicate selection, byte identity,
|
||||
native probing, thumbnails, playback, seeking and a video/audio export.
|
||||
|
||||
```sh
|
||||
flutter drive --debug --keep-app-running \
|
||||
--driver=test_driver/integration_test.dart \
|
||||
--target=integration_test/android_document_import_test.dart \
|
||||
-d DEVICE_SERIAL --flavor development \
|
||||
--dart-define=CUTDEX_DOCUMENT_SELECT=true \
|
||||
--dart-define=CUTDEX_DOCUMENT_ROOT=/data/user/0/com.example.cutdex.dev/files/document-validation \
|
||||
--dart-define=CUTDEX_DOCUMENT_SHA256=FIXTURE_SHA256
|
||||
```
|
||||
|
||||
After `import.json` reports `complete: true`, remove the generated original from
|
||||
Downloads. Re-run the same command without `CUTDEX_DOCUMENT_SELECT=true` to start
|
||||
a new app process and verify the managed original independently of provider
|
||||
access. `reopen.json` records the repeated hash, playback and export checks. Keep
|
||||
app data between runs; `--keep-app-running` prevents the driver from uninstalling
|
||||
the app. Use `adb shell run-as com.example.cutdex.dev` to retrieve reports and
|
||||
remove the test's own project and exports afterward.
|
||||
|
||||
Some devices disconnect the host driver while DocumentsUI is foreground. In
|
||||
that case, inspect the original application's log and private JSON reports; a
|
||||
driver disconnection alone does not establish whether the import succeeded.
|
||||
@@ -0,0 +1,236 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:cutdex/integrations/platform/file_picker.dart';
|
||||
import 'package:cutdex/workspace/external_media_import.dart';
|
||||
import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/workspace/persistence/timeline_creation_names.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import 'support/android_preview_measurement.dart' show pumpUntil;
|
||||
|
||||
// Opt-in: select only a generated video fixture in the real system picker.
|
||||
// Re-run without CUTDEX_DOCUMENT_SELECT after deleting the original fixture.
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
const rootPath = String.fromEnvironment('CUTDEX_DOCUMENT_ROOT');
|
||||
const select = bool.fromEnvironment('CUTDEX_DOCUMENT_SELECT');
|
||||
const expectedHash = String.fromEnvironment('CUTDEX_DOCUMENT_SHA256');
|
||||
|
||||
testWidgets(
|
||||
'Android document import survives provider removal and app restart',
|
||||
(tester) async {
|
||||
expect(Platform.isAndroid, isTrue);
|
||||
expect(rootPath, isNotEmpty);
|
||||
final root = await Directory(rootPath).create(recursive: true);
|
||||
final projectPath = p.join(root.path, 'Document.cutdex');
|
||||
final reportFile = File(
|
||||
p.join(root.path, select ? 'import.json' : 'reopen.json'),
|
||||
);
|
||||
final report = <String, Object?>{'select': select, 'complete': false};
|
||||
void save() => reportFile.writeAsStringSync(jsonEncode(report));
|
||||
final runtime = CutdexRuntime();
|
||||
ProjectWorkspace createWorkspace() => ProjectWorkspace(
|
||||
creationNames: const TimelineCreationNames(
|
||||
timeline: 'Test',
|
||||
sequence: 'Test',
|
||||
storyline: 'Test',
|
||||
),
|
||||
runtime: runtime,
|
||||
);
|
||||
var workspace = createWorkspace();
|
||||
RuntimeSession? preview;
|
||||
try {
|
||||
await tester.pumpWidget(
|
||||
const MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Center(child: Text('Document import validation')),
|
||||
),
|
||||
),
|
||||
);
|
||||
save();
|
||||
if (select) {
|
||||
debugPrint('DOCUMENT_PICKER_READY');
|
||||
final files = await tester.runAsync(
|
||||
() => const AppFilePicker().pickFiles(allowedExtensions: ['mp4']),
|
||||
);
|
||||
expect(files, hasLength(1));
|
||||
expect(files!.single, isA<ContentMediaFile>());
|
||||
report['sourceUri'] = files.single.sourceUri.toString();
|
||||
save();
|
||||
await tester.runAsync(() async {
|
||||
final providerInfo = await runtime.probe(
|
||||
MediaReference(
|
||||
id: 'provider-original',
|
||||
uri: files.single.sourceUri,
|
||||
),
|
||||
);
|
||||
expect(providerInfo.videoTrackCount, greaterThan(0));
|
||||
expect(providerInfo.audioTrackCount, greaterThan(0));
|
||||
report['providerVideoTracks'] = providerInfo.videoTrackCount;
|
||||
report['providerAudioTracks'] = providerInfo.audioTrackCount;
|
||||
await workspace.open(projectPath, name: 'Document');
|
||||
final projectId = workspace.project!.info.id;
|
||||
final result = await workspace.importExternalMedia(projectId, [
|
||||
files.single,
|
||||
files.single,
|
||||
]);
|
||||
expect(result.failures, isEmpty);
|
||||
expect(result.added, 1);
|
||||
expect(result.duplicates, 1);
|
||||
final asset = result.assets.single;
|
||||
expect(asset.storage, AssetStorage.managed);
|
||||
expect(asset.name, files.single.displayName);
|
||||
final locations = await const MediaFileResolver().resolve(
|
||||
files,
|
||||
result.assets,
|
||||
);
|
||||
expect(
|
||||
locations[files.single],
|
||||
contains(mediaSourceLocation(asset)),
|
||||
);
|
||||
report['assetId'] = asset.id;
|
||||
report['assetName'] = asset.name;
|
||||
report['managedLocation'] = asset.location;
|
||||
report['byteLength'] = asset.byteLength;
|
||||
report['duplicates'] = result.duplicates;
|
||||
await workspace.close();
|
||||
workspace = createWorkspace();
|
||||
});
|
||||
}
|
||||
await tester.runAsync(() => workspace.open(projectPath));
|
||||
final assets = await tester.runAsync(
|
||||
() => workspace.project!.listAssets(),
|
||||
);
|
||||
expect(assets, hasLength(1));
|
||||
final asset = assets!.single;
|
||||
expect(asset.storage, AssetStorage.managed);
|
||||
final uri = (await tester.runAsync(
|
||||
() => workspace.project!.resolveAsset(asset),
|
||||
))!;
|
||||
expect(uri.scheme, 'file');
|
||||
final hash = await tester.runAsync(
|
||||
() async => (await sha256.bind(File.fromUri(uri).openRead()).first)
|
||||
.toString(),
|
||||
);
|
||||
if (expectedHash.isNotEmpty) expect(hash, expectedHash);
|
||||
report['sha256'] = hash;
|
||||
report['resolvedUri'] = uri.toString();
|
||||
final media = MediaReference(id: asset.id, uri: uri);
|
||||
final info = (await tester.runAsync(() => runtime.probe(media)))!;
|
||||
expect(info.videoTrackCount, greaterThan(0));
|
||||
expect(info.audioTrackCount, greaterThan(0));
|
||||
final thumbnail = (await tester.runAsync(
|
||||
() => runtime.thumbnail(
|
||||
ThumbnailRequest(
|
||||
media: media,
|
||||
time: MediaTime(1, 1),
|
||||
maximumWidth: 320,
|
||||
maximumHeight: 180,
|
||||
),
|
||||
),
|
||||
))!;
|
||||
expect(thumbnail.data, isNotEmpty);
|
||||
final duration = MediaTime(6, 1);
|
||||
final range = MediaRange(start: MediaTime(0, 1), duration: duration);
|
||||
final plan = ExecutionPlan(
|
||||
duration: duration,
|
||||
renderSize: RenderSize(320, 180),
|
||||
frameDuration: MediaTime(1, 30),
|
||||
media: [media],
|
||||
visualLayers: [
|
||||
VisualLayer(
|
||||
id: 'video',
|
||||
mediaId: media.id,
|
||||
sourceRange: range,
|
||||
timelineRange: range,
|
||||
inputColorSpace: RenderColorSpace.rec709,
|
||||
),
|
||||
],
|
||||
audioLayers: [
|
||||
AudioLayer(
|
||||
id: 'audio',
|
||||
mediaId: media.id,
|
||||
sourceRange: range,
|
||||
timelineRange: range,
|
||||
),
|
||||
],
|
||||
);
|
||||
final session = (await tester.runAsync(runtime.createSession))!;
|
||||
preview = session;
|
||||
await tester.runAsync(() => session.load(plan));
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Center(
|
||||
child: SizedBox(
|
||||
width: 320,
|
||||
height: 180,
|
||||
child: RuntimePreview(session: session),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => (session.snapshot?.presentedVideoFrameCount ?? 0) > 0,
|
||||
'document first frame',
|
||||
);
|
||||
final before = (await tester.runAsync(session.refresh))!;
|
||||
await tester.runAsync(session.play);
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(seconds: 1)),
|
||||
);
|
||||
await tester.pump();
|
||||
final playing = (await tester.runAsync(session.refresh))!;
|
||||
expect(playing.message, isNull);
|
||||
expect(playing.position.seconds, greaterThan(before.position.seconds));
|
||||
expect(
|
||||
playing.presentedVideoFrameCount,
|
||||
greaterThan(before.presentedVideoFrameCount ?? 0),
|
||||
);
|
||||
await tester.runAsync(session.pause);
|
||||
await tester.runAsync(() => session.seek(MediaTime(3, 1)));
|
||||
final destination = File(
|
||||
p.join(root.path, select ? 'import-export.mp4' : 'reopen-export.mp4'),
|
||||
);
|
||||
if (await destination.exists()) await destination.delete();
|
||||
final exported = (await tester.runAsync(
|
||||
() => session.export(plan, destination.uri),
|
||||
))!;
|
||||
final exportInfo = (await tester.runAsync(
|
||||
() => runtime.probe(MediaReference(id: 'export', uri: exported)),
|
||||
))!;
|
||||
expect(exportInfo.videoTrackCount, greaterThan(0));
|
||||
expect(exportInfo.audioTrackCount, greaterThan(0));
|
||||
report.addAll({
|
||||
'complete': true,
|
||||
'videoTracks': info.videoTrackCount,
|
||||
'audioTracks': info.audioTrackCount,
|
||||
'presentedFrames': playing.presentedVideoFrameCount,
|
||||
'exportUri': exported.toString(),
|
||||
'exportDuration': exportInfo.duration.seconds,
|
||||
});
|
||||
save();
|
||||
debugPrint('DOCUMENT_IMPORT_PASSED ${jsonEncode(report)}');
|
||||
} catch (error, stack) {
|
||||
report.addAll({'error': error.toString(), 'stack': stack.toString()});
|
||||
save();
|
||||
rethrow;
|
||||
} finally {
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.runAsync(() async {
|
||||
await preview?.close();
|
||||
await workspace.close();
|
||||
});
|
||||
}
|
||||
},
|
||||
timeout: const Timeout(Duration(minutes: 10)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,804 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
|
||||
// Opt-in validation against complete, unmodified real media on Android.
|
||||
// Run with `flutter test --no-uninstall` to retain app data and source fixtures.
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/properties/properties_panel.dart';
|
||||
import 'package:cutdex/features/timeline/timeline_panel.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/media_file_extensions.dart';
|
||||
import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/preview_controller_registry.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import 'support/android_preview_measurement.dart';
|
||||
import 'support/real_media_export_checks.dart';
|
||||
import 'support/real_media_report.dart';
|
||||
|
||||
import 'support/saved_edit_validation.dart';
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
const source = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE');
|
||||
const output = String.fromEnvironment('CUTDEX_VALIDATION_ROOT');
|
||||
const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER');
|
||||
const sampleStart = int.fromEnvironment(
|
||||
'CUTDEX_VALIDATION_SAMPLE_START',
|
||||
defaultValue: 60,
|
||||
);
|
||||
const previewWidth = int.fromEnvironment(
|
||||
'CUTDEX_VALIDATION_PREVIEW_WIDTH',
|
||||
defaultValue: 640,
|
||||
);
|
||||
const previewHeight = int.fromEnvironment(
|
||||
'CUTDEX_VALIDATION_PREVIEW_HEIGHT',
|
||||
defaultValue: 360,
|
||||
);
|
||||
const observationSeconds = int.fromEnvironment(
|
||||
'CUTDEX_VALIDATION_OBSERVATION_SECONDS',
|
||||
defaultValue: 2,
|
||||
);
|
||||
const concurrentIo = bool.fromEnvironment('CUTDEX_VALIDATION_CONCURRENT_IO');
|
||||
const previewOnly = bool.fromEnvironment('CUTDEX_VALIDATION_PREVIEW_ONLY');
|
||||
testWidgets(
|
||||
'Android host registers native device facts and application info',
|
||||
(tester) async {
|
||||
expect(Platform.isAndroid, isTrue);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
final device = await NativeDeviceInfo.read();
|
||||
expect(
|
||||
device,
|
||||
isNotNull,
|
||||
reason: 'The application host must register cutdex_native.',
|
||||
);
|
||||
expect(device!.displayShortestSideDp, greaterThan(0));
|
||||
expect(device.interfaceIdiom, isNull);
|
||||
final application = await NativeDeviceInfo.readApplicationInfo();
|
||||
expect(application['appVersion'], isNotEmpty);
|
||||
expect(int.tryParse(application['appBuild'] ?? ''), greaterThan(0));
|
||||
},
|
||||
);
|
||||
testWidgets('Android real media: preview and editing through native runtime', (
|
||||
tester,
|
||||
) async {
|
||||
expect(Platform.isAndroid, isTrue);
|
||||
expect(source, isNotEmpty);
|
||||
expect(output, isNotEmpty);
|
||||
expect(previewWidth, greaterThan(0));
|
||||
expect(previewHeight, greaterThan(0));
|
||||
expect(observationSeconds, greaterThan(0));
|
||||
final paths =
|
||||
Directory(source)
|
||||
.listSync()
|
||||
.whereType<File>()
|
||||
.where(
|
||||
(file) =>
|
||||
mediaKindForPath(file.path) == 'video' &&
|
||||
(filter.isEmpty ||
|
||||
filter.split(',').any(p.basename(file.path).contains)),
|
||||
)
|
||||
.toList()
|
||||
..sort((a, b) => a.path.compareTo(b.path));
|
||||
expect(paths, isNotEmpty);
|
||||
final root = await Directory(output).create(recursive: true);
|
||||
final report = RealMediaReport(
|
||||
File(p.join(root.path, 'results.json')),
|
||||
metadata: {
|
||||
'platform': 'android',
|
||||
'source': source,
|
||||
'previewOnly': previewOnly,
|
||||
'previewSize': [previewWidth, previewHeight],
|
||||
'playbackObservationSeconds': observationSeconds,
|
||||
'concurrentFixtureTransfer': concurrentIo,
|
||||
'frameTimingMethod':
|
||||
'Native surface presentation counters in a debug integration build; '
|
||||
'not physical display refresh or speaker synchronization.',
|
||||
'method': previewOnly
|
||||
? 'Original files; probing, thumbnails and full-length native preview only. '
|
||||
'Editing and exports skipped. Settings database isolated in memory.'
|
||||
: 'Original files; production import service, real editor widgets, '
|
||||
'split toolbar and speed slider; command service for keyframes/audio/masks; '
|
||||
'native preview, thumbnails and export. Settings database isolated in memory.',
|
||||
},
|
||||
);
|
||||
final savedEdits = SavedEditValidation();
|
||||
final results = report.files;
|
||||
final save = report.save;
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
final container = ProviderContainer(
|
||||
overrides: [appDatabaseProvider.overrideWithValue(database)],
|
||||
);
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
final runtime = CutdexRuntime();
|
||||
addTearDown(database.close);
|
||||
var disposed = false;
|
||||
addTearDown(() {
|
||||
if (!disposed) container.dispose();
|
||||
});
|
||||
|
||||
Future<void> until(
|
||||
bool Function() ready,
|
||||
String label, {
|
||||
int seconds = 60,
|
||||
}) => pumpUntil(tester, ready, label, seconds: seconds);
|
||||
|
||||
expect(
|
||||
await projects.open(
|
||||
p.join(
|
||||
root.path,
|
||||
'Real-media-${DateTime.now().millisecondsSinceEpoch}.cutdex',
|
||||
),
|
||||
name: 'Android 真实素材验证',
|
||||
initialTimelineName: '01',
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
final projectId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.activeProject!
|
||||
.id;
|
||||
for (var index = 0; index < paths.length; index++) {
|
||||
final file = paths[index];
|
||||
final before = await file.stat();
|
||||
final checks = <Map<String, Object?>>[];
|
||||
final result = <String, Object?>{
|
||||
'path': file.path,
|
||||
'checks': checks,
|
||||
'sourceStartSeconds': sampleStart,
|
||||
'passed': false,
|
||||
};
|
||||
results.add(result);
|
||||
save();
|
||||
var stage = 'setup';
|
||||
String? testedTimeline;
|
||||
void Function()? releaseTimeline;
|
||||
Future<void> check(String name, Future<void> Function() action) async {
|
||||
stage = name;
|
||||
debugPrint(
|
||||
'REAL_MEDIA ${index + 1}/${paths.length} $name ${p.basename(file.path)}',
|
||||
);
|
||||
final clock = Stopwatch()..start();
|
||||
await action().timeout(const Duration(minutes: 4));
|
||||
expect(
|
||||
tester.takeException(),
|
||||
isNull,
|
||||
reason: 'Widget error during $name',
|
||||
);
|
||||
checks.add({
|
||||
'stage': name,
|
||||
'passed': true,
|
||||
'milliseconds': clock.elapsedMilliseconds,
|
||||
});
|
||||
save();
|
||||
}
|
||||
|
||||
try {
|
||||
if (index > 0) {
|
||||
expect(await projects.createTimeline(name: '${index + 1}'), isTrue);
|
||||
}
|
||||
final timelineId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timeline!
|
||||
.id;
|
||||
testedTimeline = timelineId;
|
||||
final retainedTimeline = container.listen(
|
||||
editorTimelineProvider(projectId, timelineId),
|
||||
(_, _) {},
|
||||
);
|
||||
releaseTimeline = retainedTimeline.close;
|
||||
final session = await container.read(
|
||||
editorTimelineProvider(projectId, timelineId).future,
|
||||
);
|
||||
final sequence = session.activeSequenceId!;
|
||||
final view = session.view(sequence);
|
||||
final media = MediaReference(id: 'real-source', uri: file.uri);
|
||||
late MediaInfo info;
|
||||
await check('probeOriginalAndSeekThumbnails', () async {
|
||||
try {
|
||||
info = await runtime.probe(media);
|
||||
} catch (_) {
|
||||
final raw = await runtime.invoke('probe', {'media': media.toMap()});
|
||||
result['rawProbeMetadata'] = raw;
|
||||
// Preserve the actual wire-contract failure in the device report.
|
||||
MediaInfo.fromMap(raw! as Map);
|
||||
rethrow;
|
||||
}
|
||||
expect(info.videoTrackCount, greaterThan(0));
|
||||
expect(info.audioTrackCount, greaterThan(0));
|
||||
expect(info.duration.seconds, greaterThan(120));
|
||||
result['durationSeconds'] = info.duration.seconds;
|
||||
result['audioTracks'] = info.audioTrackCount;
|
||||
result['displaySizes'] = [
|
||||
for (final size in info.videoDisplaySizes)
|
||||
[size.width, size.height],
|
||||
];
|
||||
for (final seconds in [
|
||||
60.0,
|
||||
info.duration.seconds / 2,
|
||||
info.duration.seconds - 5,
|
||||
]) {
|
||||
final thumbnail = await runtime.thumbnail(
|
||||
ThumbnailRequest(
|
||||
media: media,
|
||||
time: MediaTime((seconds * 1000).round(), 1000),
|
||||
maximumWidth: 320,
|
||||
maximumHeight: 180,
|
||||
),
|
||||
);
|
||||
expect(thumbnail.data, isNotEmpty);
|
||||
final image = await decodeImageFromList(thumbnail.data);
|
||||
expect(image.width, greaterThan(0));
|
||||
image.dispose();
|
||||
}
|
||||
});
|
||||
await check(
|
||||
'fullLengthPreviewStartMiddleAndEnd',
|
||||
() => measureAndroidFullLengthPreview(
|
||||
tester: tester,
|
||||
runtime: runtime,
|
||||
media: media,
|
||||
info: info,
|
||||
configuration: (
|
||||
width: previewWidth,
|
||||
height: previewHeight,
|
||||
observationSeconds: observationSeconds,
|
||||
),
|
||||
result: result,
|
||||
save: save,
|
||||
),
|
||||
);
|
||||
if (previewOnly) {
|
||||
final unchanged = await file.stat();
|
||||
expect(unchanged.size, before.size);
|
||||
expect(unchanged.modified, before.modified);
|
||||
result['passed'] = true;
|
||||
result['sourceUnchanged'] = true;
|
||||
releaseTimeline();
|
||||
save();
|
||||
continue;
|
||||
}
|
||||
await check('importOriginalAndInsertSourceRange', () async {
|
||||
final imported = await projects.importExternalMedia(projectId, [
|
||||
ExternalMediaFile(path: file.path),
|
||||
]);
|
||||
expect(imported!.failures, isEmpty);
|
||||
final asset = imported.assets.firstWhere(
|
||||
(a) => a.name == p.basename(file.path),
|
||||
);
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
SetProjectCanvas(
|
||||
width: previewWidth.toDouble(),
|
||||
height: previewHeight.toDouble(),
|
||||
),
|
||||
);
|
||||
await session.commands.insertMedia(
|
||||
sequence: sequence,
|
||||
assetId: asset.id,
|
||||
clipId: ElementId('real-clip'),
|
||||
index: 0,
|
||||
sourceStart: RationalTime.seconds(sampleStart),
|
||||
duration: RationalTime.seconds(8),
|
||||
);
|
||||
});
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final narrow = constraints.maxWidth < 600;
|
||||
return Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Flex(
|
||||
direction: narrow ? Axis.vertical : Axis.horizontal,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: EditorPreviewPanel(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: narrow ? null : 280,
|
||||
height: narrow ? 200 : null,
|
||||
child: EditorPropertiesPanel(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: 210,
|
||||
child: EditorTimelinePanel(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await check('initializeNativePreview', () async {
|
||||
final initialized = await container
|
||||
.read(editorPreviewProvider(projectId, timelineId).future)
|
||||
.timeout(const Duration(minutes: 2));
|
||||
if (initialized == null) {
|
||||
throw StateError(
|
||||
'Preview is empty; timeline duration ${session.sequenceDurationTicks(sequence)}',
|
||||
);
|
||||
}
|
||||
debugPrint(
|
||||
'REAL_MEDIA_INITIALIZED ready=${initialized.ready} busy=${initialized.busy} error=${initialized.error} duration=${initialized.durationTick}',
|
||||
);
|
||||
await until(
|
||||
() {
|
||||
final state = container.read(
|
||||
editorPreviewProvider(projectId, timelineId),
|
||||
);
|
||||
if (state.hasError) {
|
||||
throw StateError('Native preview startup: ${state.error}');
|
||||
}
|
||||
final value = state.asData?.value;
|
||||
if (value?.error != null) {
|
||||
throw StateError('Native preview: ${value!.error}');
|
||||
}
|
||||
return value?.ready == true;
|
||||
},
|
||||
'preview initialized',
|
||||
seconds: 180,
|
||||
);
|
||||
});
|
||||
final preview = container
|
||||
.read(editorPreviewProvider(projectId, timelineId))
|
||||
.requireValue!;
|
||||
// Platform-view creation spans several Flutter frames on Android.
|
||||
await until(
|
||||
() => (preview.session?.snapshot?.presentedVideoFrameCount ?? 0) > 0,
|
||||
'first preview frame',
|
||||
seconds: 90,
|
||||
);
|
||||
final clipId = ElementId('real-clip');
|
||||
ElementRecord record() {
|
||||
final q = session.persistence.timeline(sequence).current.query();
|
||||
return q.element(q.elementById(clipId)!);
|
||||
}
|
||||
|
||||
Future<void> settled() async {
|
||||
await tester.pump();
|
||||
await until(
|
||||
() => !preview.busy && preview.ready,
|
||||
'preview synchronization: ${preview.error}',
|
||||
);
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
|
||||
Future<void> seek(double seconds) async {
|
||||
await preview.controlPreview(
|
||||
sequence,
|
||||
PreviewAction.seek,
|
||||
at: CommandTime((seconds * 1000).round(), 1000),
|
||||
);
|
||||
await settled();
|
||||
expect(
|
||||
(await preview.session!.refresh()).position.seconds,
|
||||
closeTo(seconds, .15),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> playback() async {
|
||||
await seek(0);
|
||||
final beforePlay = await preview.session!.refresh();
|
||||
await tester.tap(find.byTooltip('播放').first);
|
||||
var nextLog = DateTime.now();
|
||||
await until(() {
|
||||
if (preview.error != null) {
|
||||
throw StateError('Preview playback: ${preview.error}');
|
||||
}
|
||||
final native = preview.session!.snapshot;
|
||||
if (native?.message != null) {
|
||||
throw StateError('Native playback: ${native!.message}');
|
||||
}
|
||||
if (DateTime.now().isAfter(nextLog)) {
|
||||
nextLog = DateTime.now().add(const Duration(seconds: 2));
|
||||
debugPrint(
|
||||
'REAL_MEDIA_CLOCK ui=${preview.playing}/${preview.positionTick} native=${native?.state}/${native?.position.seconds}/${native?.presentedVideoFrameCount} busy=${preview.busy}',
|
||||
);
|
||||
}
|
||||
final reachedEnd =
|
||||
preview.durationTick > 0 &&
|
||||
preview.positionTick >=
|
||||
preview.durationTick - TimelineClock.ticksPerSecond / 10;
|
||||
return (preview.playing || reachedEnd) &&
|
||||
preview.positionTick > TimelineClock.ticksPerSecond / 2 &&
|
||||
(native?.presentedVideoFrameCount ?? 0) >
|
||||
(beforePlay.presentedVideoFrameCount ?? 0);
|
||||
}, 'native playback clock');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 250));
|
||||
await tester.pump();
|
||||
final playing = await preview.session!.refresh();
|
||||
expect(
|
||||
playing.presentedVideoFrameCount,
|
||||
greaterThan(beforePlay.presentedVideoFrameCount ?? 0),
|
||||
);
|
||||
final pause = find.byTooltip('暂停播放');
|
||||
if (pause.evaluate().isNotEmpty) {
|
||||
await tester.tap(pause.first);
|
||||
} else {
|
||||
expect(
|
||||
preview.positionTick,
|
||||
greaterThanOrEqualTo(
|
||||
preview.durationTick - TimelineClock.ticksPerSecond / 10,
|
||||
),
|
||||
);
|
||||
}
|
||||
await until(() => !preview.playing && !preview.busy, 'native pause');
|
||||
final at = preview.positionTick;
|
||||
await tester.pump(const Duration(milliseconds: 250));
|
||||
expect(
|
||||
(preview.positionTick - at).abs(),
|
||||
lessThan(TimelineClock.ticksPerSecond / 10),
|
||||
);
|
||||
expect(preview.error, isNull);
|
||||
(result.putIfAbsent(
|
||||
'playback',
|
||||
() => <Map<String, Object?>>[],
|
||||
) as List).add({
|
||||
'stage': stage,
|
||||
'positionSeconds': playing.position.seconds,
|
||||
'frames': playing.presentedVideoFrameCount,
|
||||
'dropped': playing.droppedVideoFrameCount,
|
||||
'maximumGapMs': playing.maximumVideoFrameGapMs,
|
||||
'rssBytes': ProcessInfo.currentRss,
|
||||
});
|
||||
}
|
||||
|
||||
await check('nativePreviewPlayPauseAndScrub', () async {
|
||||
expect(find.byType(RuntimePreview), findsOneWidget);
|
||||
await playback();
|
||||
for (final at in [6.5, .5, 7.5, 2.0, 0.0]) {
|
||||
await seek(at);
|
||||
}
|
||||
});
|
||||
await check('splitToolbarUndoRedo', () async {
|
||||
preview.selectVisual(clipId);
|
||||
await seek(4);
|
||||
await tester.tap(find.byTooltip('在播放头处分割'));
|
||||
await settled();
|
||||
expect(record().duration, 4 * TimelineClock.ticksPerSecond);
|
||||
expect(
|
||||
session.persistence.timeline(sequence).exportDto().elements.length,
|
||||
2,
|
||||
);
|
||||
await session.commands.executeEdit(sequence, const UndoEdit());
|
||||
await settled();
|
||||
expect(record().duration, 8 * TimelineClock.ticksPerSecond);
|
||||
await session.commands.executeEdit(sequence, const RedoEdit());
|
||||
await settled();
|
||||
final other = session.persistence
|
||||
.timeline(sequence)
|
||||
.exportDto()
|
||||
.elements
|
||||
.firstWhere((e) => e.id != clipId);
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
DeleteClip(other.id.value),
|
||||
);
|
||||
await settled();
|
||||
await playback();
|
||||
});
|
||||
await check('speedSliderHalfDoubleAndNormal', () async {
|
||||
preview.selectVisual(clipId);
|
||||
await seek(0);
|
||||
await tester.tap(find.byKey(const ValueKey('property-tab-speed')));
|
||||
await tester.pump();
|
||||
final slider = find.descendant(
|
||||
of: find.byKey(const Key('clip-speed-slider')),
|
||||
matching: find.byType(Slider),
|
||||
);
|
||||
expect(slider, findsOneWidget);
|
||||
for (final requested in [2.0, .5, 1.0]) {
|
||||
final bounds = tester.getRect(slider);
|
||||
final position = (math.log(requested) / math.ln10 + 1) / 3;
|
||||
final gesture = await tester.startGesture(
|
||||
Offset(
|
||||
bounds.left +
|
||||
12 +
|
||||
(bounds.width - 24) * tester.widget<Slider>(slider).value,
|
||||
bounds.center.dy,
|
||||
),
|
||||
);
|
||||
await gesture.moveTo(
|
||||
Offset(
|
||||
bounds.left + 12 + (bounds.width - 24) * position,
|
||||
bounds.center.dy,
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await gesture.up();
|
||||
await settled();
|
||||
expect(session.clipSpeed(record()), closeTo(requested, .05));
|
||||
expect(
|
||||
record().duration,
|
||||
closeTo(
|
||||
4 * TimelineClock.ticksPerSecond / requested,
|
||||
TimelineClock.ticksPerSecond / 4,
|
||||
),
|
||||
);
|
||||
await playback();
|
||||
}
|
||||
// Keep exact source timing for subsequent pixel/audio comparisons.
|
||||
session.setClipSpeed(sequence, clipId, 1);
|
||||
await settled();
|
||||
});
|
||||
Future<Uri> export(String suffix, {int audioOrdinal = 0}) async {
|
||||
final plan = const ExecutionCompiler()
|
||||
.compile(
|
||||
ExecutionInput(
|
||||
timeline: session.persistence.timeline(sequence),
|
||||
media: {
|
||||
record().payloadRef!: ExecutionMediaBinding(
|
||||
media: media,
|
||||
videoTrackSelection: TrackSelection.index(0),
|
||||
inputColorSpace:
|
||||
info.videoColorSpaces[0] ?? RenderColorSpace.rec709,
|
||||
audioTrackSelection: TrackSelection.index(audioOrdinal),
|
||||
audioTiming: info.audioTracks[audioOrdinal],
|
||||
),
|
||||
},
|
||||
renderSize: RenderSize(320, 180),
|
||||
parameterTargets: {
|
||||
...ClipTransform.targets,
|
||||
...ClipAudioGain.targets,
|
||||
},
|
||||
editorOnlyParameters: const {ClipAudioGain.detachedId},
|
||||
),
|
||||
)
|
||||
.plan;
|
||||
return preview.session!.export(
|
||||
plan,
|
||||
File(
|
||||
p.join(
|
||||
root.path,
|
||||
'${index.toString().padLeft(2, '0')}-$suffix.mp4',
|
||||
),
|
||||
).uri,
|
||||
);
|
||||
}
|
||||
|
||||
late Uri baseline;
|
||||
await check('baselineExportAndAudio', () async {
|
||||
baseline = await export('baseline');
|
||||
final exported = await runtime.probe(
|
||||
MediaReference(id: 'baseline', uri: baseline),
|
||||
);
|
||||
expect(exported.videoTrackCount, 1);
|
||||
expect(exported.audioTrackCount, 1);
|
||||
expect(exported.duration.seconds, closeTo(4, .1));
|
||||
result['baselineExport'] = baseline.toFilePath();
|
||||
});
|
||||
if (info.audioTrackCount > 1) {
|
||||
await check('alternateAudioTrackExportAndDecode', () async {
|
||||
final uri = await export('audio-track-1', audioOrdinal: 1);
|
||||
final alternate = MediaReference(id: 'alternate-audio', uri: uri);
|
||||
final wave = await runtime.waveform(
|
||||
WaveformRequest(
|
||||
media: alternate,
|
||||
baseBucketCount: 64,
|
||||
levelCount: 1,
|
||||
),
|
||||
);
|
||||
expect(wave.levels.first.channels.length, 2);
|
||||
expect(
|
||||
wave.levels.first.channels
|
||||
.expand((values) => values)
|
||||
.any((value) => value.abs() > .0001),
|
||||
isTrue,
|
||||
);
|
||||
result['alternateAudioExport'] = uri.toFilePath();
|
||||
});
|
||||
}
|
||||
await check('audioGainMuteAndRestore', () async {
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
const SetClipAudio(clipId: 'real-clip', db: -6, muted: true),
|
||||
);
|
||||
await settled();
|
||||
expect(ClipAudioGain.fromRecord(record()).muted, isTrue);
|
||||
await playback();
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
const SetClipAudio(clipId: 'real-clip', db: -6, muted: false),
|
||||
);
|
||||
await settled();
|
||||
expect(ClipAudioGain.fromRecord(record()).db, -6);
|
||||
});
|
||||
await check('transformKeyframesAndInterpolation', () async {
|
||||
for (final entry in [(0, 0.0), (2, .1)]) {
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
EditKeyframe(
|
||||
clipId: 'real-clip',
|
||||
parameterId: 'canvas.position.x',
|
||||
at: CommandTime(entry.$1, 1),
|
||||
action: KeyframeAction.set,
|
||||
value: entry.$2,
|
||||
interpolation: KeyInterpolation.linear,
|
||||
),
|
||||
);
|
||||
}
|
||||
await settled();
|
||||
await seek(1);
|
||||
final animation = ClipAnimation.at(
|
||||
view.version.kernelVersion.query(),
|
||||
view.version.kernelVersion.query().elementById(clipId)!,
|
||||
TimelineClock.ticksPerSecond,
|
||||
TimelineClock.ticksPerSecond ~/ 30,
|
||||
);
|
||||
expect(animation.value.x, closeTo(.05, .001));
|
||||
await playback();
|
||||
});
|
||||
await check('keyframeOnlyExport', () async {
|
||||
final uri = await export('keyframes');
|
||||
final exported = await runtime.probe(
|
||||
MediaReference(id: 'keyframes', uri: uri),
|
||||
);
|
||||
expect(exported.duration.seconds, closeTo(4, .1));
|
||||
result['keyframeExport'] = uri.toFilePath();
|
||||
});
|
||||
await check('rectangleEllipseFeatherAndInvertedMasks', () async {
|
||||
await seek(0);
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
EditMask(
|
||||
clipId: 'real-clip',
|
||||
at: CommandTime(0, 1),
|
||||
action: MaskAction.add,
|
||||
maskId: 'real-mask',
|
||||
shape: MaskShape.rectangle,
|
||||
x: .5,
|
||||
y: .5,
|
||||
width: .5,
|
||||
height: .5,
|
||||
),
|
||||
);
|
||||
await settled();
|
||||
for (final inverted in [false, true]) {
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
EditMask(
|
||||
clipId: 'real-clip',
|
||||
at: CommandTime(0, 1),
|
||||
action: MaskAction.set,
|
||||
maskId: 'real-mask',
|
||||
shape: MaskShape.ellipse,
|
||||
inverted: inverted,
|
||||
feather: .1,
|
||||
),
|
||||
);
|
||||
await settled();
|
||||
expect(
|
||||
ClipMaskStack(record(), 0).layers.single.mask.inverted,
|
||||
inverted,
|
||||
);
|
||||
await playback();
|
||||
}
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
EditMask(
|
||||
clipId: 'real-clip',
|
||||
at: CommandTime(0, 1),
|
||||
action: MaskAction.set,
|
||||
maskId: 'real-mask',
|
||||
shape: MaskShape.rectangle,
|
||||
inverted: false,
|
||||
feather: 0,
|
||||
),
|
||||
);
|
||||
await settled();
|
||||
});
|
||||
await check('editedExportPixelsAudioAndPersistence', () async {
|
||||
final exportedUri = await export('edited');
|
||||
result['editedExport'] = exportedUri.toFilePath();
|
||||
result['audioRmsRatio'] = await verifyEditedExport(
|
||||
runtime,
|
||||
edited: exportedUri,
|
||||
baseline: baseline,
|
||||
);
|
||||
await session.flush();
|
||||
expect(session.saveError, isNull);
|
||||
final projectPath = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.activeProject!
|
||||
.path;
|
||||
final edits = await savedEdits.capture(
|
||||
projectPath,
|
||||
timelineId,
|
||||
session,
|
||||
sequence,
|
||||
);
|
||||
expect(
|
||||
((edits['clips'] as List).single as Map)['parameters'],
|
||||
hasLength(greaterThanOrEqualTo(3)),
|
||||
);
|
||||
result['savedTimelineId'] = timelineId;
|
||||
result['savedProject'] = projectPath;
|
||||
});
|
||||
result['passed'] = true;
|
||||
} catch (error, stack) {
|
||||
checks.add({
|
||||
'stage': stage,
|
||||
'passed': false,
|
||||
'error': '$error',
|
||||
'stack': '$stack',
|
||||
});
|
||||
debugPrint('REAL_MEDIA_FAILED $stage $error\n$stack');
|
||||
}
|
||||
final after = await file.stat();
|
||||
result['sourceUnchanged'] =
|
||||
before.size == after.size && before.modified == after.modified;
|
||||
if (result['sourceUnchanged'] != true) result['passed'] = false;
|
||||
save();
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
if (testedTimeline != null) {
|
||||
await container.read(previewControllerRegistryProvider).invalidate((
|
||||
projectId,
|
||||
testedTimeline,
|
||||
));
|
||||
}
|
||||
releaseTimeline?.call();
|
||||
}
|
||||
container.dispose();
|
||||
disposed = true;
|
||||
await savedEdits.verify(
|
||||
wait: tester.pump,
|
||||
onVerified: (projectPath, timelineId, edits) {
|
||||
final result = results.singleWhere(
|
||||
(r) =>
|
||||
r['savedProject'] == projectPath &&
|
||||
r['savedTimelineId'] == timelineId,
|
||||
);
|
||||
result['savedEditsIdenticalAfterReopen'] = true;
|
||||
save();
|
||||
},
|
||||
);
|
||||
expect(
|
||||
results.where((file) => file['passed'] != true).toList(),
|
||||
isEmpty,
|
||||
reason: 'See ${report.file.path}',
|
||||
);
|
||||
}, timeout: const Timeout(Duration(minutes: 90)));
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
import '../test/support/preview_fixture.dart';
|
||||
import 'support/native_media_fixture.dart';
|
||||
|
||||
RationalTime t(num value) => RationalTime((value * 1000).round(), 1000);
|
||||
ParameterCurveDto scalar(String id, double value) => ParameterCurveDto(
|
||||
definition: TimelineParameterDefinition(
|
||||
id: id,
|
||||
defaultValue: value,
|
||||
minimum: -96,
|
||||
maximum: 100,
|
||||
),
|
||||
);
|
||||
ElementDto clip(
|
||||
String id, {
|
||||
num source = 1,
|
||||
num duration = 2,
|
||||
num offset = 0,
|
||||
List<ParameterCurveDto> parameters = const [],
|
||||
}) => ElementDto(
|
||||
id: ElementId(id),
|
||||
structure: ElementStructure.content,
|
||||
payloadRef: PayloadRef('source'),
|
||||
duration: t(duration),
|
||||
parallelOffset: t(offset),
|
||||
parameters: parameters,
|
||||
sourceRange: TimeRange(start: t(source), duration: t(duration)),
|
||||
mediaRange: TimeRange(start: t(0), duration: t(30)),
|
||||
);
|
||||
TimelineDto complexTimeline() => TimelineDto(
|
||||
id: SequenceId('one'),
|
||||
format: TimelineFormat.fps30,
|
||||
primaryStorylineId: StorylineId('primary'),
|
||||
storylines: [
|
||||
StorylineDto(
|
||||
id: StorylineId('primary'),
|
||||
elementIds: [ElementId('box'), ElementId('a'), ElementId('b')],
|
||||
),
|
||||
StorylineDto(
|
||||
id: StorylineId('inside'),
|
||||
timeDomain: TimeDomain.parallel,
|
||||
elementIds: [ElementId('lower'), ElementId('upper')],
|
||||
),
|
||||
],
|
||||
elements: [
|
||||
ElementDto(
|
||||
id: ElementId('box'),
|
||||
structure: ElementStructure.container,
|
||||
duration: t(2),
|
||||
containerStorylineId: StorylineId('inside'),
|
||||
containerViewMode: ContainerViewMode.fixedRange,
|
||||
sourceRange: TimeRange(start: t(0), duration: t(1)),
|
||||
parameters: [
|
||||
scalar('opacity', .9),
|
||||
ParameterCurveDto(
|
||||
definition: TimelineParameterDefinition(
|
||||
id: 'gain',
|
||||
defaultValue: -6,
|
||||
minimum: -96,
|
||||
maximum: 12,
|
||||
semantic: ParameterSemantic.audioGainDb,
|
||||
),
|
||||
),
|
||||
],
|
||||
retimeSegments: [
|
||||
RetimeSegmentDto(
|
||||
projectDuration: t(1),
|
||||
sourceStart: t(0),
|
||||
sourceDelta: t(1),
|
||||
),
|
||||
RetimeSegmentDto(
|
||||
projectDuration: t(.5),
|
||||
sourceStart: t(1),
|
||||
sourceDelta: t(0),
|
||||
),
|
||||
RetimeSegmentDto(
|
||||
projectDuration: t(.5),
|
||||
sourceStart: t(1),
|
||||
sourceDelta: t(-.5),
|
||||
),
|
||||
],
|
||||
),
|
||||
clip('lower'),
|
||||
clip(
|
||||
'upper',
|
||||
source: 2,
|
||||
offset: .25,
|
||||
parameters: [
|
||||
scalar('opacity', .5),
|
||||
scalar('scale.x', .7),
|
||||
scalar('scale.y', .7),
|
||||
],
|
||||
),
|
||||
clip('a', source: 3),
|
||||
clip('b', source: 5),
|
||||
clip(
|
||||
'attached',
|
||||
source: 7,
|
||||
duration: 3,
|
||||
parameters: [scalar('opacity', .7)],
|
||||
),
|
||||
],
|
||||
connections: [
|
||||
ConnectionDto(
|
||||
id: ConnectionId('link'),
|
||||
anchorId: ElementId('b'),
|
||||
targetId: ElementId('attached'),
|
||||
anchorTime: t(1),
|
||||
targetTime: t(0),
|
||||
side: ConnectionSide.above,
|
||||
),
|
||||
],
|
||||
transitions: [
|
||||
TransitionDto(
|
||||
id: TransitionId('mix'),
|
||||
storylineId: StorylineId('primary'),
|
||||
leftId: ElementId('a'),
|
||||
rightId: ElementId('b'),
|
||||
duration: t(1),
|
||||
startOffset: t(-.5),
|
||||
timing: TransitionTiming.mediaHandles,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
testWidgets(
|
||||
'native nested composition, reverse, freeze, transition and attached tail survive edits',
|
||||
(tester) async {
|
||||
final mediaFile = await nativeMediaFixture();
|
||||
final fixture = await createPreviewFixture(
|
||||
mediaFile.uri,
|
||||
hasAudio: true,
|
||||
timelineOverride: complexTimeline(),
|
||||
renderSize: {'width': 320, 'height': 180},
|
||||
);
|
||||
final preview = PreviewController(
|
||||
timeline: fixture.timeline,
|
||||
activeSequence: () => fixture.timeline.activeSequenceId,
|
||||
viewForSequence: fixture.timeline.view,
|
||||
runtime: CutdexRuntime(),
|
||||
);
|
||||
addTearDown(() async {
|
||||
await preview.close();
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
await preview.initialize();
|
||||
expect(preview.error, isNull);
|
||||
expect(preview.durationTick, TimelineClock.ticksPerSecond * 8);
|
||||
final ids = (fixture.workspace.project!.info.id, 'project');
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
editorTimelineProvider(
|
||||
ids.$1,
|
||||
ids.$2,
|
||||
).overrideWith((ref) async => fixture.timeline),
|
||||
editorPreviewProvider(
|
||||
ids.$1,
|
||||
ids.$2,
|
||||
).overrideWith((ref) async => preview),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: EditorPreviewPanel(projectId: ids.$1, timelineId: ids.$2),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final view = fixture.timeline.view(SequenceId('one'));
|
||||
final nativePreview = find.byType(
|
||||
Platform.isIOS ? UiKitView : AppKitView,
|
||||
);
|
||||
expect(nativePreview, findsOneWidget);
|
||||
final nativeView = tester.state(nativePreview);
|
||||
for (final at in [
|
||||
.1,
|
||||
.8,
|
||||
1.1,
|
||||
1.4,
|
||||
1.6,
|
||||
1.9,
|
||||
2.2,
|
||||
3.6,
|
||||
4.0,
|
||||
4.4,
|
||||
5.2,
|
||||
6.5,
|
||||
7.8,
|
||||
.2,
|
||||
]) {
|
||||
view.seekTo((at * TimelineClock.ticksPerSecond).round());
|
||||
await Future<void>.delayed(const Duration(milliseconds: 400));
|
||||
await tester.pump();
|
||||
var snapshot = await preview.session!.refresh();
|
||||
for (
|
||||
var attempt = 0;
|
||||
attempt < 100 && (snapshot.position.seconds - at).abs() > .1;
|
||||
attempt++
|
||||
) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
await tester.pump();
|
||||
snapshot = await preview.session!.refresh();
|
||||
}
|
||||
expect(preview.error, isNull, reason: 'Seek to $at');
|
||||
expect(snapshot.position.seconds, closeTo(at, .1));
|
||||
expect(tester.state(nativePreview), same(nativeView));
|
||||
}
|
||||
view.seekTo((3.8 * TimelineClock.ticksPerSecond).round());
|
||||
await Future<void>.delayed(const Duration(milliseconds: 400));
|
||||
await preview.togglePlayback();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 550));
|
||||
await preview.togglePlayback();
|
||||
expect(
|
||||
(await preview.session!.refresh()).position.seconds,
|
||||
greaterThan(4),
|
||||
);
|
||||
view.setSelection([
|
||||
view.version.kernelVersion.query().elementById(ElementId('b'))!,
|
||||
]);
|
||||
view.seekTo(TimelineClock.ticksPerSecond * 5);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 300));
|
||||
for (final edit in [view.cutSelectionAtPlayhead, view.undo, view.redo]) {
|
||||
edit();
|
||||
for (var i = 0; i < 600; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
await tester.pump();
|
||||
if (!preview.busy) break;
|
||||
}
|
||||
expect(preview.busy, isFalse);
|
||||
expect(preview.error, isNull);
|
||||
expect(preview.durationTick, TimelineClock.ticksPerSecond * 8);
|
||||
expect(
|
||||
(await preview.session!.refresh()).position.seconds,
|
||||
closeTo(5, .1),
|
||||
);
|
||||
expect(tester.state(nativePreview), same(nativeView));
|
||||
}
|
||||
final runtime = CutdexRuntime();
|
||||
final preparedMedia = await prepareEditorMedia(
|
||||
session: fixture.timeline,
|
||||
sequence: SequenceId('one'),
|
||||
version: fixture.timeline.persistence
|
||||
.timeline(SequenceId('one'))
|
||||
.current,
|
||||
probe: runtime.probe,
|
||||
unknownVideoColorSpace: const PreviewPolicy().unknownVideoColorSpace,
|
||||
);
|
||||
final execution = const ExecutionCompiler().compile(
|
||||
ExecutionInput(
|
||||
timeline: fixture.timeline.persistence.timeline(SequenceId('one')),
|
||||
media: preparedMedia.bindings,
|
||||
renderSize: RenderSize(320, 180),
|
||||
toneMapping: RenderToneMapping.headroom(source: 4, target: 1),
|
||||
),
|
||||
);
|
||||
final exported = await preview.session!.export(
|
||||
execution.plan,
|
||||
File('${fixture.directory.path}/complex.mp4').uri,
|
||||
);
|
||||
final result = await runtime.probe(
|
||||
MediaReference(id: 'exported', uri: exported),
|
||||
);
|
||||
expect(result.duration.seconds, closeTo(8, .05));
|
||||
expect(result.videoTrackCount, 1);
|
||||
expect(result.audioTrackCount, 1);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
skip: !hasNativeMediaFixture,
|
||||
);
|
||||
testWidgets(
|
||||
'native image and empty compositing canvas execute without video media',
|
||||
(tester) async {
|
||||
final directory = await Directory.systemTemp.createTemp(
|
||||
'cutdex-image-preview-',
|
||||
);
|
||||
final recorder = ui.PictureRecorder();
|
||||
ui.Canvas(recorder)
|
||||
.drawColor(const ui.Color(0xffff0000), ui.BlendMode.src);
|
||||
final picture = recorder.endRecording();
|
||||
final image = await picture.toImage(64, 64);
|
||||
final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
final file = File('${directory.path}/red.png');
|
||||
await file.writeAsBytes(bytes!.buffer.asUint8List());
|
||||
picture.dispose();
|
||||
image.dispose();
|
||||
final runtime = CutdexRuntime();
|
||||
final session = await runtime.createSession();
|
||||
addTearDown(() async {
|
||||
await session.close();
|
||||
await directory.delete(recursive: true);
|
||||
});
|
||||
final duration = MediaTime(1, 1);
|
||||
final range = MediaRange(start: MediaTime(0, 1), duration: duration);
|
||||
final group = RenderCompositingGroup(
|
||||
id: 'black',
|
||||
backgroundOpacity: RenderAutomation(
|
||||
target: 'opacity',
|
||||
defaultValue: .5,
|
||||
),
|
||||
);
|
||||
final plan = ExecutionPlan(
|
||||
revision: 0,
|
||||
duration: duration,
|
||||
renderSize: RenderSize(64, 64),
|
||||
frameDuration: MediaTime(1, 30),
|
||||
media: [MediaReference(id: 'image', uri: file.uri, isImage: true)],
|
||||
visualLayers: [
|
||||
VisualLayer(
|
||||
id: 'image',
|
||||
mediaId: 'image',
|
||||
sourceRange: range,
|
||||
timelineRange: range,
|
||||
),
|
||||
VisualLayer.canvas(
|
||||
id: 'canvas',
|
||||
timelineRange: range,
|
||||
lane: 1,
|
||||
groups: [group],
|
||||
),
|
||||
],
|
||||
);
|
||||
await session.load(plan);
|
||||
await session.seek(MediaTime(1, 2));
|
||||
expect((await session.refresh()).position.seconds, closeTo(.5, .05));
|
||||
final exported = await session.export(
|
||||
plan,
|
||||
File('${directory.path}/image.mp4').uri,
|
||||
);
|
||||
final cover = await runtime.thumbnail(
|
||||
ThumbnailRequest(
|
||||
media: MediaReference(id: 'out', uri: exported),
|
||||
),
|
||||
);
|
||||
final codec = await ui.instantiateImageCodec(cover.data);
|
||||
final frame = await codec.getNextFrame();
|
||||
final pixels = await frame.image.toByteData(
|
||||
format: ui.ImageByteFormat.rawRgba,
|
||||
);
|
||||
// A 50% opaque black group over red must darken the image, even with no children.
|
||||
final center =
|
||||
(frame.image.height ~/ 2 * frame.image.width +
|
||||
frame.image.width ~/ 2) *
|
||||
4;
|
||||
expect(pixels!.getUint8(center), inInclusiveRange(165, 200));
|
||||
expect(pixels.getUint8(center + 1), lessThan(10));
|
||||
expect(pixels.getUint8(center + 2), lessThan(10));
|
||||
frame.image.dispose();
|
||||
codec.dispose();
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
|
||||
// Opt-in cadence measurements from the mounted macOS source-preview renderer.
|
||||
// Requires macOS 14.4+, CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1 in the host environment,
|
||||
// and CUTDEX_VALIDATION_ROOT / CUTDEX_VALIDATION_SOURCE Dart defines.
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex/features/media/media_panel.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/media_file_extensions.dart';
|
||||
import 'package:cutdex/workspace/preview_target.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
void main() {
|
||||
const root = String.fromEnvironment('CUTDEX_VALIDATION_ROOT');
|
||||
const sourceDirectory = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE');
|
||||
const configured = root != '' && sourceDirectory != '';
|
||||
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
// The host activates this diagnostic window through macOS accessibility.
|
||||
// Establish its OS-owned semantics handle before testWidgets records handles
|
||||
// and resets node IDs; forcing a test-owned handle first conflicts with that
|
||||
// late activation in Flutter's native accessibility bridge.
|
||||
setUpAll(() async {
|
||||
if (!configured) return;
|
||||
debugPrint('APP_CADENCE_WAIT_FOR_VISIBLE_HOST_WINDOW');
|
||||
final deadline = DateTime.now().add(const Duration(seconds: 60));
|
||||
while (!binding.semanticsEnabled) {
|
||||
if (DateTime.now().isAfter(deadline)) {
|
||||
throw StateError(
|
||||
'Activate the cadence window through macOS accessibility',
|
||||
);
|
||||
}
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
}
|
||||
});
|
||||
testWidgets(
|
||||
'Downloads: mounted source-preview cadence',
|
||||
(tester) async {
|
||||
const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER');
|
||||
const measurementSeconds = int.fromEnvironment(
|
||||
'CUTDEX_CADENCE_SECONDS',
|
||||
defaultValue: 8,
|
||||
);
|
||||
expect(root, isNotEmpty);
|
||||
expect(sourceDirectory, isNotEmpty);
|
||||
expect(measurementSeconds, greaterThan(0));
|
||||
Directory(root).createSync(recursive: true);
|
||||
final paths =
|
||||
Directory(sourceDirectory)
|
||||
.listSync()
|
||||
.whereType<File>()
|
||||
.map((file) => file.path)
|
||||
.where(
|
||||
(path) =>
|
||||
mediaKindForPath(path) == 'video' &&
|
||||
(filter.isEmpty ||
|
||||
filter
|
||||
.split(',')
|
||||
.any((value) => p.basename(path).contains(value))),
|
||||
)
|
||||
.toList()
|
||||
..sort();
|
||||
expect(paths, isNotEmpty, reason: 'No matching video sources');
|
||||
final results = <Map<String, Object?>>[];
|
||||
final report = File(p.join(root, 'app-cadence.json'));
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
final container = ProviderContainer(
|
||||
overrides: [appDatabaseProvider.overrideWithValue(database)],
|
||||
);
|
||||
addTearDown(() async {
|
||||
container.dispose();
|
||||
await database.close();
|
||||
});
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
expect(
|
||||
await projects.open(
|
||||
p.join(
|
||||
root,
|
||||
'Cadence-${DateTime.now().millisecondsSinceEpoch}.cutdex',
|
||||
),
|
||||
name: '素材预览帧率验证',
|
||||
initialTimelineName: '01',
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
final state = container.read(projectsProvider).requireValue;
|
||||
final projectId = state.activeProject!.id;
|
||||
final timelineId = state.timeline!.id;
|
||||
void save() => report.writeAsStringSync(
|
||||
const JsonEncoder.withIndent(' ').convert({
|
||||
'files': results,
|
||||
'scope':
|
||||
'Actual Cutdex source-preview panel, full source resolution, 30fps plan; '
|
||||
'AVSampleBufferVideoRenderer counters on a mounted native view; adaptive warmup and up to ${measurementSeconds}s measurement per segment',
|
||||
}),
|
||||
);
|
||||
Future<void> until(bool Function() predicate, String name) async {
|
||||
final deadline = DateTime.now().add(const Duration(seconds: 40));
|
||||
while (!predicate()) {
|
||||
if (DateTime.now().isAfter(deadline)) {
|
||||
throw StateError('Timed out: $name');
|
||||
}
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
}
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<void> advance(Duration duration) async {
|
||||
final watch = Stopwatch()..start();
|
||||
while (watch.elapsed < duration) {
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
}
|
||||
}
|
||||
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 300,
|
||||
child: MediaPanel(
|
||||
projectId: projectId,
|
||||
grid: true,
|
||||
onGridChanged: (_) {},
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: EditorPreviewPanel(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
const channel = MethodChannel('cutdex_runtime');
|
||||
Future<List<Map<String, Object?>>> metrics() async =>
|
||||
(await channel.invokeListMethod<Object?>('_debugPreviewCadence'))!
|
||||
.map((item) => Map<String, Object?>.from(item! as Map))
|
||||
.toList();
|
||||
Future<void> nativeDrop(String path, int session) async {
|
||||
for (final phase in ['enter', 'drop']) {
|
||||
final done = Completer<void>();
|
||||
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
|
||||
'cutdex_native/file_drop/media-library',
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
MethodCall('event', {
|
||||
'phase': phase,
|
||||
'session': session,
|
||||
'x': 0.0,
|
||||
'y': 0.0,
|
||||
'files': [
|
||||
{'path': path},
|
||||
],
|
||||
}),
|
||||
),
|
||||
(_) => done.complete(),
|
||||
);
|
||||
await done.future;
|
||||
await tester.pump();
|
||||
}
|
||||
}
|
||||
|
||||
for (var index = 0; index < paths.length; index++) {
|
||||
final path = paths[index];
|
||||
final before = File(path).statSync();
|
||||
final segments = <Map<String, Object?>>[];
|
||||
final result = <String, Object?>{
|
||||
'path': path,
|
||||
'segments': segments,
|
||||
'passed': false,
|
||||
};
|
||||
results.add(result);
|
||||
save();
|
||||
debugPrint(
|
||||
'APP_CADENCE ${index + 1}/${paths.length} ${p.basename(path)}',
|
||||
);
|
||||
final target = container.read(
|
||||
previewTargetProvider(projectId, timelineId),
|
||||
);
|
||||
try {
|
||||
await nativeDrop(path, index + 1);
|
||||
await until(
|
||||
() => container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.assets
|
||||
.any((asset) => asset.name == p.basename(path)),
|
||||
'import',
|
||||
);
|
||||
final asset = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.assets
|
||||
.firstWhere((asset) => asset.name == p.basename(path));
|
||||
await target.openSource(asset);
|
||||
final source = target.source!;
|
||||
await until(() => source.canPlay, 'source ready');
|
||||
final duration = source.durationTick / TimelineClock.ticksPerSecond;
|
||||
final warmupSeconds = duration < measurementSeconds + 3 ? 0.2 : 2.0;
|
||||
final measuredSeconds = math.min(
|
||||
measurementSeconds.toDouble(),
|
||||
duration - warmupSeconds - 0.4,
|
||||
);
|
||||
expect(
|
||||
measuredSeconds,
|
||||
greaterThan(1),
|
||||
reason: 'Cadence needs a source longer than 1.6 seconds',
|
||||
);
|
||||
final latestStart = math.max(
|
||||
0.0,
|
||||
duration - warmupSeconds - measuredSeconds - 0.3,
|
||||
);
|
||||
for (final positionSeconds in [
|
||||
duration > 80 ? math.min(60.0, latestStart) : 0.0,
|
||||
math.min(duration / 2, latestStart),
|
||||
]) {
|
||||
final position = (positionSeconds * TimelineClock.ticksPerSecond)
|
||||
.round();
|
||||
await source.control(
|
||||
SourcePreviewAction.seek,
|
||||
at: CommandTime(position, TimelineClock.ticksPerSecond),
|
||||
);
|
||||
await until(
|
||||
() => !source.busy && source.canPlay,
|
||||
'source seek settled',
|
||||
);
|
||||
expect(source.error, isNull);
|
||||
await tester.pump();
|
||||
await tester.tap(find.byTooltip('播放'));
|
||||
await until(() => source.playing, 'playing');
|
||||
await advance(
|
||||
Duration(microseconds: (warmupSeconds * 1e6).round()),
|
||||
);
|
||||
var first = (await metrics()).singleWhere(
|
||||
(m) => m['mounted'] == true && (m['rate']! as num) > 0,
|
||||
);
|
||||
final visibilityDeadline = DateTime.now().add(
|
||||
const Duration(seconds: 40),
|
||||
);
|
||||
while (first['windowVisible'] != true ||
|
||||
first['windowOccluded'] != false) {
|
||||
if (DateTime.now().isAfter(visibilityDeadline)) {
|
||||
throw StateError(
|
||||
'Preview window must be visible for cadence measurement',
|
||||
);
|
||||
}
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
first = (await metrics()).singleWhere(
|
||||
(m) => m['id'] == first['id'],
|
||||
);
|
||||
}
|
||||
final watch = Stopwatch()..start();
|
||||
await advance(
|
||||
Duration(microseconds: (measuredSeconds * 1e6).round()),
|
||||
);
|
||||
final last = (await metrics()).singleWhere(
|
||||
(m) => m['id'] == first['id'],
|
||||
);
|
||||
watch.stop();
|
||||
await tester.tap(find.byTooltip('暂停播放'));
|
||||
await until(() => !source.playing && !source.busy, 'paused');
|
||||
expect(source.error, isNull);
|
||||
final paused = (await metrics()).singleWhere(
|
||||
(m) => m['id'] == first['id'],
|
||||
);
|
||||
await advance(const Duration(milliseconds: 500));
|
||||
final afterPause = (await metrics()).singleWhere(
|
||||
(m) => m['id'] == first['id'],
|
||||
);
|
||||
final seconds = watch.elapsedMicroseconds / 1e6;
|
||||
final frames =
|
||||
(last['frames']! as num).toInt() -
|
||||
(first['frames']! as num).toInt();
|
||||
final dropped =
|
||||
(last['dropped']! as num).toInt() -
|
||||
(first['dropped']! as num).toInt();
|
||||
final segment = <String, Object?>{
|
||||
'positionSeconds': position / TimelineClock.ticksPerSecond,
|
||||
'warmupSeconds': warmupSeconds,
|
||||
'sourceDurationSeconds': duration,
|
||||
'measurementSeconds': seconds,
|
||||
'rendererTotalFrames': frames,
|
||||
'rendererDroppedFrames': dropped,
|
||||
'rendererFPS': frames / seconds,
|
||||
'displayedFPS': (frames - dropped) / seconds,
|
||||
'clockAdvanceRatio':
|
||||
((last['clockSeconds']! as num) -
|
||||
(first['clockSeconds']! as num)) /
|
||||
seconds,
|
||||
'accumulatedFrameDelaySeconds':
|
||||
(last['delay']! as num) - (first['delay']! as num),
|
||||
'viewWidth': first['width'],
|
||||
'viewHeight': first['height'],
|
||||
'windowVisibleAtStart': first['windowVisible'],
|
||||
'windowVisibleAtEnd': last['windowVisible'],
|
||||
'windowOccludedAtStart': first['windowOccluded'],
|
||||
'windowOccludedAtEnd': last['windowOccluded'],
|
||||
'measurementValid':
|
||||
first['windowVisible'] == true &&
|
||||
last['windowVisible'] == true &&
|
||||
first['windowOccluded'] == false &&
|
||||
last['windowOccluded'] == false,
|
||||
'pauseClockAdvanceSeconds':
|
||||
(afterPause['clockSeconds']! as num) -
|
||||
(paused['clockSeconds']! as num),
|
||||
'pauseRendererFrameAdvance':
|
||||
(afterPause['frames']! as num) - (paused['frames']! as num),
|
||||
'pausedRate': afterPause['rate'],
|
||||
};
|
||||
segments.add(segment);
|
||||
debugPrint('APP_CADENCE_SEGMENT ${index + 1} $segment');
|
||||
save();
|
||||
}
|
||||
result['keepsUp'] =
|
||||
segments.length == 2 &&
|
||||
segments.every(
|
||||
(segment) =>
|
||||
(segment['displayedFPS']! as num) >= 28.5 &&
|
||||
segment['measurementValid'] == true &&
|
||||
(segment['rendererDroppedFrames']! as num) == 0 &&
|
||||
(segment['clockAdvanceRatio']! as num) >= 0.95 &&
|
||||
(segment['pauseClockAdvanceSeconds']! as num).abs() <
|
||||
0.001 &&
|
||||
(segment['pauseRendererFrameAdvance']! as num) == 0 &&
|
||||
(segment['pausedRate']! as num) == 0,
|
||||
);
|
||||
result['passed'] = true;
|
||||
} catch (error, stack) {
|
||||
result['error'] = '$error';
|
||||
debugPrint('APP_CADENCE_ERROR $error\n$stack');
|
||||
} finally {
|
||||
await target.closeSource();
|
||||
await tester.pump();
|
||||
}
|
||||
final after = File(path).statSync();
|
||||
result['sourceUnchanged'] =
|
||||
before.size == after.size && before.modified == after.modified;
|
||||
save();
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
expect(
|
||||
results
|
||||
.where(
|
||||
(r) =>
|
||||
r['passed'] != true ||
|
||||
r['keepsUp'] != true ||
|
||||
r['sourceUnchanged'] != true,
|
||||
)
|
||||
.toList(),
|
||||
isEmpty,
|
||||
reason: report.path,
|
||||
);
|
||||
},
|
||||
skip: !configured,
|
||||
semanticsEnabled: false,
|
||||
timeout: const Timeout(Duration(minutes: 10)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,821 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
|
||||
// Opt-in, real desktop runtime validation. Source files are referenced, never copied.
|
||||
// CUTDEX_VALIDATION_KIND=audio also checks source-preview transport and mute controls.
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex/features/media/media_asset_drag.dart';
|
||||
import 'package:cutdex/features/media/media_panel.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/properties/properties_panel.dart';
|
||||
import 'package:cutdex/features/timeline/timeline_panel.dart';
|
||||
import 'package:cutdex/features/timeline/timeline_external_drop_target.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/media_file_extensions.dart';
|
||||
import 'package:cutdex/workspace/preview_target.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/layout.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
void main() {
|
||||
const root = String.fromEnvironment('CUTDEX_VALIDATION_ROOT');
|
||||
const sourceDirectory = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE');
|
||||
const configured = root != '' && sourceDirectory != '';
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
testWidgets(
|
||||
'Downloads: native drop, timeline drag and editing with real playback',
|
||||
(tester) async {
|
||||
const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER');
|
||||
const directDrop = bool.fromEnvironment('CUTDEX_VALIDATION_DIRECT_DROP');
|
||||
const dropOnly = bool.fromEnvironment('CUTDEX_VALIDATION_DROP_ONLY');
|
||||
const kind = String.fromEnvironment(
|
||||
'CUTDEX_VALIDATION_KIND',
|
||||
defaultValue: 'video',
|
||||
);
|
||||
expect(kind, anyOf('video', 'audio'));
|
||||
Directory(root).createSync(recursive: true);
|
||||
final paths =
|
||||
Directory(sourceDirectory)
|
||||
.listSync()
|
||||
.whereType<File>()
|
||||
.map((file) => file.path)
|
||||
.where(
|
||||
(path) =>
|
||||
mediaKindForPath(path) == kind &&
|
||||
(filter.isEmpty ||
|
||||
filter
|
||||
.split(',')
|
||||
.any((value) => p.basename(path).contains(value))),
|
||||
)
|
||||
.toList()
|
||||
..sort();
|
||||
expect(paths, isNotEmpty);
|
||||
// AppKit menu tracking consumes physical input outside the test binding.
|
||||
// Exercise the existing Flutter menu fallback; native playback stays real.
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
const MethodChannel('cutdex_native/context_menu'),
|
||||
(_) async => throw MissingPluginException(),
|
||||
);
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
const MethodChannel('cutdex_native/context_menu'),
|
||||
null,
|
||||
),
|
||||
);
|
||||
final results = <Map<String, Object?>>[];
|
||||
final report = File(
|
||||
p.join(
|
||||
root,
|
||||
kind == 'audio'
|
||||
? 'audio-editor-results.json'
|
||||
: 'downloads-editor-results.json',
|
||||
),
|
||||
);
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
final container = ProviderContainer(
|
||||
overrides: [appDatabaseProvider.overrideWithValue(database)],
|
||||
);
|
||||
addTearDown(() async {
|
||||
container.dispose();
|
||||
await database.close();
|
||||
});
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
final projectPath = p.join(
|
||||
root,
|
||||
'Downloads-${DateTime.now().millisecondsSinceEpoch}.cutdex',
|
||||
);
|
||||
void save() => report.writeAsStringSync(
|
||||
const JsonEncoder.withIndent(' ').convert({
|
||||
'validatedAt': DateTime.now().toIso8601String(),
|
||||
'sourceDirectory': sourceDirectory,
|
||||
'projectPath': projectPath,
|
||||
'directDrop': directDrop,
|
||||
'dropOnly': dropOnly,
|
||||
'kind': kind,
|
||||
'method':
|
||||
'Real ${Platform.operatingSystem} application and native playback runtime; '
|
||||
'${directDrop ? 'injected native file-drop events directly on the timeline' : 'injected native file-drop events into the library, pointer drag from media tiles'}, '
|
||||
'toolbar and property slider. AppKit menu bridge disabled only in test '
|
||||
'to exercise production Flutter context-menu fallback.',
|
||||
'files': results,
|
||||
}),
|
||||
);
|
||||
Future<void> until(
|
||||
bool Function() predicate,
|
||||
String stage, {
|
||||
int seconds = 40,
|
||||
}) async {
|
||||
final deadline = DateTime.now().add(Duration(seconds: seconds));
|
||||
while (!predicate()) {
|
||||
if (DateTime.now().isAfter(deadline)) {
|
||||
throw StateError('Timed out: $stage');
|
||||
}
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
}
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<void> nativeDrop(
|
||||
String phase,
|
||||
String path,
|
||||
int session, {
|
||||
bool timeline = false,
|
||||
Offset position = Offset.zero,
|
||||
}) async {
|
||||
final done = Completer<void>();
|
||||
// The same entry point receives Finder NSDraggingInfo events in production.
|
||||
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
|
||||
timeline
|
||||
? 'cutdex_native/file_drop/timeline'
|
||||
: 'cutdex_native/file_drop/media-library',
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
MethodCall('event', {
|
||||
'phase': phase,
|
||||
'session': session,
|
||||
'x': position.dx,
|
||||
'y': position.dy,
|
||||
'files': [
|
||||
{'path': path},
|
||||
],
|
||||
}),
|
||||
),
|
||||
(_) => done.complete(),
|
||||
);
|
||||
await done.future;
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
expect(
|
||||
await projects.open(
|
||||
projectPath,
|
||||
name: 'Downloads 操作验证',
|
||||
initialTimelineName: '01',
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
final projectId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.activeProject!
|
||||
.id;
|
||||
for (var index = 0; index < paths.length; index++) {
|
||||
final path = paths[index];
|
||||
final before = File(path).statSync();
|
||||
final checks = <Map<String, Object?>>[];
|
||||
final result = <String, Object?>{
|
||||
'path': path,
|
||||
'checks': checks,
|
||||
'passed': false,
|
||||
};
|
||||
results.add(result);
|
||||
save();
|
||||
String stage = 'setup';
|
||||
Future<void> check(String name, Future<void> Function() action) async {
|
||||
stage = name;
|
||||
debugPrint(
|
||||
'DOWNLOADS_WORKFLOW ${index + 1}/${paths.length} $name ${p.basename(path)}',
|
||||
);
|
||||
await action();
|
||||
checks.add({'stage': name, 'passed': true});
|
||||
save();
|
||||
}
|
||||
|
||||
try {
|
||||
if (index > 0) {
|
||||
expect(
|
||||
await projects.createTimeline(
|
||||
name: '${index + 1}'.padLeft(2, '0'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
}
|
||||
final timelineId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timeline!
|
||||
.id;
|
||||
final ids = (projectId, timelineId);
|
||||
result['timelineId'] = timelineId;
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 300,
|
||||
child: MediaPanel(
|
||||
projectId: projectId,
|
||||
grid: true,
|
||||
onGridChanged: (_) {},
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: EditorPreviewPanel(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 320,
|
||||
child: EditorPropertiesPanel(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: 330,
|
||||
child: EditorTimelinePanel(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 400));
|
||||
final session = await container.read(
|
||||
editorTimelineProvider(ids.$1, ids.$2).future,
|
||||
);
|
||||
final sequence = session.activeSequenceId!;
|
||||
final view = session.view(sequence);
|
||||
if (directDrop) {
|
||||
await check('nativeDropDirectlyIntoTimeline', () async {
|
||||
final rect = tester.getRect(
|
||||
find.byType(TimelineExternalDropTarget),
|
||||
);
|
||||
final position = Offset(
|
||||
24,
|
||||
view.camera.screenYForWorld(
|
||||
view.geometry.primaryTop +
|
||||
view.geometry.primaryHeight / 2 +
|
||||
(kind == 'audio' ? 100 : 0),
|
||||
TimelineViewportRect(width: rect.width, height: rect.height),
|
||||
),
|
||||
);
|
||||
await nativeDrop(
|
||||
'enter',
|
||||
path,
|
||||
index + 1,
|
||||
timeline: true,
|
||||
position: position,
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
await nativeDrop(
|
||||
'drop',
|
||||
path,
|
||||
index + 1,
|
||||
timeline: true,
|
||||
position: position,
|
||||
);
|
||||
await until(
|
||||
() => session.sequenceDurationTicks(sequence) > 0,
|
||||
'direct timeline insert',
|
||||
);
|
||||
expect(
|
||||
container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.assets
|
||||
.any((asset) => asset.name == p.basename(path)),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
await check('nativeDropIntoMediaLibrary', () async {
|
||||
await nativeDrop('enter', path, index + 1);
|
||||
await nativeDrop('drop', path, index + 1);
|
||||
await until(
|
||||
() => container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.assets
|
||||
.any((a) => a.name == p.basename(path)),
|
||||
'import',
|
||||
);
|
||||
});
|
||||
final asset = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.assets
|
||||
.firstWhere((a) => a.name == p.basename(path));
|
||||
await check('sourcePreviewSeekPlayPause', () async {
|
||||
final target = container.read(
|
||||
previewTargetProvider(ids.$1, ids.$2),
|
||||
);
|
||||
try {
|
||||
await target.openSource(asset);
|
||||
final source = target.source!;
|
||||
await until(() => source.canPlay, 'source ready');
|
||||
expect(source.audioOnly, kind == 'audio');
|
||||
for (final position in [0, source.durationTick ~/ 2]) {
|
||||
await source.control(
|
||||
SourcePreviewAction.seek,
|
||||
at: CommandTime(position, TimelineClock.ticksPerSecond),
|
||||
);
|
||||
await until(
|
||||
() => !source.busy && source.canPlay,
|
||||
'source seek settled',
|
||||
);
|
||||
expect(source.error, isNull);
|
||||
await tester.pump();
|
||||
await tester.tap(find.byTooltip('播放'));
|
||||
await until(
|
||||
() =>
|
||||
source.playing &&
|
||||
source.positionTick >
|
||||
position + TimelineClock.ticksPerSecond ~/ 5,
|
||||
'source play advances',
|
||||
);
|
||||
expect(source.error, isNull);
|
||||
await until(
|
||||
() => find.byTooltip('暂停播放').evaluate().isNotEmpty,
|
||||
'source pause button',
|
||||
);
|
||||
await tester.tap(find.byTooltip('暂停播放'));
|
||||
await until(
|
||||
() => !source.playing && !source.busy,
|
||||
'source pause',
|
||||
);
|
||||
final paused = source.positionTick;
|
||||
for (var i = 0; i < 4; i++) {
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
}
|
||||
expect(
|
||||
(source.positionTick - paused).abs(),
|
||||
lessThan(TimelineClock.ticksPerSecond ~/ 10),
|
||||
);
|
||||
expect(source.error, isNull);
|
||||
}
|
||||
} finally {
|
||||
await target.closeSource();
|
||||
await tester.pump();
|
||||
}
|
||||
});
|
||||
await check('pointerDragIntoTimeline', () async {
|
||||
final tile = find.byWidgetPredicate(
|
||||
(widget) =>
|
||||
widget is Draggable<MediaAssetDrag> &&
|
||||
widget.data?.assetId == asset.id,
|
||||
);
|
||||
// Scroll the media panel as needed without opening a source preview.
|
||||
final scroll = tester.state<ScrollableState>(
|
||||
find
|
||||
.descendant(
|
||||
of: find.byType(MediaPanel),
|
||||
matching: find.byType(Scrollable),
|
||||
)
|
||||
.last,
|
||||
);
|
||||
scroll.position.jumpTo(0);
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
for (
|
||||
var attempt = 0;
|
||||
tile.evaluate().isEmpty && attempt < 20;
|
||||
attempt++
|
||||
) {
|
||||
scroll.position.jumpTo(
|
||||
math.min(
|
||||
scroll.position.maxScrollExtent,
|
||||
scroll.position.pixels + 180,
|
||||
),
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 150));
|
||||
}
|
||||
expect(tile, findsOneWidget);
|
||||
await tester.ensureVisible(tile);
|
||||
await tester.pump();
|
||||
final surfaceRect = tester.getRect(
|
||||
find.byKey(const Key('editor-timeline-surface')),
|
||||
);
|
||||
final viewport = TimelineViewportRect(
|
||||
width: surfaceRect.width,
|
||||
height: surfaceRect.height,
|
||||
);
|
||||
final destination =
|
||||
surfaceRect.topLeft +
|
||||
Offset(
|
||||
24,
|
||||
view.camera.screenYForWorld(
|
||||
view.geometry.primaryTop +
|
||||
view.geometry.primaryHeight / 2 +
|
||||
(kind == 'audio' ? 100 : 0),
|
||||
viewport,
|
||||
),
|
||||
);
|
||||
final gesture = await tester.startGesture(
|
||||
tester.getCenter(tile),
|
||||
kind: PointerDeviceKind.mouse,
|
||||
);
|
||||
await gesture.moveBy(const Offset(24, 0));
|
||||
await tester.pump();
|
||||
await gesture.moveTo(destination);
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
final drop = tester.state<TimelineExternalDropTargetState>(
|
||||
find.byType(TimelineExternalDropTarget),
|
||||
);
|
||||
debugPrint(
|
||||
'DOWNLOADS_DRAG preview=${drop.hasPreview} enabled=${drop.enabled} error=${drop.error} placement=${drop.placementError} duration=${drop.preparedMedia?.metadata.duration}',
|
||||
);
|
||||
await gesture.up();
|
||||
await until(
|
||||
() => session.sequenceDurationTicks(sequence) > 0,
|
||||
'timeline insert',
|
||||
);
|
||||
});
|
||||
}
|
||||
final query = session.persistence.timeline(sequence).current.query();
|
||||
final original = session.persistence
|
||||
.timeline(sequence)
|
||||
.exportDto()
|
||||
.elements
|
||||
.map((dto) => query.elementById(dto.id)!)
|
||||
.firstWhere((h) {
|
||||
final record = query.element(h);
|
||||
return record.payloadRef != null &&
|
||||
session.payloadFor(record.payloadRef!)?.type == kind;
|
||||
});
|
||||
final clipId = query.element(original).id;
|
||||
final originalDuration = query.element(original).duration;
|
||||
result['originalDurationTicks'] = originalDuration;
|
||||
await check('sourceDurationPreserved', () async {
|
||||
final source = await container
|
||||
.read(runtimeConnectionProvider)
|
||||
.probe(
|
||||
MediaReference(id: 'duration-check', uri: File(path).uri),
|
||||
);
|
||||
final numerator = BigInt.from(source.duration.numerator);
|
||||
final denominator = BigInt.from(source.duration.denominator);
|
||||
final expectedTicks =
|
||||
numerator *
|
||||
BigInt.from(TimelineClock.ticksPerSecond) ~/
|
||||
denominator;
|
||||
expect(BigInt.from(originalDuration), expectedTicks);
|
||||
expect(query.element(original).sourceDuration, originalDuration);
|
||||
expect(query.element(original).mediaDuration, originalDuration);
|
||||
result['nativeSourceDuration'] = source.duration.toMap();
|
||||
result['discardedTickFraction'] =
|
||||
'${numerator * BigInt.from(TimelineClock.ticksPerSecond) % denominator}/$denominator';
|
||||
});
|
||||
final frameTicks = view.format.frameGrid.quantumTicks;
|
||||
final splitTick = math.max(
|
||||
frameTicks,
|
||||
((math.min(4 * TimelineClock.ticksPerSecond, originalDuration / 2) /
|
||||
frameTicks)
|
||||
.floor()) *
|
||||
frameTicks,
|
||||
);
|
||||
await until(
|
||||
() =>
|
||||
container
|
||||
.read(editorPreviewProvider(ids.$1, ids.$2))
|
||||
.asData
|
||||
?.value
|
||||
?.ready ==
|
||||
true,
|
||||
'preview ready',
|
||||
);
|
||||
var preview = container
|
||||
.read(editorPreviewProvider(ids.$1, ids.$2))
|
||||
.requireValue!;
|
||||
container.read(previewTargetProvider(ids.$1, ids.$2)).showTimeline();
|
||||
Future<void> seek(int tick) async {
|
||||
var waits = 0;
|
||||
debugPrint('DOWNLOADS_SEEK stage=$stage tick=$tick');
|
||||
await until(() {
|
||||
// Import/autosave can replace the preview binding. Follow the
|
||||
// live provider rather than waiting on a disposed controller.
|
||||
final active = container
|
||||
.read(editorPreviewProvider(ids.$1, ids.$2))
|
||||
.asData
|
||||
?.value;
|
||||
if (active != null && active.error != null) {
|
||||
throw StateError('Native preview: ${active.error}');
|
||||
}
|
||||
if (active == null || !active.ready || active.busy) {
|
||||
if (waits++ % 50 == 0) {
|
||||
debugPrint(
|
||||
'DOWNLOADS_WAIT ready=${active?.ready} busy=${active?.busy} '
|
||||
'playing=${active?.playing} native=${active?.session?.snapshot?.state}',
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
preview = active;
|
||||
return true;
|
||||
}, 'timeline preview ready for seek');
|
||||
expect(preview.error, isNull);
|
||||
await preview.controlPreview(
|
||||
sequence,
|
||||
PreviewAction.seek,
|
||||
at: CommandTime(tick, TimelineClock.ticksPerSecond),
|
||||
);
|
||||
await until(() => !preview.busy, 'seek');
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
|
||||
Future<void> playPause() async {
|
||||
final start = preview.positionTick;
|
||||
await tester.tap(find.byTooltip('播放'));
|
||||
await until(
|
||||
() =>
|
||||
preview.playing &&
|
||||
preview.positionTick >
|
||||
start +
|
||||
math.min(
|
||||
TimelineClock.ticksPerSecond ~/ 4,
|
||||
math.max(
|
||||
frameTicks,
|
||||
(session.sequenceDurationTicks(sequence) -
|
||||
start) ~/
|
||||
3,
|
||||
),
|
||||
),
|
||||
'play advances',
|
||||
);
|
||||
expect(preview.error, isNull);
|
||||
await until(
|
||||
() => find.byTooltip('暂停播放').evaluate().isNotEmpty,
|
||||
'pause button renders',
|
||||
seconds: 5,
|
||||
);
|
||||
await tester.tap(find.byTooltip('暂停播放'));
|
||||
await until(() => !preview.playing && !preview.busy, 'pause');
|
||||
final paused = preview.positionTick;
|
||||
await tester.pump(const Duration(milliseconds: 400));
|
||||
expect(
|
||||
(preview.positionTick - paused).abs(),
|
||||
lessThan(TimelineClock.ticksPerSecond ~/ 10),
|
||||
);
|
||||
expect(preview.error, isNull);
|
||||
final state = preview.queryPreview(sequence);
|
||||
(result.putIfAbsent(
|
||||
'playbackSamples',
|
||||
() => <Map<String, Object?>>[],
|
||||
) as List).add({
|
||||
'startTick': start,
|
||||
'pausedTick': paused,
|
||||
'presentedVideoFrames': state.presentedVideoFrameCount,
|
||||
'droppedVideoFrames': state.droppedVideoFrameCount,
|
||||
'maximumVideoFrameGapMs': state.maximumVideoFrameGapMs,
|
||||
});
|
||||
}
|
||||
|
||||
await check('playAndPause', () async {
|
||||
await seek(0);
|
||||
await playPause();
|
||||
});
|
||||
if (dropOnly) {
|
||||
await check('seekImportedClip', () async {
|
||||
await seek(
|
||||
math.min(
|
||||
2 * TimelineClock.ticksPerSecond,
|
||||
originalDuration ~/ 2,
|
||||
),
|
||||
);
|
||||
await playPause();
|
||||
});
|
||||
await check('saveImportedClip', () async {
|
||||
await session.flush();
|
||||
expect(session.saveError, isNull);
|
||||
final saved = session.persistence.timeline(sequence).exportDto();
|
||||
final content = saved.elements
|
||||
.where((element) => element.payloadRef != null)
|
||||
.single;
|
||||
expect(
|
||||
TimelineClock.standard.toTicks(content.duration),
|
||||
originalDuration,
|
||||
);
|
||||
expect(content.sourceRange.duration, content.duration);
|
||||
expect(content.mediaRange!.duration, content.duration);
|
||||
});
|
||||
result['passed'] = true;
|
||||
final after = File(path).statSync();
|
||||
result['sourceUnchanged'] =
|
||||
before.size == after.size && before.modified == after.modified;
|
||||
if (result['sourceUnchanged'] != true) result['passed'] = false;
|
||||
save();
|
||||
continue;
|
||||
}
|
||||
await check('splitFromToolbar', () async {
|
||||
preview.selectVisual(clipId);
|
||||
await seek(splitTick);
|
||||
await tester.pump();
|
||||
await tester.tap(find.byTooltip('在播放头处分割'));
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
final q = session.persistence.timeline(sequence).current.query();
|
||||
final clips = session.persistence
|
||||
.timeline(sequence)
|
||||
.exportDto()
|
||||
.elements
|
||||
.map((dto) => q.elementById(dto.id)!)
|
||||
.where((h) {
|
||||
final record = q.element(h);
|
||||
return record.payloadRef != null &&
|
||||
session.payloadFor(record.payloadRef!)?.type == kind;
|
||||
})
|
||||
.toList();
|
||||
expect(clips.length, 2);
|
||||
expect(q.element(q.elementById(clipId)!).duration, splitTick);
|
||||
expect(
|
||||
clips.map((h) => q.element(h).duration).reduce((a, b) => a + b),
|
||||
originalDuration,
|
||||
);
|
||||
await seek(
|
||||
math.max(0, splitTick - TimelineClock.ticksPerSecond ~/ 10),
|
||||
);
|
||||
await playPause();
|
||||
});
|
||||
await check('speedFromPropertySlider', () async {
|
||||
preview.selectVisual(clipId);
|
||||
await tester.pump();
|
||||
await tester.tap(find.byKey(const ValueKey('property-tab-speed')));
|
||||
await tester.pump();
|
||||
final slider = find.descendant(
|
||||
of: find.byKey(const Key('clip-speed-slider')),
|
||||
matching: find.byType(Slider),
|
||||
);
|
||||
expect(slider, findsOneWidget);
|
||||
// Drag the native editor's logarithmic slider, verify the actual retime map.
|
||||
for (final requestedSpeed in [2.0, 0.5]) {
|
||||
final rect = tester.getRect(slider);
|
||||
final oldValue = tester.widget<Slider>(slider).value;
|
||||
final pos = (math.log(requestedSpeed) / math.ln10 + 1) / 3;
|
||||
final gesture = await tester.startGesture(
|
||||
Offset(
|
||||
rect.left + 12 + (rect.width - 24) * oldValue,
|
||||
rect.center.dy,
|
||||
),
|
||||
);
|
||||
await gesture.moveTo(
|
||||
Offset(
|
||||
rect.left + 12 + (rect.width - 24) * pos,
|
||||
rect.center.dy,
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await gesture.up();
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
final q = session.persistence.timeline(sequence).current.query();
|
||||
final record = q.element(q.elementById(clipId)!);
|
||||
final speed = session.clipSpeed(record)!;
|
||||
expect(speed, closeTo(requestedSpeed, 0.05));
|
||||
expect(
|
||||
record.duration,
|
||||
closeTo(
|
||||
splitTick / requestedSpeed,
|
||||
TimelineClock.ticksPerSecond / 4,
|
||||
),
|
||||
);
|
||||
(result.putIfAbsent('testedSpeeds', () => <double>[]) as List)
|
||||
.add(speed);
|
||||
await seek(0);
|
||||
await playPause();
|
||||
}
|
||||
});
|
||||
if (kind == 'audio') {
|
||||
await check('muteAndUnmuteFromProperties', () async {
|
||||
preview.selectVisual(clipId);
|
||||
await tester.pump();
|
||||
await tester.tap(
|
||||
find.byKey(const ValueKey('property-tab-audio')),
|
||||
);
|
||||
await tester.pump();
|
||||
for (final muted in [true, false]) {
|
||||
await tester.tap(find.byKey(const Key('audio-mute')));
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
final q = session.persistence
|
||||
.timeline(sequence)
|
||||
.current
|
||||
.query();
|
||||
expect(
|
||||
ClipAudioGain.fromRecord(q.element(q.elementById(clipId)!))
|
||||
.muted,
|
||||
muted,
|
||||
);
|
||||
await seek(0);
|
||||
await playPause();
|
||||
}
|
||||
});
|
||||
} else if (session.hasAudio(query.element(original))) {
|
||||
await check('detachAudioFromContextMenu', () async {
|
||||
await seek(0);
|
||||
preview.selectVisual(clipId);
|
||||
await tester.pump();
|
||||
final surface = find.byKey(const Key('editor-timeline-surface'));
|
||||
final bounds = tester.getRect(surface);
|
||||
final frame = view.project(
|
||||
TimelineViewportRect(
|
||||
width: bounds.width,
|
||||
height: bounds.height,
|
||||
),
|
||||
);
|
||||
// First primary video spans the first two seconds in the visible viewport.
|
||||
final clipIndex = Iterable<int>.generate(frame.length)
|
||||
.firstWhere((i) {
|
||||
final handle = view.elementForIdentity(frame.identityAt(i));
|
||||
return handle != null &&
|
||||
view.version.kernelVersion.query().element(handle).id ==
|
||||
clipId;
|
||||
});
|
||||
final clipBounds = view.presentationBoundsAt(frame, clipIndex);
|
||||
final point =
|
||||
bounds.topLeft +
|
||||
Offset(
|
||||
math.max(clipBounds.left + 15, 20),
|
||||
clipBounds.center.dy,
|
||||
);
|
||||
final contextGesture = await tester.startGesture(
|
||||
point,
|
||||
kind: PointerDeviceKind.mouse,
|
||||
buttons: kSecondaryMouseButton,
|
||||
);
|
||||
await contextGesture.up();
|
||||
await until(
|
||||
() => find.text('分离音频').evaluate().isNotEmpty,
|
||||
'audio menu',
|
||||
);
|
||||
await tester.tap(find.text('分离音频'));
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
final q = session.persistence.timeline(sequence).current.query();
|
||||
final video = q.element(q.elementById(clipId)!);
|
||||
expect(ClipAudioGain.fromRecord(video).muted, isTrue);
|
||||
expect(ClipAudioGain.isDetached(video), isTrue);
|
||||
final audio = session.persistence
|
||||
.timeline(sequence)
|
||||
.exportDto()
|
||||
.elements
|
||||
.map((dto) => q.element(q.elementById(dto.id)!))
|
||||
.where(
|
||||
(r) =>
|
||||
r.payloadRef != null &&
|
||||
session.payloadFor(r.payloadRef!)?.type == 'audio',
|
||||
)
|
||||
.toList();
|
||||
expect(audio.length, 1);
|
||||
expect(audio.single.duration, video.duration);
|
||||
expect(audio.single.sourceDuration, video.sourceDuration);
|
||||
expect(
|
||||
session.clipSpeed(audio.single),
|
||||
closeTo(session.clipSpeed(video)!, 0.001),
|
||||
);
|
||||
result['detachedAudioId'] = audio.single.id.value;
|
||||
await seek(0);
|
||||
await playPause();
|
||||
});
|
||||
}
|
||||
await check('save', () async {
|
||||
await session.flush();
|
||||
expect(session.saveError, isNull);
|
||||
});
|
||||
result['passed'] = true;
|
||||
} catch (error, stack) {
|
||||
checks.add({'stage': stage, 'passed': false, 'error': '$error'});
|
||||
debugPrint('DOWNLOADS_WORKFLOW FAILED $stage $error\n$stack');
|
||||
}
|
||||
final after = File(path).statSync();
|
||||
result['sourceUnchanged'] =
|
||||
before.size == after.size && before.modified == after.modified;
|
||||
if (result['sourceUnchanged'] != true) result['passed'] = false;
|
||||
save();
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
expect(
|
||||
results.where((r) => r['passed'] != true).toList(),
|
||||
isEmpty,
|
||||
reason: 'See ${report.path}',
|
||||
);
|
||||
},
|
||||
skip: !configured,
|
||||
timeout: const Timeout(Duration(minutes: 30)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/diagnostics/app_diagnostics.dart';
|
||||
import 'package:cutdex/diagnostics/diagnostic_store.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/properties/speed_properties.dart';
|
||||
import 'package:cutdex/features/timeline/timeline_panel.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import 'support/native_media_fixture.dart';
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
const output = String.fromEnvironment('CUTDEX_TEST_REPORT');
|
||||
const cadence = bool.fromEnvironment('CUTDEX_DIAGNOSTIC_CADENCE');
|
||||
testWidgets(
|
||||
'real editor diagnostics and logging performance comparison',
|
||||
(tester) async {
|
||||
expect(
|
||||
kProfileMode || cadence,
|
||||
isTrue,
|
||||
reason: 'Use Profile for Flutter timings, or Debug with opt-in native cadence.',
|
||||
);
|
||||
final root = Directory(output)..createSync(recursive: true);
|
||||
final source = await nativeMediaFixture();
|
||||
final originalSource = await source.stat();
|
||||
final store = DiagnosticStore(
|
||||
Directory(
|
||||
p.join(root.path, 'logs-${DateTime.now().microsecondsSinceEpoch}'),
|
||||
),
|
||||
);
|
||||
final diagnostics = AppDiagnostics(
|
||||
store,
|
||||
metadata: {
|
||||
'validation': 'real editor',
|
||||
'platform': Platform.operatingSystem,
|
||||
'buildMode': kProfileMode ? 'profile' : 'debug',
|
||||
},
|
||||
);
|
||||
await diagnostics.readApplicationInfo();
|
||||
var logging = true;
|
||||
var measuring = false;
|
||||
final recordCosts = <int>[];
|
||||
void sink(DiagnosticEvent event) {
|
||||
if (!logging) return;
|
||||
final watch = Stopwatch()..start();
|
||||
diagnostics.event(event);
|
||||
if (measuring) recordCosts.add(watch.elapsedMicroseconds);
|
||||
}
|
||||
|
||||
final runtime = CutdexRuntime(diagnostics: sink);
|
||||
final probe = await runtime.probe(
|
||||
MediaReference(id: 'media', uri: source.uri),
|
||||
);
|
||||
expect(probe.videoTrackCount, greaterThan(0));
|
||||
expect(probe.duration.seconds, greaterThanOrEqualTo(25));
|
||||
final sequence = SequenceId('sequence');
|
||||
final clipId = ElementId('clip');
|
||||
final duration = RationalTime(
|
||||
probe.duration.numerator,
|
||||
probe.duration.denominator,
|
||||
);
|
||||
final project = await ProjectFile.create(
|
||||
Directory(
|
||||
p.join(
|
||||
root.path,
|
||||
'Editing-${DateTime.now().microsecondsSinceEpoch}.cutdex',
|
||||
),
|
||||
),
|
||||
name: 'Diagnostic validation',
|
||||
);
|
||||
await project.saveAsset(
|
||||
AssetDocument(
|
||||
id: 'media',
|
||||
name: 'Generated test media',
|
||||
storage: AssetStorage.external,
|
||||
location: source.uri.toString(),
|
||||
),
|
||||
);
|
||||
await project.saveTimeline(
|
||||
TimelineDocument(
|
||||
id: 'timeline',
|
||||
name: 'Diagnostic validation',
|
||||
defaultSequenceId: sequence,
|
||||
settings: {
|
||||
'renderSize': {'width': 1280, 'height': 720},
|
||||
},
|
||||
payloads: [
|
||||
PayloadDocument(
|
||||
id: 'video',
|
||||
type: 'video',
|
||||
assetIds: ['media'],
|
||||
data: {
|
||||
'videoTrackIndex': 0,
|
||||
if (probe.audioTrackCount > 0) 'audioTrackIndex': 0,
|
||||
},
|
||||
),
|
||||
],
|
||||
sequences: [
|
||||
TimelineDto(
|
||||
id: sequence,
|
||||
format: TimelineFormat.fps30,
|
||||
primaryStorylineId: StorylineId('primary'),
|
||||
storylines: [
|
||||
StorylineDto(id: StorylineId('primary'), elementIds: [clipId]),
|
||||
],
|
||||
elements: [
|
||||
ElementDto(
|
||||
id: clipId,
|
||||
structure: ElementStructure.content,
|
||||
duration: duration,
|
||||
sourceRange: TimeRange(
|
||||
start: RationalTime.zero,
|
||||
duration: duration,
|
||||
),
|
||||
mediaRange: TimeRange(
|
||||
start: RationalTime.zero,
|
||||
duration: duration,
|
||||
),
|
||||
payloadRef: PayloadRef('video'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
final session = _FaultingSession(
|
||||
document: await project.loadTimeline('timeline'),
|
||||
persistence: await project.openTimelineSaveSession('timeline'),
|
||||
assetUris: {'media': source.uri},
|
||||
diagnostics: (event) => withDiagnosticContext({
|
||||
'projectId': project.info.id,
|
||||
}, () => reportDiagnostic(sink, event)),
|
||||
);
|
||||
final preview = PreviewController(
|
||||
timeline: session,
|
||||
runtime: runtime,
|
||||
activeSequence: () => session.activeSequenceId,
|
||||
viewForSequence: session.view,
|
||||
);
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
final frames = _FrameMeasurements();
|
||||
addTearDown(() async {
|
||||
SchedulerBinding.instance.removeTimingsCallback(frames.accept);
|
||||
session.fault = null;
|
||||
await preview.close();
|
||||
await session.close();
|
||||
await project.close();
|
||||
await store.flush();
|
||||
await database.close();
|
||||
});
|
||||
SchedulerBinding.instance.addTimingsCallback(frames.accept);
|
||||
final faults = <Map<String, Object?>>[];
|
||||
final runs = <Map<String, Object?>>[];
|
||||
final report = File(p.join(root.path, 'results.json'));
|
||||
var passed = false;
|
||||
Map<String, Object?>? savedState;
|
||||
void save() => report.writeAsStringSync(
|
||||
const JsonEncoder.withIndent(' ').convert({
|
||||
'at': DateTime.now().toUtc().toIso8601String(),
|
||||
'passed': passed,
|
||||
'platform': Platform.operatingSystem,
|
||||
'dart': Platform.version,
|
||||
'mode': kProfileMode ? 'profile' : 'debug',
|
||||
'source': {
|
||||
'path': source.path,
|
||||
'durationSeconds': probe.duration.seconds,
|
||||
'bytes': originalSource.size,
|
||||
},
|
||||
'method':
|
||||
'Mounted production timeline toolbar, speed slider and native playback; '
|
||||
'controlled failures at the authoritative commit boundary. Same-build alternating '
|
||||
'diagnostic sink on/off; bounded 16 ms pumps during playback. '
|
||||
'Flutter timings exclude independently rendered platform-view video. '
|
||||
'Native cadence is available only in opt-in macOS Debug builds.',
|
||||
'faults': faults,
|
||||
'runs': runs,
|
||||
'savedState': savedState,
|
||||
'storage': {
|
||||
'flushes': store.eventFlushes,
|
||||
'bytes': store.eventBytesWritten,
|
||||
'dropped': store.dropped,
|
||||
'droppedErrors': store.droppedErrors,
|
||||
'writeFailures': store.writeFailures,
|
||||
},
|
||||
}),
|
||||
);
|
||||
save();
|
||||
await preview.initialize();
|
||||
expect(preview.error, isNull);
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
appDatabaseProvider.overrideWithValue(database),
|
||||
editorTimelineProvider(
|
||||
project.info.id,
|
||||
'timeline',
|
||||
).overrideWith((ref) async => session),
|
||||
editorPreviewProvider(
|
||||
project.info.id,
|
||||
'timeline',
|
||||
).overrideWith((ref) async => preview),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: EditorPreviewPanel(
|
||||
projectId: project.info.id,
|
||||
timelineId: 'timeline',
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 280,
|
||||
child: SingleChildScrollView(
|
||||
child: SpeedProperties(
|
||||
session: session,
|
||||
sequence: sequence,
|
||||
clip: clipId,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: 260,
|
||||
child: EditorTimelinePanel(
|
||||
projectId: project.info.id,
|
||||
timelineId: 'timeline',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(RuntimePreview), findsOneWidget);
|
||||
final view = session.view(sequence);
|
||||
Future<void> until(bool Function() predicate, String label) async {
|
||||
final watch = Stopwatch()..start();
|
||||
while (!predicate()) {
|
||||
if (preview.error != null) {
|
||||
throw StateError('$label: ${preview.error}');
|
||||
}
|
||||
if (watch.elapsed > const Duration(seconds: 30)) {
|
||||
throw StateError('Timed out: $label');
|
||||
}
|
||||
await tester.pump(const Duration(milliseconds: 30));
|
||||
}
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<void> settle() async {
|
||||
await until(
|
||||
() =>
|
||||
preview.canPlay &&
|
||||
!preview.busy &&
|
||||
preview.durationTick == session.sequenceDurationTicks(sequence),
|
||||
'native preview',
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
|
||||
Future<void> selectAt(double seconds) async {
|
||||
final query = session.persistence.timeline(sequence).current.query();
|
||||
view.setSelection([query.elementById(clipId)!]);
|
||||
view.seekTo((seconds * TimelineClock.ticksPerSecond).round());
|
||||
await settle();
|
||||
}
|
||||
|
||||
Future<void> slider(double speed) async {
|
||||
final finder = find.descendant(
|
||||
of: find.byKey(const Key('clip-speed-slider')),
|
||||
matching: find.byType(Slider),
|
||||
);
|
||||
expect(finder, findsOneWidget);
|
||||
final rect = tester.getRect(finder);
|
||||
final position = (math.log(speed) / math.ln10 + 1) / 3;
|
||||
final old = tester.widget<Slider>(finder).value;
|
||||
final start = Offset(
|
||||
rect.left + 12 + (rect.width - 24) * old,
|
||||
rect.center.dy,
|
||||
);
|
||||
final end = Offset(
|
||||
rect.left + 12 + (rect.width - 24) * position,
|
||||
rect.center.dy,
|
||||
);
|
||||
final gesture = await tester.startGesture(start);
|
||||
for (var i = 1; i <= 12; i++) {
|
||||
await gesture.moveTo(Offset.lerp(start, end, i / 12)!);
|
||||
await tester.pump(const Duration(milliseconds: 16));
|
||||
}
|
||||
await gesture.up();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<void> edit(String operation) async {
|
||||
switch (operation) {
|
||||
case 'split':
|
||||
await tester.tap(find.byTooltip('在播放头处分割'));
|
||||
case 'trimLeft':
|
||||
await tester.tap(find.byKey(const ValueKey('timeline-trim-left')));
|
||||
case 'trimRight':
|
||||
await tester.tap(find.byKey(const ValueKey('timeline-trim-right')));
|
||||
case 'setSpeed':
|
||||
await slider(2);
|
||||
}
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> exported() async => jsonDecode(
|
||||
await (await diagnostics.export(
|
||||
Directory(p.join(root.path, 'exports')),
|
||||
)).readAsString(),
|
||||
) as Map<String, dynamic>;
|
||||
for (final operation in ['split', 'trimLeft', 'trimRight', 'setSpeed']) {
|
||||
await selectAt(5);
|
||||
final before = session.version;
|
||||
final marker = 'CONTROLLED_${operation.toUpperCase()}_STACK';
|
||||
session.fault = marker;
|
||||
try {
|
||||
await withDiagnosticContext({
|
||||
'validationScenario': operation,
|
||||
}, () => edit(operation));
|
||||
} finally {
|
||||
session.fault = null;
|
||||
}
|
||||
expect(session.version, before);
|
||||
final events = (await exported())['events'] as List;
|
||||
final event = events.singleWhere(
|
||||
(e) =>
|
||||
(e as Map)['level'] == 'error' &&
|
||||
(e['context'] as Map)['validationScenario'] == operation,
|
||||
) as Map;
|
||||
expect(
|
||||
event['operation'],
|
||||
operation.startsWith('trim') ? 'trim' : operation,
|
||||
);
|
||||
final context = event['context'] as Map;
|
||||
expect(context['clipIds'], ['clip']);
|
||||
expect(context['timelineId'], 'timeline');
|
||||
expect(context['projectId'], project.info.id);
|
||||
expect(context['operationId'], isNotEmpty);
|
||||
expect(context['versionBefore'], before);
|
||||
expect(context['versionAfter'], before);
|
||||
expect(event['stackTrace'], marker);
|
||||
faults.add({
|
||||
'operation': operation,
|
||||
'passed': true,
|
||||
'operationId': context['operationId'],
|
||||
'stack': event['stackTrace'],
|
||||
});
|
||||
// Recovery uses the same UI path with the failure removed.
|
||||
await edit(operation);
|
||||
expect(session.version, isNot(before));
|
||||
await settle();
|
||||
await tester.tap(find.byTooltip('撤销'));
|
||||
await tester.pump();
|
||||
await settle();
|
||||
await session.flush();
|
||||
save();
|
||||
}
|
||||
Future<Map<String, Object?>> nativeCadence() async {
|
||||
if (!cadence) return {};
|
||||
final values = (await const MethodChannel('cutdex_runtime')
|
||||
.invokeListMethod<Object?>('_debugPreviewCadence'))!;
|
||||
return values
|
||||
.map((v) => Map<String, Object?>.from(v! as Map))
|
||||
.singleWhere(
|
||||
(v) => v['mounted'] == true && (v['rate']! as num) > 0,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> observe(Duration duration) async {
|
||||
final watch = Stopwatch()..start();
|
||||
while (watch.elapsed < duration) {
|
||||
await tester.pump(const Duration(milliseconds: 16));
|
||||
}
|
||||
}
|
||||
|
||||
// Warm the native decoders and editor before collecting comparisons.
|
||||
await selectAt(0);
|
||||
await preview.togglePlayback();
|
||||
await observe(const Duration(seconds: 2));
|
||||
await preview.togglePlayback();
|
||||
for (var round = 0; round < 6; round++) {
|
||||
// Three paired comparisons; alternate pair order to reduce order bias.
|
||||
logging = const [false, true, true, false, false, true][round];
|
||||
await selectAt(5);
|
||||
await session.flush();
|
||||
await store.flush();
|
||||
final initialFlushes = store.eventFlushes;
|
||||
final initialBytes = store.eventBytesWritten;
|
||||
recordCosts.clear();
|
||||
frames.start();
|
||||
measuring = true;
|
||||
final watch = Stopwatch()..start();
|
||||
for (final operation in ['split', 'trimLeft', 'trimRight']) {
|
||||
await selectAt(5);
|
||||
await edit(operation);
|
||||
await settle();
|
||||
await tester.tap(find.byTooltip('撤销'));
|
||||
await tester.pump();
|
||||
await settle();
|
||||
}
|
||||
await slider(2);
|
||||
await settle();
|
||||
final query = session.persistence.timeline(sequence).current.query();
|
||||
expect(
|
||||
session.clipSpeed(query.element(query.elementById(clipId)!)),
|
||||
closeTo(2, 0.05),
|
||||
);
|
||||
await selectAt(0);
|
||||
await preview.togglePlayback();
|
||||
await observe(const Duration(milliseconds: 500));
|
||||
final firstNative = await nativeCadence();
|
||||
final firstPosition =
|
||||
(await preview.session!.refresh()).position.seconds;
|
||||
final playbackWatch = Stopwatch()..start();
|
||||
await observe(const Duration(seconds: 3));
|
||||
final lastNative = await nativeCadence();
|
||||
final lastPosition =
|
||||
(await preview.session!.refresh()).position.seconds;
|
||||
playbackWatch.stop();
|
||||
await preview.togglePlayback();
|
||||
expect(lastPosition, greaterThan(firstPosition + 1));
|
||||
expect(preview.error, isNull);
|
||||
await tester.tap(find.text('1×'));
|
||||
await settle();
|
||||
await session.flush();
|
||||
await store.flush();
|
||||
await observe(const Duration(milliseconds: 150));
|
||||
measuring = false;
|
||||
final timing = frames.stop();
|
||||
if (kProfileMode) expect(timing['count'], greaterThan(10));
|
||||
final native = <String, Object?>{};
|
||||
if (cadence) {
|
||||
for (final value in [firstNative, lastNative]) {
|
||||
expect(value['windowVisible'], isTrue);
|
||||
expect(value['windowOccluded'], isFalse);
|
||||
}
|
||||
final frames =
|
||||
(lastNative['frames']! as num) - (firstNative['frames']! as num);
|
||||
final dropped =
|
||||
(lastNative['dropped']! as num) -
|
||||
(firstNative['dropped']! as num);
|
||||
native.addAll({
|
||||
'viewWidth': firstNative['width'],
|
||||
'viewHeight': firstNative['height'],
|
||||
'windowVisible': firstNative['windowVisible'],
|
||||
'windowOccluded': firstNative['windowOccluded'],
|
||||
'frames': frames,
|
||||
'dropped': dropped,
|
||||
'rendererFps': frames / (playbackWatch.elapsedMicroseconds / 1e6),
|
||||
'displayedFps':
|
||||
(frames - dropped) / (playbackWatch.elapsedMicroseconds / 1e6),
|
||||
});
|
||||
expect(frames, greaterThan(0));
|
||||
}
|
||||
runs.add({
|
||||
'round': round,
|
||||
'logging': logging,
|
||||
'elapsedMs': watch.elapsedMicroseconds / 1000,
|
||||
'flutterFrames': timing,
|
||||
'nativeCadence': native,
|
||||
'playbackSeconds': playbackWatch.elapsedMicroseconds / 1e6,
|
||||
'playbackClockAdvanceSeconds': lastPosition - firstPosition,
|
||||
'logCalls': recordCosts.length,
|
||||
'recordP95Us': _percentile(recordCosts, .95),
|
||||
'flushes': store.eventFlushes - initialFlushes,
|
||||
'logBytes': store.eventBytesWritten - initialBytes,
|
||||
});
|
||||
expect(store.dropped, 0);
|
||||
expect(store.writeFailures, 0);
|
||||
save();
|
||||
}
|
||||
logging = true;
|
||||
await session.flush();
|
||||
final stored = await project.loadTimeline('timeline');
|
||||
final savedClip = stored.sequences.single.elements.singleWhere(
|
||||
(e) => e.id == clipId,
|
||||
);
|
||||
expect(savedClip.duration, duration);
|
||||
expect(savedClip.sourceRange.duration, duration);
|
||||
final bundle = await exported();
|
||||
final errors = (bundle['events'] as List)
|
||||
.where((e) => (e as Map)['level'] == 'error')
|
||||
.toList();
|
||||
expect(
|
||||
errors,
|
||||
hasLength(4),
|
||||
reason: 'Only the four controlled failures are expected.',
|
||||
);
|
||||
savedState = {
|
||||
'passed': true,
|
||||
'durationSeconds': savedClip.duration.seconds,
|
||||
'sourceDurationSeconds': savedClip.sourceRange.duration.seconds,
|
||||
'errorEvents': errors.length,
|
||||
};
|
||||
final afterSource = await source.stat();
|
||||
expect(afterSource.size, originalSource.size);
|
||||
expect(afterSource.modified, originalSource.modified);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
passed = true;
|
||||
save();
|
||||
},
|
||||
skip: output.isEmpty || !hasNativeMediaFixture,
|
||||
timeout: const Timeout(Duration(minutes: 10)),
|
||||
);
|
||||
}
|
||||
|
||||
class _FaultingSession extends EditorTimelineSession {
|
||||
_FaultingSession({
|
||||
required super.document,
|
||||
required super.persistence,
|
||||
required super.assetUris,
|
||||
super.diagnostics,
|
||||
});
|
||||
String? fault;
|
||||
@override
|
||||
T commit<T>(SequenceId? sequence, T Function() action) {
|
||||
if (fault case final marker?) {
|
||||
Error.throwWithStackTrace(
|
||||
StateError('Controlled edit failure'),
|
||||
StackTrace.fromString(marker),
|
||||
);
|
||||
}
|
||||
return super.commit(sequence, action);
|
||||
}
|
||||
}
|
||||
|
||||
final class _FrameMeasurements {
|
||||
final _frames = <FrameTiming>[];
|
||||
var _active = false;
|
||||
void accept(List<FrameTiming> frames) {
|
||||
if (_active) _frames.addAll(frames);
|
||||
}
|
||||
|
||||
void start() {
|
||||
_frames.clear();
|
||||
_active = true;
|
||||
}
|
||||
|
||||
Map<String, Object?> stop() {
|
||||
_active = false;
|
||||
final build = _frames.map((f) => f.buildDuration.inMicroseconds).toList();
|
||||
final raster = _frames.map((f) => f.rasterDuration.inMicroseconds).toList();
|
||||
return {
|
||||
'count': _frames.length,
|
||||
'buildP95Us': _percentile(build, .95),
|
||||
'rasterP95Us': _percentile(raster, .95),
|
||||
'buildOver16ms': build.where((v) => v > 16667).length,
|
||||
'rasterOver16ms': raster.where((v) => v > 16667).length,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
int? _percentile(List<int> values, double fraction) {
|
||||
if (values.isEmpty) return null;
|
||||
final ordered = [...values]..sort();
|
||||
return ordered[(ordered.length * fraction).ceil() - 1];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import 'complex_preview_test.dart' as composition;
|
||||
import 'picture_keyframes_test.dart' as keyframes;
|
||||
import 'playback_app_acceptance_test.dart' as application;
|
||||
import 'preview_drag_timing_test.dart' as dragging;
|
||||
import 'preview_test.dart' as playback;
|
||||
import 'timeline_thumbnail_timing_test.dart' as thumbnails;
|
||||
|
||||
/// Runs the shared native media regressions in one installation on an iPhone.
|
||||
void main() {
|
||||
playback.main();
|
||||
composition.main();
|
||||
keyframes.main();
|
||||
thumbnails.main();
|
||||
dragging.main();
|
||||
application.main();
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/features/timeline/timeline_drop_preparation.dart';
|
||||
import 'package:cutdex/features/timeline/timeline_external_drop_target.dart';
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
import '../test/support/preview_fixture.dart';
|
||||
import 'support/native_media_fixture.dart';
|
||||
|
||||
class _DropProjects extends Projects {
|
||||
_DropProjects(this.workspace, this.session, this.asset);
|
||||
final ProjectWorkspace workspace;
|
||||
final EditorTimelineSession session;
|
||||
final AssetDocument asset;
|
||||
String get _projectId => workspace.project!.info.id;
|
||||
|
||||
@override
|
||||
Future<ProjectState> build() async => ProjectState(
|
||||
activeProject: RecentProject(
|
||||
id: _projectId,
|
||||
name: 'Media timebase test',
|
||||
path: workspace.project!.directory.path,
|
||||
),
|
||||
timeline: session.document,
|
||||
assets: [asset],
|
||||
);
|
||||
|
||||
@override
|
||||
Future<T> withAssetMedia<T>(
|
||||
String? projectId,
|
||||
AssetDocument asset,
|
||||
Future<T> Function(MediaReference) action,
|
||||
) => workspace.withAssetMedia(_projectId, asset, action);
|
||||
}
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
testWidgets('real media timebase supports Finder and project asset drops', (
|
||||
tester,
|
||||
) async {
|
||||
final source = await nativeMediaFixture();
|
||||
expect(await source.exists(), isTrue);
|
||||
final info = await CutdexRuntime().probe(
|
||||
MediaReference(id: 'source', uri: source.uri),
|
||||
);
|
||||
debugPrint(
|
||||
'DROP_PROBE ${info.duration.numerator}/${info.duration.denominator}',
|
||||
);
|
||||
final fixture = await createPreviewFixture(source.uri);
|
||||
final session = fixture.timeline;
|
||||
final workspace = fixture.workspace;
|
||||
session.selectSequence(SequenceId('empty'));
|
||||
final asset = (await workspace.project!.listAssets()).single;
|
||||
final projects = _DropProjects(workspace, session, asset);
|
||||
final container = ProviderContainer(
|
||||
overrides: [projectsProvider.overrideWith(() => projects)],
|
||||
);
|
||||
final target = GlobalKey<TimelineExternalDropTargetState>();
|
||||
final incoming = ValueNotifier<TimelineIncomingAsset?>(null);
|
||||
addTearDown(() async {
|
||||
incoming.dispose();
|
||||
container.dispose();
|
||||
await workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
await container.read(projectsProvider.future);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
home: Scaffold(
|
||||
body: TimelineExternalDropTarget(
|
||||
key: target,
|
||||
projectId: projects._projectId,
|
||||
session: session,
|
||||
sequenceId: SequenceId('empty'),
|
||||
incoming: incoming,
|
||||
child: const SizedBox.expand(),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final ticks =
|
||||
(BigInt.from(info.duration.numerator) *
|
||||
BigInt.from(TimelineClock.ticksPerSecond) ~/
|
||||
BigInt.from(info.duration.denominator))
|
||||
.toInt();
|
||||
final runtime = CutdexRuntime();
|
||||
final native = await runtime.createSession();
|
||||
addTearDown(native.close);
|
||||
Future<ExecutionPlan> plan() async {
|
||||
final kernel = session.persistence.timeline(SequenceId('empty'));
|
||||
final media = await prepareEditorMedia(
|
||||
session: session,
|
||||
sequence: SequenceId('empty'),
|
||||
version: kernel.current,
|
||||
probe: runtime.probe,
|
||||
unknownVideoColorSpace: const PreviewPolicy().unknownVideoColorSpace,
|
||||
);
|
||||
return const ExecutionCompiler()
|
||||
.compile(
|
||||
ExecutionInput(
|
||||
timeline: kernel,
|
||||
media: media.bindings,
|
||||
renderSize: RenderSize(320, 180),
|
||||
),
|
||||
)
|
||||
.plan;
|
||||
}
|
||||
|
||||
for (final finder in [true, false]) {
|
||||
if (finder) {
|
||||
target.currentState!.enterExternal(
|
||||
1,
|
||||
source.path,
|
||||
const Offset(125, 65),
|
||||
);
|
||||
} else {
|
||||
incoming.value = (
|
||||
asset: asset,
|
||||
globalPosition:
|
||||
tester.getTopLeft(find.byType(TimelineExternalDropTarget)) +
|
||||
const Offset(125, 65),
|
||||
);
|
||||
}
|
||||
final preparer = container.read(
|
||||
timelineDropPreparationProvider(
|
||||
projects._projectId,
|
||||
session,
|
||||
SequenceId('empty'),
|
||||
).notifier,
|
||||
);
|
||||
await preparer.waitForPreparation();
|
||||
await tester.pumpAndSettle();
|
||||
expect(target.currentState!.placementError, isNull);
|
||||
expect(target.currentState!.incomingClip?.layout, isNotNull);
|
||||
await target.currentState!.drop();
|
||||
incoming.value = null;
|
||||
await tester.pumpAndSettle();
|
||||
final query = session.persistence
|
||||
.timeline(SequenceId('empty'))
|
||||
.current
|
||||
.query();
|
||||
final clip = query.element(
|
||||
query.storylineElements(query.primaryStoryline).single,
|
||||
);
|
||||
expect(clip.duration, ticks);
|
||||
await session.flush();
|
||||
final saved = await workspace.project!.loadTimeline('project');
|
||||
expect(
|
||||
saved.sequences
|
||||
.singleWhere((s) => s.id == SequenceId('empty'))
|
||||
.elements
|
||||
.single
|
||||
.duration,
|
||||
RationalTime.timelineTicks(ticks),
|
||||
);
|
||||
debugPrint('DROP_VALIDATED finder=$finder ticks=$ticks');
|
||||
if (finder) {
|
||||
await native.load(await plan());
|
||||
for (final fraction in [.5, .9, 0.0]) {
|
||||
final tick = (ticks * fraction).floor();
|
||||
await native.seek(MediaTime(tick, TimelineClock.ticksPerSecond));
|
||||
expect(
|
||||
(await native.refresh()).position.seconds,
|
||||
closeTo(tick / TimelineClock.ticksPerSecond, .05),
|
||||
);
|
||||
}
|
||||
await native.play();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||
await native.pause();
|
||||
expect((await native.refresh()).position.seconds, greaterThan(.1));
|
||||
debugPrint('DROP_NATIVE_PLAYBACK_VALIDATED');
|
||||
} else {
|
||||
session.commands.applyEdit(
|
||||
SequenceId('empty'),
|
||||
TrimClip(clip.id.value, CommandTime(3, 1)),
|
||||
);
|
||||
const output = String.fromEnvironment('CUTDEX_TEST_OUTPUT');
|
||||
final destination = File(
|
||||
output.isEmpty
|
||||
? '${fixture.directory.path}/timebase-export.mp4'
|
||||
: output,
|
||||
);
|
||||
final exported = await native.export(await plan(), destination.uri);
|
||||
final result = await runtime.probe(
|
||||
MediaReference(id: 'export', uri: exported),
|
||||
);
|
||||
expect(result.duration.seconds, closeTo(3, .05));
|
||||
expect(result.videoTrackCount, 1);
|
||||
expect(result.audioTrackCount, info.audioTrackCount > 0 ? 1 : 0);
|
||||
final thumbnail = await runtime.thumbnail(
|
||||
ThumbnailRequest(
|
||||
media: MediaReference(id: 'export', uri: exported),
|
||||
time: MediaTime(1, 1),
|
||||
),
|
||||
);
|
||||
expect(thumbnail.data, isNotEmpty);
|
||||
debugPrint('DROP_EXPORT_VALIDATED $exported');
|
||||
session.view(SequenceId('empty')).undo();
|
||||
expect(
|
||||
session.persistence
|
||||
.timeline(SequenceId('empty'))
|
||||
.current
|
||||
.query()
|
||||
.storylineSpan(query.primaryStoryline),
|
||||
ticks,
|
||||
);
|
||||
}
|
||||
session.view(SequenceId('empty')).undo();
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
}, skip: !hasNativeMediaFixture);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
testWidgets(
|
||||
'desktop host registers native window and dynamic file destinations',
|
||||
(tester) async {
|
||||
// This harness has no project state to save when the native host quits.
|
||||
const lifecycle = MethodChannel('cutdex/lifecycle');
|
||||
lifecycle.setMethodCallHandler(
|
||||
(call) async => call.method == 'prepareToQuit',
|
||||
);
|
||||
await lifecycle.invokeMethod<void>('ready');
|
||||
await tester.pumpWidget(
|
||||
const MaterialApp(home: Scaffold(body: SizedBox.expand())),
|
||||
);
|
||||
|
||||
final chrome = WindowChromeSession(headerHeight: 40);
|
||||
chrome.attach();
|
||||
addTearDown(chrome.dispose);
|
||||
for (var attempt = 0; attempt < 20 && !chrome.integrated; attempt++) {
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
}
|
||||
expect(
|
||||
chrome.integrated,
|
||||
isTrue,
|
||||
reason: 'The real native host must register window chrome.',
|
||||
);
|
||||
|
||||
final drop = NativeFileDropConnection(
|
||||
regionId: 'integration-host',
|
||||
onEvent: (_) async {},
|
||||
);
|
||||
drop.bind();
|
||||
addTearDown(drop.dispose);
|
||||
await drop.setRegion(
|
||||
const Rect.fromLTWH(0, 80, 100, 100),
|
||||
NativeDropConfiguration(
|
||||
allowedExtensions: ['wav'],
|
||||
maximumFileCount: 1,
|
||||
),
|
||||
);
|
||||
// No mock handler: this must reach a destination created by the real plugin.
|
||||
await drop.release(0);
|
||||
await drop.setRegion(null, NativeDropConfiguration.unrestricted);
|
||||
|
||||
if (Platform.isMacOS) {
|
||||
var exits = 0;
|
||||
final fullscreen = NativeFullscreenSession(onExit: () => exits++);
|
||||
fullscreen.attach();
|
||||
await fullscreen.setFullscreen(true);
|
||||
await fullscreen.setFullscreen(false);
|
||||
await tester.pump();
|
||||
expect(exits, 1);
|
||||
fullscreen.dispose();
|
||||
}
|
||||
},
|
||||
skip: !(Platform.isMacOS || Platform.isWindows),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/properties/picture_properties.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
import '../test/support/preview_fixture.dart';
|
||||
import 'support/native_media_fixture.dart';
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
const outputName = String.fromEnvironment('CUTDEX_TEST_OUTPUT');
|
||||
testWidgets('native grouped keyframes preview, scrub, play and export', (
|
||||
tester,
|
||||
) async {
|
||||
final output = outputName.isEmpty
|
||||
? ''
|
||||
: '${(await Directory.systemTemp.createTemp('cutdex-keyframes-')).path}/$outputName';
|
||||
final mediaFile = await nativeMediaFixture();
|
||||
final f = await createPreviewFixture(
|
||||
mediaFile.uri,
|
||||
clipDuration: RationalTime.seconds(4),
|
||||
renderSize: {'width': 640, 'height': 360},
|
||||
);
|
||||
final runtime = CutdexRuntime();
|
||||
final preview = PreviewController(
|
||||
timeline: f.timeline,
|
||||
activeSequence: () => f.timeline.activeSequenceId,
|
||||
viewForSequence: f.timeline.view,
|
||||
runtime: runtime,
|
||||
);
|
||||
addTearDown(() async {
|
||||
await preview.close();
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
await preview.initialize();
|
||||
expect(preview.error, isNull);
|
||||
final sequence = SequenceId('one');
|
||||
final clip = ElementId('clip');
|
||||
final view = f.timeline.view(sequence);
|
||||
ClipAnimation at(int seconds) {
|
||||
final q = view.version.kernelVersion.query();
|
||||
return ClipAnimation.at(
|
||||
q,
|
||||
q.elementById(clip)!,
|
||||
seconds * TimelineClock.ticksPerSecond,
|
||||
TimelineClock.ticksPerSecond ~/ 30,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> ready() async {
|
||||
for (var i = 0; i < 200 && preview.busy; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 25));
|
||||
await tester.pump();
|
||||
}
|
||||
expect(preview.busy, isFalse);
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
|
||||
Future<void> commit(List<ParameterCurveDto> curves) async {
|
||||
f.timeline.commitParameters(
|
||||
sequence,
|
||||
f.timeline.previewParameters(sequence, clip, curves),
|
||||
parameterTargets: ClipTransform.targets,
|
||||
);
|
||||
await ready();
|
||||
}
|
||||
|
||||
await commit(at(0).edit(const ClipTransform(scale: .5)));
|
||||
await commit([
|
||||
for (final channel in TransformChannel.values) ...at(0).toggle(channel),
|
||||
]);
|
||||
await commit(
|
||||
at(2).edit(
|
||||
const ClipTransform(x: .2, y: .1, scale: .7, scaleY: .9, rotation: 45),
|
||||
),
|
||||
);
|
||||
final ids = (f.workspace.project!.info.id, 'project');
|
||||
final boundary = GlobalKey();
|
||||
Future<void> mount(ThemeData theme, double width) => tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
editorPreviewProvider(
|
||||
ids.$1,
|
||||
ids.$2,
|
||||
).overrideWith((ref) async => preview),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: theme,
|
||||
home: Scaffold(
|
||||
body: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: EditorPreviewPanel(
|
||||
projectId: ids.$1,
|
||||
timelineId: ids.$2,
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: width,
|
||||
child: RepaintBoundary(
|
||||
key: boundary,
|
||||
child: ColoredBox(
|
||||
color: theme.scaffoldBackgroundColor,
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: PictureProperties(
|
||||
projectId: ids.$1,
|
||||
timelineId: ids.$2,
|
||||
session: f.timeline,
|
||||
sequence: sequence,
|
||||
clip: at(0).record,
|
||||
animationView: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await mount(EditorTheme.penDark, 280);
|
||||
preview.selectVisual(clip);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byType(PreviewInteractionOverlay),
|
||||
matching: find.byType(CustomPaint),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
view.seekTo(TimelineClock.ticksPerSecond);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||
await tester.pump();
|
||||
final visual = preview.visualForProperties(clip)!;
|
||||
expect(visual.transform.scaleY, closeTo(.7, 1e-8));
|
||||
expect(visual.transform.rotation, closeTo(22.5, 1e-8));
|
||||
final drag = preview.transforms.begin(visual)!;
|
||||
expect(await drag.prepared, isTrue);
|
||||
drag.update(drag.value.copyWith(scaleY: .8));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
await drag.end();
|
||||
preview.cancelTransform();
|
||||
await ready();
|
||||
expect(at(1).value.scaleY, closeTo(.8, 1e-8));
|
||||
expect(at(0).value.scaleY, .5);
|
||||
expect(at(2).value.scaleY, .9);
|
||||
await preview.togglePlayback();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 400));
|
||||
await tester.pump();
|
||||
expect(preview.playing, isTrue);
|
||||
expect(preview.selectedVisualIds, {clip});
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byType(PreviewInteractionOverlay),
|
||||
matching: find.byType(CustomPaint),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
await preview.pauseForCanvasInteraction();
|
||||
final snapshot = await preview.session!.refresh();
|
||||
expect(snapshot.position.seconds, greaterThan(1));
|
||||
expect(preview.error, isNull);
|
||||
for (final (theme, width, name) in [
|
||||
(EditorTheme.penDark, 280.0, 'dark'),
|
||||
(EditorTheme.penLight, 225.0, 'light'),
|
||||
]) {
|
||||
await mount(theme, width);
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.takeException(), isNull);
|
||||
if (output.isNotEmpty) {
|
||||
final image =
|
||||
await (boundary.currentContext!.findRenderObject()!
|
||||
as RenderRepaintBoundary)
|
||||
.toImage(pixelRatio: 2);
|
||||
final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
await File('$output-$name.png')
|
||||
.writeAsBytes(bytes!.buffer.asUint8List());
|
||||
image.dispose();
|
||||
}
|
||||
}
|
||||
if (output.isNotEmpty) {
|
||||
final preparedMedia = await prepareEditorMedia(
|
||||
session: f.timeline,
|
||||
sequence: sequence,
|
||||
version: f.timeline.persistence.timeline(sequence).current,
|
||||
probe: runtime.probe,
|
||||
unknownVideoColorSpace: const PreviewPolicy().unknownVideoColorSpace,
|
||||
);
|
||||
final compiled = const ExecutionCompiler().compile(
|
||||
ExecutionInput(
|
||||
timeline: f.timeline.persistence.timeline(sequence),
|
||||
renderSize: RenderSize(640, 360),
|
||||
parameterTargets: ClipTransform.targets,
|
||||
media: preparedMedia.bindings,
|
||||
),
|
||||
);
|
||||
await preview.session!.export(compiled.plan, File('$output.mp4').uri);
|
||||
expect(await File('$output.mp4').length(), greaterThan(1000));
|
||||
debugPrint('KEYFRAME_ARTIFACTS $output');
|
||||
}
|
||||
await f.timeline.flush();
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/app/app.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
import '../test/support/preview_fixture.dart';
|
||||
import 'support/native_media_fixture.dart';
|
||||
|
||||
void main() {
|
||||
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
const report = String.fromEnvironment('CUTDEX_TEST_REPORT');
|
||||
|
||||
testWidgets('full Cutdex app playback lifecycle and sustained editing', (
|
||||
tester,
|
||||
) async {
|
||||
final mediaFile = await nativeMediaFixture();
|
||||
final fixture = await createPreviewFixture(
|
||||
mediaFile.uri,
|
||||
clipDuration: RationalTime.seconds(12),
|
||||
hasAudio: true,
|
||||
renderSize: {'width': 640, 'height': 360},
|
||||
);
|
||||
await fixture.workspace.close();
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
final container = ProviderContainer(
|
||||
overrides: [appDatabaseProvider.overrideWithValue(database)],
|
||||
);
|
||||
// macOS can hide the test window while another app is foreground. Keep
|
||||
// tester.pump progressing without changing the application's lifecycle state.
|
||||
final hiddenWindowFrames = Timer.periodic(
|
||||
const Duration(milliseconds: 16),
|
||||
(_) {
|
||||
if (!binding.framesEnabled) binding.scheduleForcedFrame();
|
||||
},
|
||||
);
|
||||
final samples = <Map<String, Object?>>[];
|
||||
final steps = <String>[];
|
||||
void mark(String step) {
|
||||
steps.add(step);
|
||||
debugPrint('ACCEPTANCE: $step');
|
||||
}
|
||||
|
||||
final watch = Stopwatch()..start();
|
||||
var quit = false;
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
Future<void> until(
|
||||
bool Function() condition, {
|
||||
String label = 'UI settled',
|
||||
}) async {
|
||||
for (var attempt = 0; attempt < 500; attempt++) {
|
||||
await tester.pump(const Duration(milliseconds: 20));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||
if (condition()) {
|
||||
expect(tester.takeException(), isNull, reason: label);
|
||||
return;
|
||||
}
|
||||
}
|
||||
fail('Timed out: $label');
|
||||
}
|
||||
|
||||
Future<void> settled(PreviewController preview) async {
|
||||
await tester.pump();
|
||||
await until(
|
||||
() => !preview.busy && preview.ready,
|
||||
label: 'preview ready: ${preview.error}',
|
||||
);
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
|
||||
void sample(String phase, int edits) {
|
||||
samples.add({
|
||||
'phase': phase,
|
||||
'edits': edits,
|
||||
'elapsedMs': watch.elapsedMilliseconds,
|
||||
'rssBytes': ProcessInfo.currentRss,
|
||||
});
|
||||
debugPrint('ACCEPTANCE MEMORY: ${samples.last}');
|
||||
if (report.isNotEmpty) {
|
||||
File(report).writeAsStringSync(
|
||||
jsonEncode({
|
||||
'steps': steps,
|
||||
'memory': samples,
|
||||
'durationMs': watch.elapsedMilliseconds,
|
||||
'complete': false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: const CutdexApp(),
|
||||
),
|
||||
);
|
||||
await until(() => container.read(projectsProvider).hasValue);
|
||||
final phoneCut = find.byKey(const Key('workspace-cut-destination'));
|
||||
final desktopMode = find.byKey(const Key('sidebar-mode-trigger'));
|
||||
await until(
|
||||
() =>
|
||||
phoneCut.evaluate().isNotEmpty || desktopMode.evaluate().isNotEmpty,
|
||||
);
|
||||
if (phoneCut.evaluate().isNotEmpty) {
|
||||
expect(find.byKey(const Key('phone-workspace-shell')), findsOneWidget);
|
||||
await tester.tap(phoneCut);
|
||||
} else {
|
||||
await tester.tap(desktopMode);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const ValueKey('sidebar-mode-cut')));
|
||||
}
|
||||
await tester.pumpAndSettle();
|
||||
mark('selected Cut mode through the application navigation');
|
||||
expect(
|
||||
await projects.open('${fixture.directory.path}/Preview.cutdex'),
|
||||
isTrue,
|
||||
);
|
||||
final state = await container.read(projectsProvider.future);
|
||||
final ids = (state.activeProject!.id, 'project');
|
||||
expect(await projects.openTimeline(ids.$1, ids.$2), isTrue);
|
||||
await until(
|
||||
() =>
|
||||
container
|
||||
.read(editorPreviewProvider(ids.$1, ids.$2))
|
||||
.asData
|
||||
?.value
|
||||
?.ready ==
|
||||
true,
|
||||
label: 'full application preview initialized',
|
||||
);
|
||||
final preview = container
|
||||
.read(editorPreviewProvider(ids.$1, ids.$2))
|
||||
.requireValue!;
|
||||
final timeline = await container.read(
|
||||
editorTimelineProvider(ids.$1, ids.$2).future,
|
||||
);
|
||||
final sequence = SequenceId('one');
|
||||
final view = timeline.view(sequence);
|
||||
expect(find.byType(CutdexApp), findsOneWidget);
|
||||
await until(
|
||||
() => find.byType(RuntimePreview).evaluate().isNotEmpty,
|
||||
label: 'native preview widget mounted',
|
||||
);
|
||||
expect(find.byType(RuntimePreview), findsOneWidget);
|
||||
expect(find.byType(TimelineView), findsOneWidget);
|
||||
mark('full application and native preview mounted');
|
||||
|
||||
final panel = find.byType(EditorPreviewPanel);
|
||||
await tester.tap(
|
||||
find
|
||||
.descendant(of: panel, matching: find.byIcon(Icons.play_arrow))
|
||||
.first,
|
||||
);
|
||||
await until(() => preview.playing, label: 'UI play');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 700));
|
||||
await tester.pump();
|
||||
expect(
|
||||
(await preview.session!.refresh()).position.seconds,
|
||||
greaterThan(0),
|
||||
);
|
||||
await tester.tap(
|
||||
find.descendant(of: panel, matching: find.byIcon(Icons.pause)).first,
|
||||
);
|
||||
await until(() => !preview.playing, label: 'UI pause');
|
||||
mark('real play and pause buttons advanced native media clock');
|
||||
|
||||
final timelineRect = tester.getRect(find.byType(TimelineView));
|
||||
await tester.dragFrom(
|
||||
Offset(timelineRect.left + 80, timelineRect.top + 10),
|
||||
const Offset(160, 0),
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 150));
|
||||
expect(preview.error, isNull);
|
||||
for (final second in [3, 8, 1, 10, 0]) {
|
||||
view.seekTo(second * TimelineClock.ticksPerSecond);
|
||||
await tester.pump(const Duration(milliseconds: 120));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 80));
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
mark('timeline pointer drag and repeated forward/backward seeking');
|
||||
|
||||
expect(
|
||||
await projects.createTimeline(name: 'Acceptance empty timeline'),
|
||||
isTrue,
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 300));
|
||||
expect(await projects.openTimeline(ids.$1, ids.$2), isTrue);
|
||||
await settled(preview);
|
||||
mark('switch to empty timeline and return');
|
||||
|
||||
for (final events in [
|
||||
[
|
||||
PlaybackSystemEvent.systemWillSleep,
|
||||
PlaybackSystemEvent.systemDidWake,
|
||||
],
|
||||
[
|
||||
PlaybackSystemEvent.interruptionBegan,
|
||||
PlaybackSystemEvent.interruptionEnded,
|
||||
],
|
||||
]) {
|
||||
await preview.session!.handleSystemEvent(events.first);
|
||||
final before = preview.session!.snapshot!.revision;
|
||||
for (var i = 0; i < 8; i++) {
|
||||
timeline.commands.setTransform(
|
||||
sequence: sequence,
|
||||
clip: ElementId('clip'),
|
||||
tick: 0,
|
||||
change: (value) => value.copyWith(x: i / 100),
|
||||
);
|
||||
}
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
expect(preview.session!.snapshot!.revision, before);
|
||||
await preview.session!.handleSystemEvent(events.last);
|
||||
await settled(preview);
|
||||
}
|
||||
await preview.session!.handleSystemEvent(
|
||||
PlaybackSystemEvent.audioRouteChanged,
|
||||
);
|
||||
timeline.commands.setTransform(
|
||||
sequence: sequence,
|
||||
clip: ElementId('clip'),
|
||||
tick: 0,
|
||||
change: (value) => value.copyWith(x: .12),
|
||||
);
|
||||
await settled(preview);
|
||||
expect(preview.session!.availability, PlaybackAvailability.available);
|
||||
mark(
|
||||
'native sleep/wake, interruption and audio route events during real edits',
|
||||
);
|
||||
|
||||
sample('before warmup', 0);
|
||||
for (var index = 0; index < 180; index++) {
|
||||
timeline.commands.setTransform(
|
||||
sequence: sequence,
|
||||
clip: ElementId('clip'),
|
||||
tick: 0,
|
||||
change: (value) => value.copyWith(x: (index % 10) / 100),
|
||||
);
|
||||
await settled(preview);
|
||||
if (index % 10 == 0) {
|
||||
view.seekTo((index % 11) * TimelineClock.ticksPerSecond);
|
||||
}
|
||||
await tester.pump(const Duration(milliseconds: 40));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 700));
|
||||
if ((index + 1) % 20 == 0) sample('editing', index + 1);
|
||||
expect(preview.error, isNull);
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
await timeline.saveTimeline();
|
||||
mark('180 native-backed edits with periodic seeks, saved successfully');
|
||||
|
||||
await preview.session!.handleSystemEvent(
|
||||
PlaybackSystemEvent.systemWillSleep,
|
||||
);
|
||||
timeline.commands.setTransform(
|
||||
sequence: sequence,
|
||||
clip: ElementId('clip'),
|
||||
tick: 0,
|
||||
change: (value) => value.copyWith(x: .2),
|
||||
);
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
expect(
|
||||
await projects.prepareToQuit().timeout(const Duration(seconds: 15)),
|
||||
isTrue,
|
||||
);
|
||||
quit = true;
|
||||
mark('close workspace while preview waits for recovery');
|
||||
if (report.isNotEmpty) {
|
||||
await File(report).writeAsString(
|
||||
const JsonEncoder.withIndent(' ').convert({
|
||||
'steps': steps,
|
||||
'memory': samples,
|
||||
'durationMs': watch.elapsedMilliseconds,
|
||||
'systemEvents': 'injected into the actual app native facade; no physical machine sleep',
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (!quit) {
|
||||
try {
|
||||
await projects.prepareToQuit();
|
||||
} catch (_) {}
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
hiddenWindowFrames.cancel();
|
||||
container.dispose();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await database.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
}
|
||||
}, timeout: const Timeout(Duration(minutes: 10)));
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/properties/properties_panel.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
import '../test/support/preview_fixture.dart';
|
||||
import 'support/native_media_fixture.dart';
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
testWidgets('measure repeated real-media canvas drags', (tester) async {
|
||||
final channel = _TimingChannel();
|
||||
final mediaFile = await nativeMediaFixture();
|
||||
final fixture = await createPreviewFixture(
|
||||
mediaFile.uri,
|
||||
renderSize: {'width': 1920, 'height': 1440},
|
||||
);
|
||||
final preview = PreviewController(
|
||||
timeline: fixture.timeline,
|
||||
activeSequence: () => fixture.timeline.activeSequenceId,
|
||||
viewForSequence: fixture.timeline.view,
|
||||
runtime: CutdexRuntime(channel: channel),
|
||||
);
|
||||
addTearDown(() async {
|
||||
await preview.close();
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
await preview.initialize();
|
||||
expect(preview.error, isNull);
|
||||
final ids = (fixture.workspace.project!.info.id, 'project');
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
editorTimelineProvider(
|
||||
ids.$1,
|
||||
ids.$2,
|
||||
).overrideWith((ref) async => fixture.timeline),
|
||||
editorPreviewProvider(
|
||||
ids.$1,
|
||||
ids.$2,
|
||||
).overrideWith((ref) async => preview),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: EditorPreviewPanel(
|
||||
projectId: ids.$1,
|
||||
timelineId: ids.$2,
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 280,
|
||||
child: EditorPropertiesPanel(
|
||||
projectId: ids.$1,
|
||||
timelineId: ids.$2,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
await tester.pump();
|
||||
final canvas = tester.getRect(find.byKey(const Key('preview-canvas')));
|
||||
final screenScale = canvas.width / preview.canvas.width;
|
||||
preview.selectVisual(ElementId('clip'));
|
||||
await tester.pump();
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
|
||||
final samples = <double>[];
|
||||
final records = <Map<String, Object>>[];
|
||||
final clock = Stopwatch()..start();
|
||||
// Identical inputs before/after. Option excludes snap acquisition/release.
|
||||
for (var run = 0; run < 3; run++) {
|
||||
final visual = preview.visuals.single;
|
||||
final origin = canvas.topLeft + visual.geometry.center * screenScale;
|
||||
final gesture = await tester.startGesture(origin);
|
||||
for (var i = 1; i <= 120; i++) {
|
||||
final dx = 100 * math.sin(i * 2 * math.pi / 120);
|
||||
final dy = 30 * math.sin(i * 4 * math.pi / 120);
|
||||
await gesture.moveTo(origin + Offset(dx, dy));
|
||||
await tester.pump();
|
||||
final paint = tester.widget<CustomPaint>(
|
||||
find.descendant(
|
||||
of: find.byType(PreviewInteractionOverlay),
|
||||
matching: find.byType(CustomPaint),
|
||||
),
|
||||
);
|
||||
final geometry =
|
||||
(paint.painter as dynamic).geometry as PreviewGeometry?;
|
||||
if (geometry != null) {
|
||||
final shownX = geometry.center.dx / preview.canvas.width - .5;
|
||||
final error = (shownX - channel.completedX).abs() * canvas.width;
|
||||
samples.add(error);
|
||||
records.add({
|
||||
'ms': clock.elapsedMicroseconds / 1000,
|
||||
'boxX': shownX,
|
||||
'nativeX': channel.completedX,
|
||||
'gapPx': error,
|
||||
});
|
||||
}
|
||||
await Future<void>.delayed(const Duration(milliseconds: 8));
|
||||
}
|
||||
await gesture.up();
|
||||
await preview.transforms.settled;
|
||||
await Future<void>.delayed(const Duration(milliseconds: 150));
|
||||
await tester.pump();
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
|
||||
samples.sort();
|
||||
channel.latency.sort();
|
||||
double percentile(List<double> values, double p) =>
|
||||
values[((values.length - 1) * p).round()];
|
||||
final result = {
|
||||
'samples': samples.length,
|
||||
'updates': channel.latency.length,
|
||||
'gapMeasurement': 'callbackGeometry',
|
||||
'gapP50Px': percentile(samples, .5),
|
||||
'gapP95Px': percentile(samples, .95),
|
||||
'gapMaxPx': samples.last,
|
||||
'nativeP50Ms': percentile(channel.latency, .5),
|
||||
'nativeP95Ms': percentile(channel.latency, .95),
|
||||
'nativeMaxMs': channel.latency.last,
|
||||
'canvasWidth': canvas.width,
|
||||
'records': records,
|
||||
};
|
||||
debugPrint('DRAG_TIMING ${jsonEncode({...result}..remove('records'))}');
|
||||
const report = String.fromEnvironment('CUTDEX_TEST_REPORT');
|
||||
if (report.isNotEmpty) await File(report).writeAsString(jsonEncode(result));
|
||||
expect(samples.length, 360);
|
||||
expect(channel.latency.length, greaterThan(0));
|
||||
expect(
|
||||
samples.last,
|
||||
lessThan(1),
|
||||
reason: 'Selection must follow the acknowledged native snapshot',
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
}, skip: !hasNativeMediaFixture);
|
||||
}
|
||||
|
||||
class _TimingChannel extends MethodChannel {
|
||||
_TimingChannel() : super('cutdex_runtime');
|
||||
double completedX = 0;
|
||||
final latency = <double>[];
|
||||
|
||||
@override
|
||||
Future<T?> invokeMethod<T>(String method, [dynamic arguments]) async {
|
||||
final request = method == 'request'
|
||||
? jsonDecode(arguments['request'] as String) as Map
|
||||
: arguments as Map;
|
||||
final update =
|
||||
method == 'updateInteractiveTransform' ||
|
||||
request['method'] == 'updateInteractiveTransform';
|
||||
final watch = Stopwatch()..start();
|
||||
final response = await super.invokeMethod<T>(method, arguments);
|
||||
if (update) {
|
||||
latency.add(watch.elapsedMicroseconds / 1000);
|
||||
final transforms = request['transforms'] as List;
|
||||
if (transforms.isNotEmpty) {
|
||||
completedX = (transforms.first['x'] as num).toDouble();
|
||||
}
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import '../test/support/creation_names.dart';
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
|
||||
import '../test/support/processing_fixture.dart';
|
||||
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/integrations/editor_tools.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
for (final mask in [0, 1, 2, 4, 3, 5, 6, 7, -1]) {
|
||||
testWidgets('timeline native preview with optional capability mask $mask', (
|
||||
tester,
|
||||
) async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'preview-capabilities-',
|
||||
);
|
||||
final config = await processingFixture(
|
||||
root,
|
||||
mask < 0 ? 7 : mask,
|
||||
stale: mask < 0,
|
||||
);
|
||||
final workspace = ProjectWorkspace(
|
||||
creationNames: testCreationNames,
|
||||
processing: config,
|
||||
);
|
||||
try {
|
||||
await workspace.open('${root.path}/Test.cutdex', name: 'Preview');
|
||||
final document = TimelineDocument(
|
||||
id: 'timeline',
|
||||
name: 'Preview',
|
||||
defaultSequenceId: SequenceId('main'),
|
||||
sequences: [
|
||||
TimelineDto(
|
||||
id: SequenceId('main'),
|
||||
format: TimelineFormat.fps30,
|
||||
primaryStorylineId: StorylineId('primary'),
|
||||
storylines: [
|
||||
StorylineDto(id: StorylineId('primary'), elementIds: []),
|
||||
],
|
||||
elements: [],
|
||||
),
|
||||
],
|
||||
);
|
||||
await workspace.project!.saveTimeline(document);
|
||||
final timeline = await workspace.openTimelineSession(
|
||||
workspace.project!.info.id,
|
||||
await workspace.project!.loadTimeline(document.id),
|
||||
);
|
||||
final ids = (workspace.project!.info.id, document.id);
|
||||
final scoped = ProviderContainer(
|
||||
overrides: [
|
||||
editorTimelineProvider(
|
||||
ids.$1,
|
||||
ids.$2,
|
||||
).overrideWith((ref) async => timeline),
|
||||
],
|
||||
);
|
||||
try {
|
||||
final subscription = scoped.listen(
|
||||
editorPreviewProvider(ids.$1, ids.$2),
|
||||
(_, _) {},
|
||||
);
|
||||
final preview = await scoped.read(
|
||||
editorPreviewProvider(ids.$1, ids.$2).future,
|
||||
);
|
||||
expect(preview, isNotNull);
|
||||
expect(preview!.ready, isTrue);
|
||||
expect(preview.error, isNull);
|
||||
final enabled = mask < 0 ? 0 : mask;
|
||||
expect(
|
||||
timeline.supportedCommandOperations.contains(
|
||||
EditorOperation.startTranscription,
|
||||
),
|
||||
enabled & 1 != 0,
|
||||
);
|
||||
expect(
|
||||
timeline.supportedCommandOperations.contains(
|
||||
EditorOperation.startSubtitleTranslation,
|
||||
),
|
||||
enabled & 2 != 0,
|
||||
);
|
||||
expect(
|
||||
timeline.supportedCommandOperations.contains(
|
||||
EditorOperation.startVocalSeparation,
|
||||
),
|
||||
enabled & 4 != 0,
|
||||
);
|
||||
await preview.close();
|
||||
subscription.close();
|
||||
} finally {
|
||||
scoped.dispose();
|
||||
}
|
||||
} finally {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
}
|
||||
testWidgets(
|
||||
'opening a timeline initializes native preview through App providers',
|
||||
(tester) async {
|
||||
final directory = await Directory.systemTemp.createTemp(
|
||||
'cutdex preview startup ',
|
||||
);
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
final container = ProviderContainer(
|
||||
overrides: [appDatabaseProvider.overrideWithValue(database)],
|
||||
);
|
||||
try {
|
||||
container.read(applicationToolAccessProvider);
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
expect(
|
||||
await projects.open('${directory.path}/Test.cutdex', name: 'Preview'),
|
||||
isTrue,
|
||||
);
|
||||
expect(await projects.createTimeline(name: 'Timeline'), isTrue);
|
||||
final state = await container.read(projectsProvider.future);
|
||||
final ids = (state.activeProject!.id, state.timeline!.id);
|
||||
final subscription = container.listen(
|
||||
editorPreviewProvider(ids.$1, ids.$2),
|
||||
(_, _) {},
|
||||
);
|
||||
final preview = await container.read(
|
||||
editorPreviewProvider(ids.$1, ids.$2).future,
|
||||
);
|
||||
expect(preview, isNull);
|
||||
final timeline = await container.read(
|
||||
editorTimelineProvider(ids.$1, ids.$2).future,
|
||||
);
|
||||
expect(timeline.preview, isNull);
|
||||
subscription.close();
|
||||
await timeline.close();
|
||||
} finally {
|
||||
container.dispose();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
await database.close();
|
||||
await directory.delete(recursive: true);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/features/properties/canvas_presets.dart';
|
||||
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/timeline/timeline_panel.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
import '../test/support/preview_fixture.dart';
|
||||
import 'support/native_media_fixture.dart';
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
testWidgets(
|
||||
'native preview follows the full real-media timeline with audio',
|
||||
(tester) async {
|
||||
final mediaFile = await nativeMediaFixture();
|
||||
expect(await mediaFile.exists(), isTrue);
|
||||
final channel = _ObservedRuntimeChannel();
|
||||
final runtime = CutdexRuntime(channel: channel);
|
||||
final info = await runtime.probe(
|
||||
MediaReference(id: 'media', uri: mediaFile.uri),
|
||||
);
|
||||
final ticks =
|
||||
(BigInt.from(info.duration.numerator) *
|
||||
BigInt.from(TimelineClock.ticksPerSecond) ~/
|
||||
BigInt.from(info.duration.denominator))
|
||||
.toInt();
|
||||
final fixture = await createPreviewFixture(
|
||||
mediaFile.uri,
|
||||
clipDuration: RationalTime.timelineTicks(ticks),
|
||||
hasAudio: info.audioTrackCount > 0,
|
||||
);
|
||||
final preview = PreviewController(
|
||||
timeline: fixture.timeline,
|
||||
activeSequence: () => fixture.timeline.activeSequenceId,
|
||||
viewForSequence: fixture.timeline.view,
|
||||
runtime: runtime,
|
||||
);
|
||||
addTearDown(() async {
|
||||
await preview.close();
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
await preview.initialize();
|
||||
expect(preview.error, isNull);
|
||||
final ids = (fixture.workspace.project!.info.id, 'project');
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
editorTimelineProvider(
|
||||
ids.$1,
|
||||
ids.$2,
|
||||
).overrideWith((ref) async => fixture.timeline),
|
||||
editorPreviewProvider(
|
||||
ids.$1,
|
||||
ids.$2,
|
||||
).overrideWith((ref) async => preview),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: EditorPreviewPanel(
|
||||
projectId: ids.$1,
|
||||
timelineId: ids.$2,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: EditorTimelinePanel(
|
||||
projectId: ids.$1,
|
||||
timelineId: ids.$2,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(RuntimePreview), findsOneWidget);
|
||||
final view = fixture.timeline.view(SequenceId('one'));
|
||||
final thumbnails = tester
|
||||
.widget<TimelineView>(find.byType(TimelineView))
|
||||
.thumbnails!;
|
||||
final query = view.version.kernelVersion.query();
|
||||
final clip = query.element(query.elementById(ElementId('clip'))!);
|
||||
const logicalThumbnailSize = Size(82, 46);
|
||||
final devicePixelRatio = tester.view.devicePixelRatio;
|
||||
ui.Image? cover;
|
||||
for (var attempt = 0; attempt < 100 && cover == null; attempt++) {
|
||||
thumbnails.beginFrame();
|
||||
cover = thumbnails.imageFor(
|
||||
clip,
|
||||
0,
|
||||
sourceSpanTicks: TimelineClock.ticksPerSecond,
|
||||
logicalSize: logicalThumbnailSize,
|
||||
devicePixelRatio: devicePixelRatio,
|
||||
);
|
||||
thumbnails.endFrame();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
}
|
||||
expect(
|
||||
cover,
|
||||
isNotNull,
|
||||
reason: 'Timeline must decode an actual runtime thumbnail',
|
||||
);
|
||||
final maximumEdge = RuntimeTimelineThumbnails.maximumEdgeFor(
|
||||
logicalSize: logicalThumbnailSize,
|
||||
devicePixelRatio: devicePixelRatio,
|
||||
);
|
||||
expect(cover!.width, lessThanOrEqualTo(maximumEdge));
|
||||
expect(cover.height, lessThanOrEqualTo(maximumEdge));
|
||||
view.seekTo(TimelineClock.ticksPerSecond ~/ 2);
|
||||
await channel.settle(tester);
|
||||
var snapshot = await preview.session!.refresh();
|
||||
expect(snapshot.position.seconds, closeTo(0.5, 0.1));
|
||||
await preview.togglePlayback();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 350));
|
||||
await preview.session!.pause();
|
||||
snapshot = await preview.session!.refresh();
|
||||
expect(snapshot.position.seconds, greaterThan(0.5));
|
||||
expect(
|
||||
snapshot.position.seconds,
|
||||
lessThanOrEqualTo(info.duration.seconds),
|
||||
);
|
||||
final previewView = tester.element(find.byType(RuntimePreview));
|
||||
// Scrub repeatedly in both directions, then locate the exact end.
|
||||
for (final fraction in [0.7, 0.1, 0.8, 0.2, 0.6, 0.0, 1.0]) {
|
||||
view.seekTo((ticks * fraction).floor());
|
||||
await channel.settle(tester);
|
||||
snapshot = await preview.session!.refresh();
|
||||
expect(preview.error, isNull);
|
||||
expect(
|
||||
snapshot.position.seconds,
|
||||
closeTo(info.duration.seconds * fraction, 0.1),
|
||||
);
|
||||
expect(tester.element(find.byType(RuntimePreview)), same(previewView));
|
||||
}
|
||||
view.seekTo(TimelineClock.ticksPerSecond ~/ 2);
|
||||
await channel.settle(tester);
|
||||
snapshot = await preview.session!.refresh();
|
||||
for (var i = 0; i < 3; i++) {
|
||||
final pausedAt = snapshot.position.seconds;
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
channel.calls.clear();
|
||||
await preview.togglePlayback();
|
||||
expect(channel.calls, [
|
||||
'play',
|
||||
], reason: 'Resume must retain the current native image');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 150));
|
||||
await tester.pump();
|
||||
expect(tester.element(find.byType(RuntimePreview)), same(previewView));
|
||||
expect(preview.playing, isTrue);
|
||||
await preview.togglePlayback();
|
||||
snapshot = await preview.session!.refresh();
|
||||
expect(snapshot.state, PlaybackState.paused);
|
||||
expect(snapshot.position.seconds, greaterThan(pausedAt));
|
||||
}
|
||||
if (info.duration.seconds > 10) {
|
||||
// Exercise actual nanosecond clock observations across the int64
|
||||
// multiplication boundary; a short initial playback cannot catch this.
|
||||
view.seekTo(TimelineClock.ticksPerSecond * 5);
|
||||
await channel.settle(tester);
|
||||
await preview.togglePlayback();
|
||||
final observed = <int>[];
|
||||
for (var i = 0; i < 40; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
await tester.pump();
|
||||
observed.add(view.playheadTick);
|
||||
}
|
||||
await preview.session!.pause();
|
||||
expect(
|
||||
observed.first,
|
||||
greaterThanOrEqualTo(TimelineClock.ticksPerSecond * 5),
|
||||
);
|
||||
expect(observed.last, greaterThan(TimelineClock.ticksPerSecond * 8));
|
||||
for (var i = 1; i < observed.length; i++) {
|
||||
expect(
|
||||
observed[i],
|
||||
greaterThanOrEqualTo(observed[i - 1]),
|
||||
reason:
|
||||
'Playback observations must not send the playhead back to zero',
|
||||
);
|
||||
}
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
// The tail must remain seekable even when the source audio ends sooner.
|
||||
final tail = ticks - TimelineClock.ticksPerSecond ~/ 20;
|
||||
view.seekTo(tail);
|
||||
await channel.settle(tester);
|
||||
snapshot = await preview.session!.refresh();
|
||||
expect(
|
||||
snapshot.position.seconds,
|
||||
closeTo(tail / TimelineClock.ticksPerSecond, 0.1),
|
||||
);
|
||||
expect(preview.error, isNull);
|
||||
// The real App keeps one frozen-frame context across repeated releases.
|
||||
preview.setCanvas(ProjectCanvasPresets.values['4:3']!);
|
||||
await tester.pumpAndSettle();
|
||||
await channel.settle(tester);
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
channel.calls.clear();
|
||||
for (var i = 0; i < 8; i++) {
|
||||
final rect = tester.getRect(find.byKey(const Key('preview-canvas')));
|
||||
final center = preview.visuals.first.geometry.center;
|
||||
final start =
|
||||
rect.topLeft + center * (rect.width / preview.canvas.width);
|
||||
await tester.dragFrom(start, Offset(i.isEven ? 30 : -30, 0));
|
||||
await preview.transforms.settled;
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
expect(
|
||||
channel.calls.where((c) => c == 'beginInteractiveTransform'),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(
|
||||
channel.calls.where((c) => c == 'updateInteractiveTransform').length,
|
||||
greaterThanOrEqualTo(8),
|
||||
);
|
||||
expect(channel.calls, isNot(contains('applyPatch')));
|
||||
view.setSelection([
|
||||
view.version.kernelVersion.query().elementById(ElementId('clip'))!,
|
||||
]);
|
||||
view.seekTo(TimelineClock.ticksPerSecond);
|
||||
await channel.settle(tester);
|
||||
for (final edit in [view.cutSelectionAtPlayhead, view.undo, view.redo]) {
|
||||
channel.calls.clear();
|
||||
edit();
|
||||
await tester.pumpAndSettle();
|
||||
await channel.settle(tester);
|
||||
expect(preview.busy, isFalse);
|
||||
expect(preview.error, isNull);
|
||||
expect(channel.calls, contains('applyPatch'));
|
||||
expect(channel.calls, isNot(contains('seek')));
|
||||
snapshot = await preview.session!.refresh();
|
||||
expect(snapshot.position.seconds, closeTo(1, 0.1));
|
||||
expect(tester.element(find.byType(RuntimePreview)), same(previewView));
|
||||
}
|
||||
fixture.timeline.selectSequence(SequenceId('empty'));
|
||||
await tester.pumpAndSettle();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
expect(preview.error, isNull);
|
||||
expect(preview.durationTick, 0);
|
||||
expect(preview.canPlay, isFalse);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
skip: !hasNativeMediaFixture,
|
||||
);
|
||||
}
|
||||
|
||||
class _ObservedRuntimeChannel extends MethodChannel {
|
||||
_ObservedRuntimeChannel() : super('cutdex_runtime');
|
||||
final calls = <String>[];
|
||||
var _pendingControls = 0;
|
||||
final _quiet = Stopwatch()..start();
|
||||
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
final deadline = Stopwatch()..start();
|
||||
// Includes the controller's trailing exact-seek debounce. Pumping is
|
||||
// required for frame-bound transform handoffs; wall-clock sleep is not enough.
|
||||
_quiet.reset();
|
||||
while (_pendingControls != 0 || _quiet.elapsedMilliseconds < 200) {
|
||||
if (deadline.elapsed > const Duration(seconds: 30)) {
|
||||
fail('Preview controls did not settle within 30 seconds');
|
||||
}
|
||||
await tester.pump(const Duration(milliseconds: 16));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T?> invokeMethod<T>(String method, [dynamic arguments]) async {
|
||||
final operation = method == 'request'
|
||||
? (jsonDecode(arguments['request'] as String) as Map)['method']
|
||||
as String
|
||||
: method;
|
||||
calls.add(operation);
|
||||
final control = const {
|
||||
'load',
|
||||
'seek',
|
||||
'play',
|
||||
'pause',
|
||||
'applyPatch',
|
||||
'applySnapshot',
|
||||
'beginInteractiveTransform',
|
||||
'updateInteractiveTransform',
|
||||
'endInteractiveTransform',
|
||||
'recover',
|
||||
}.contains(operation);
|
||||
if (control) {
|
||||
_pendingControls++;
|
||||
_quiet.reset();
|
||||
}
|
||||
const timings = bool.fromEnvironment('CUTDEX_TEST_TIMINGS');
|
||||
final watch = Stopwatch()..start();
|
||||
try {
|
||||
return await super.invokeMethod<T>(method, arguments);
|
||||
} finally {
|
||||
if (control) {
|
||||
_pendingControls--;
|
||||
_quiet.reset();
|
||||
}
|
||||
if (timings && operation != 'snapshot') {
|
||||
debugPrint('RUNTIME_TIMING $operation ${watch.elapsedMilliseconds}ms');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
import '../test/support/creation_names.dart';
|
||||
|
||||
import 'dart:io';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex/integrations/runtime/processing_configuration.dart';
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
const source = String.fromEnvironment('CUTDEX_ASR_FIXTURE');
|
||||
const packageRoot = String.fromEnvironment('CUTDEX_PROCESSING_ROOT');
|
||||
Future<void> until(
|
||||
bool Function() done, {
|
||||
Duration timeout = const Duration(minutes: 4),
|
||||
}) async {
|
||||
final watch = Stopwatch()..start();
|
||||
while (!done()) {
|
||||
if (watch.elapsed > timeout) {
|
||||
throw StateError('Timed out waiting for processing');
|
||||
}
|
||||
await Future<void>.delayed(const Duration(milliseconds: 30));
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<String>> workers() async {
|
||||
final List<String> processes;
|
||||
if (Platform.isWindows) {
|
||||
final result = await Process.run('powershell.exe', [
|
||||
'-NoProfile',
|
||||
'-Command',
|
||||
r"Get-CimInstance Win32_Process | Where-Object { $_.Name -match '^(cutdex-(processing|asr|audio|m2m100)-worker|ffmpeg)\.exe$' } | Select-Object -ExpandProperty ExecutablePath | ConvertTo-Json -Compress",
|
||||
]);
|
||||
if (result.exitCode != 0) throw StateError('${result.stderr}');
|
||||
final output = (result.stdout as String).trim();
|
||||
final decoded = output.isEmpty ? null : jsonDecode(output);
|
||||
processes = switch (decoded) {
|
||||
null => [],
|
||||
String path => [path],
|
||||
List<Object?> paths => paths.cast<String>(),
|
||||
_ => throw StateError('Unexpected Windows process inventory'),
|
||||
};
|
||||
} else {
|
||||
final result = await Process.run('/bin/ps', ['-axo', 'pid=,command=']);
|
||||
if (result.exitCode != 0) throw StateError('${result.stderr}');
|
||||
processes = (result.stdout as String).split('\n');
|
||||
}
|
||||
final normalizedRoot = packageRoot.replaceAll(r'\', '/').toLowerCase();
|
||||
return processes.where((line) {
|
||||
final normalized = line.replaceAll(r'\', '/').toLowerCase();
|
||||
return normalized.contains('$normalizedRoot/') &&
|
||||
RegExp(r'(cutdex-(processing|asr|audio|m2m100)-worker|/ffmpeg)')
|
||||
.hasMatch(normalized);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
Future<void> workerStarted(bool Function() terminal, String worker) async {
|
||||
final watch = Stopwatch()..start();
|
||||
while (!(await workers()).any((line) => line.contains(worker))) {
|
||||
if (terminal() || watch.elapsed > const Duration(seconds: 30)) {
|
||||
throw StateError('No live worker observed');
|
||||
}
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
}
|
||||
}
|
||||
|
||||
Future<
|
||||
({
|
||||
ProjectWorkspace workspace,
|
||||
EditorTimelineSession session,
|
||||
Directory root,
|
||||
String projectId,
|
||||
String assetId,
|
||||
})
|
||||
>
|
||||
fixture() async {
|
||||
final config = ProcessingConfiguration.configured()!;
|
||||
expect(config.transcriptionModel, isNotNull);
|
||||
expect(config.translationModel, isNotNull);
|
||||
expect(config.vocalSeparationModel, isNotNull);
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-real-processing-');
|
||||
final workspace = ProjectWorkspace(
|
||||
creationNames: testCreationNames,
|
||||
processing: config,
|
||||
);
|
||||
await workspace.open('${root.path}/Test.cutdex', name: 'Real processing');
|
||||
final timelines = await workspace.createTimeline('Speech');
|
||||
final project = workspace.project!;
|
||||
final imported = await project.importFile(File(source), name: 'Speech');
|
||||
final document = await workspace.loadTimeline(
|
||||
project.info.id,
|
||||
timelines.single.id,
|
||||
);
|
||||
final session = await workspace.openTimelineSession(
|
||||
project.info.id,
|
||||
document,
|
||||
);
|
||||
final media = await workspace.prepareMedia(project.info.id, imported.id);
|
||||
session.insertAsset(
|
||||
sequenceId: session.activeSequenceId!,
|
||||
assetId: imported.id,
|
||||
assetName: 'Speech',
|
||||
uri: media.uri,
|
||||
duration: media.duration,
|
||||
position: 0,
|
||||
kind: 'audio',
|
||||
hasAudio: true,
|
||||
clipId: ElementId('speech'),
|
||||
);
|
||||
return (
|
||||
workspace: workspace,
|
||||
session: session,
|
||||
root: root,
|
||||
projectId: project.info.id,
|
||||
assetId: imported.id,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> play(EditorTimelineSession session) async {
|
||||
session.view(session.activeSequenceId!).seekTo(0);
|
||||
final preview = PreviewController(
|
||||
timeline: session,
|
||||
activeSequence: () => session.activeSequenceId,
|
||||
viewForSequence: session.view,
|
||||
runtime: CutdexRuntime(),
|
||||
);
|
||||
try {
|
||||
await preview.initialize();
|
||||
expect(preview.error, isNull);
|
||||
expect(preview.ready, isTrue);
|
||||
await preview.controlPreview(session.activeSequenceId!, PreviewAction.play);
|
||||
await until(
|
||||
() =>
|
||||
preview.positionTick > TimelineClock.ticksPerSecond ~/ 5 ||
|
||||
preview.error != null,
|
||||
timeout: const Duration(seconds: 15),
|
||||
);
|
||||
expect(preview.error, isNull);
|
||||
expect(preview.positionTick, greaterThan(0));
|
||||
await preview.controlPreview(
|
||||
session.activeSequenceId!,
|
||||
PreviewAction.pause,
|
||||
);
|
||||
} finally {
|
||||
await preview.close();
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
testWidgets(
|
||||
'real recognition, independent translation, stems and native playback',
|
||||
(tester) async {
|
||||
final f = await fixture();
|
||||
try {
|
||||
final session = f.session;
|
||||
final sequence = session.activeSequenceId!;
|
||||
final service = session.transcriptions!;
|
||||
final recognition = await service.start(
|
||||
StartTranscription(mediaId: f.assetId, language: 'en', threads: 2),
|
||||
);
|
||||
await until(() => recognition.terminal);
|
||||
expect(
|
||||
recognition.status,
|
||||
TranscriptionStatus.succeeded,
|
||||
reason: recognition.error,
|
||||
);
|
||||
expect(recognition.result!.cues, isNotEmpty);
|
||||
final recognized = await session.applyTranscription(
|
||||
sequence,
|
||||
ApplyTranscription(taskId: recognition.id, clipId: 'speech'),
|
||||
);
|
||||
final recognizedIds = (recognized['captionIds'] as List).cast<String>();
|
||||
expect(recognizedIds, hasLength(recognition.result!.cues.length));
|
||||
expect(
|
||||
session.caption(sequence, recognizedIds.first).text,
|
||||
recognition.result!.cues.first.text,
|
||||
);
|
||||
service.configure(
|
||||
backend: null,
|
||||
modelDirectory: null,
|
||||
translationBackend: service.translationBackend,
|
||||
translationModel: service.translationModel,
|
||||
);
|
||||
expect(service.recognitionAvailable, isFalse);
|
||||
final translation = await service.startTranslation(
|
||||
StartSubtitleTranslation(
|
||||
source: recognition.result!.subtitles.toFilePath(),
|
||||
sourceLanguage: 'en',
|
||||
targetLanguage: 'zh',
|
||||
threads: 2,
|
||||
),
|
||||
);
|
||||
await until(() => translation.terminal);
|
||||
expect(
|
||||
translation.status,
|
||||
TranscriptionStatus.succeeded,
|
||||
reason: translation.error,
|
||||
);
|
||||
expect(translation.result!.document.cues, isNotEmpty);
|
||||
final translated = await session.applySubtitleTranslation(
|
||||
sequence,
|
||||
ApplySubtitleTranslation(
|
||||
taskId: translation.id,
|
||||
clipId: 'speech',
|
||||
source: recognition.source!.toFilePath(),
|
||||
sourceStartMs: recognition.sourceStartMs,
|
||||
),
|
||||
);
|
||||
final translatedIds = (translated['captionIds'] as List).cast<String>();
|
||||
expect(
|
||||
translatedIds,
|
||||
hasLength(translation.result!.document.cues.length),
|
||||
);
|
||||
expect(
|
||||
session.caption(sequence, translatedIds.first).text,
|
||||
translation.result!.document.cues.first.text,
|
||||
);
|
||||
await play(session);
|
||||
final separated = await session.vocalSeparations!.start(
|
||||
StartVocalSeparation(mediaId: f.assetId, threads: 2),
|
||||
);
|
||||
await until(() => separated.terminal);
|
||||
expect(
|
||||
separated.status,
|
||||
VocalSeparationStatus.succeeded,
|
||||
reason: separated.error,
|
||||
);
|
||||
for (final uri in [
|
||||
separated.result!.vocals,
|
||||
separated.result!.instrumental,
|
||||
]) {
|
||||
expect(await File.fromUri(uri).length(), greaterThan(44));
|
||||
final info = await CutdexRuntime().probe(
|
||||
MediaReference(id: 'stem', uri: uri),
|
||||
);
|
||||
expect(info.audioTrackCount, greaterThan(0));
|
||||
expect(
|
||||
info.duration.seconds,
|
||||
closeTo(recognition.result!.durationMs / 1000, 0.1),
|
||||
);
|
||||
}
|
||||
await session.applyVocalSeparation(
|
||||
sequence,
|
||||
ApplyVocalSeparation(
|
||||
taskId: separated.id,
|
||||
clipId: 'speech',
|
||||
stems: VocalStem.values,
|
||||
insertIntoTimeline: true,
|
||||
),
|
||||
);
|
||||
expect(await f.workspace.listAssets(f.projectId), hasLength(3));
|
||||
await play(session);
|
||||
await session.flush();
|
||||
expect(await workers(), isEmpty);
|
||||
} finally {
|
||||
await f.workspace.close();
|
||||
await f.root.delete(recursive: true);
|
||||
}
|
||||
},
|
||||
skip: !(Platform.isMacOS || Platform.isWindows) || source.isEmpty,
|
||||
timeout: const Timeout(Duration(minutes: 12)),
|
||||
);
|
||||
for (final capability in ['asr', 'translation', 'audio']) {
|
||||
for (final action in [
|
||||
'cancel',
|
||||
'closeTimeline',
|
||||
'switchProjectThenClose',
|
||||
]) {
|
||||
testWidgets(
|
||||
'real $capability $action reaps processes and avoids partial publication',
|
||||
(tester) async {
|
||||
final f = await fixture();
|
||||
try {
|
||||
final destination = '${f.root.path}/cancel-output';
|
||||
late bool Function() terminal;
|
||||
late void Function() cancel;
|
||||
late String Function() status;
|
||||
late String worker;
|
||||
switch (capability) {
|
||||
case 'asr':
|
||||
final task = await f.session.transcriptions!.start(
|
||||
StartTranscription(
|
||||
mediaId: f.assetId,
|
||||
language: 'en',
|
||||
threads: 2,
|
||||
destination: destination,
|
||||
),
|
||||
);
|
||||
terminal = () => task.terminal;
|
||||
cancel = () => f.session.transcriptions!.cancel(task.id);
|
||||
status = () => task.status.name;
|
||||
worker = 'cutdex-asr-worker';
|
||||
case 'translation':
|
||||
final input = File('${f.root.path}/input.json');
|
||||
await input.writeAsString(
|
||||
jsonEncode({
|
||||
'schemaVersion': 1,
|
||||
'language': 'en',
|
||||
'cues': [
|
||||
{
|
||||
'startMs': 0,
|
||||
'endMs': 1000,
|
||||
'text': 'This is a short translation test.',
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
final task = await f.session.transcriptions!.startTranslation(
|
||||
StartSubtitleTranslation(
|
||||
source: input.path,
|
||||
sourceLanguage: 'en',
|
||||
targetLanguage: 'zh',
|
||||
threads: 2,
|
||||
destination: destination,
|
||||
),
|
||||
);
|
||||
terminal = () => task.terminal;
|
||||
cancel = () =>
|
||||
f.session.transcriptions!.cancelTranslation(task.id);
|
||||
status = () => task.status.name;
|
||||
worker = 'cutdex-m2m100-worker';
|
||||
case 'audio':
|
||||
final task = await f.session.vocalSeparations!.start(
|
||||
StartVocalSeparation(
|
||||
mediaId: f.assetId,
|
||||
threads: 2,
|
||||
destination: destination,
|
||||
),
|
||||
);
|
||||
terminal = () => task.terminal;
|
||||
cancel = () => f.session.vocalSeparations!.cancel(task.id);
|
||||
status = () => task.status.name;
|
||||
worker = 'cutdex-audio-worker';
|
||||
}
|
||||
await workerStarted(terminal, worker);
|
||||
switch (action) {
|
||||
case 'cancel':
|
||||
cancel();
|
||||
await until(terminal);
|
||||
case 'closeTimeline':
|
||||
await f.session.close();
|
||||
case 'switchProjectThenClose':
|
||||
await f.workspace.open(
|
||||
'${f.root.path}/Other.cutdex',
|
||||
name: 'Other',
|
||||
);
|
||||
expect(f.session.acceptsEdits, isTrue);
|
||||
await f.session.close();
|
||||
}
|
||||
expect(status(), action == 'cancel' ? 'cancelled' : 'interrupted');
|
||||
expect(await workers(), isEmpty);
|
||||
expect(await Directory(destination).exists(), isFalse);
|
||||
final staging = await f.root
|
||||
.list()
|
||||
.where(
|
||||
(entry) => entry.uri.pathSegments
|
||||
.where((segment) => segment.isNotEmpty)
|
||||
.last
|
||||
.startsWith('.cutdex-'),
|
||||
)
|
||||
.toList();
|
||||
if (action == 'cancel' || capability == 'translation') {
|
||||
expect(
|
||||
staging,
|
||||
isEmpty,
|
||||
reason: 'Disposable staging must be removed',
|
||||
);
|
||||
} else {
|
||||
// Host interruption preserves a resumable ASR/audio checkpoint, not a published result.
|
||||
expect(staging, hasLength(1));
|
||||
expect(
|
||||
await File('${staging.single.path}/checkpoint.json').exists(),
|
||||
isTrue,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await f.workspace.close();
|
||||
await f.root.delete(recursive: true);
|
||||
}
|
||||
},
|
||||
skip: !(Platform.isMacOS || Platform.isWindows) || source.isEmpty,
|
||||
timeout: const Timeout(Duration(minutes: 2)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
Future<void> pumpUntil(
|
||||
WidgetTester tester,
|
||||
bool Function() ready,
|
||||
String label, {
|
||||
int seconds = 60,
|
||||
}) async {
|
||||
final deadline = DateTime.now().add(Duration(seconds: seconds));
|
||||
while (!ready()) {
|
||||
if (DateTime.now().isAfter(deadline)) throw TimeoutException(label);
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
}
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<void> measureAndroidFullLengthPreview({
|
||||
required WidgetTester tester,
|
||||
required CutdexRuntime runtime,
|
||||
required MediaReference media,
|
||||
required MediaInfo info,
|
||||
required ({int width, int height, int observationSeconds}) configuration,
|
||||
required Map<String, Object?> result,
|
||||
required void Function() save,
|
||||
}) async {
|
||||
final full = await runtime.createSession();
|
||||
try {
|
||||
final duration = MediaTime(
|
||||
(math.min(
|
||||
info.duration.seconds,
|
||||
info.audioTracks.first.duration.seconds,
|
||||
) *
|
||||
1000)
|
||||
.floor() -
|
||||
100,
|
||||
1000,
|
||||
);
|
||||
final range = MediaRange(start: MediaTime(0, 1), duration: duration);
|
||||
await full.load(
|
||||
ExecutionPlan(
|
||||
duration: duration,
|
||||
renderSize: RenderSize(
|
||||
configuration.width.toDouble(),
|
||||
configuration.height.toDouble(),
|
||||
),
|
||||
frameDuration: MediaTime(1, 30),
|
||||
media: [media],
|
||||
visualLayers: [
|
||||
VisualLayer(
|
||||
id: 'full-video',
|
||||
mediaId: media.id,
|
||||
sourceRange: range,
|
||||
timelineRange: range,
|
||||
inputColorSpace:
|
||||
info.videoColorSpaces[0] ?? RenderColorSpace.rec709,
|
||||
),
|
||||
],
|
||||
audioLayers: [
|
||||
AudioLayer(
|
||||
id: 'full-audio',
|
||||
mediaId: media.id,
|
||||
sourceRange: range,
|
||||
timelineRange: range,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Center(
|
||||
child: SizedBox(
|
||||
width: configuration.width.toDouble(),
|
||||
height: configuration.height.toDouble(),
|
||||
child: RuntimePreview(session: full),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => (full.snapshot?.presentedVideoFrameCount ?? 0) > 0,
|
||||
'full-length first frame',
|
||||
seconds: 90,
|
||||
);
|
||||
final observations = <Map<String, Object?>>[];
|
||||
result['fullLengthPlayback'] = observations;
|
||||
for (final seconds in [
|
||||
60.0,
|
||||
duration.seconds / 2,
|
||||
duration.seconds - math.max(5, configuration.observationSeconds + 2),
|
||||
]) {
|
||||
final seekWatch = Stopwatch()..start();
|
||||
await full.seek(MediaTime((seconds * 1000).round(), 1000));
|
||||
final before = await full.refresh();
|
||||
final seekLatency = seekWatch.elapsedMilliseconds;
|
||||
final startWatch = Stopwatch()..start();
|
||||
await full.play();
|
||||
final startLatency = startWatch.elapsedMilliseconds;
|
||||
await Future<void>.delayed(
|
||||
Duration(seconds: configuration.observationSeconds),
|
||||
);
|
||||
await tester.pump();
|
||||
var after = await full.refresh();
|
||||
while (after.message == null &&
|
||||
(after.position.seconds <= seconds + .5 ||
|
||||
(after.presentedVideoFrameCount ?? 0) <=
|
||||
(before.presentedVideoFrameCount ?? 0)) &&
|
||||
startWatch.elapsedMilliseconds <
|
||||
startLatency +
|
||||
math.max(10000, configuration.observationSeconds * 1000)) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 250));
|
||||
await tester.pump();
|
||||
after = await full.refresh();
|
||||
}
|
||||
expect(after.message, isNull);
|
||||
expect(after.position.seconds, greaterThan(seconds + .5));
|
||||
expect(
|
||||
after.presentedVideoFrameCount,
|
||||
greaterThan(before.presentedVideoFrameCount ?? 0),
|
||||
);
|
||||
observations.add({
|
||||
'at': seconds,
|
||||
'position': after.position.seconds,
|
||||
'seekMilliseconds': seekLatency,
|
||||
'playStartupMilliseconds': startLatency,
|
||||
'observationMilliseconds': startWatch.elapsedMilliseconds,
|
||||
'slowPlayback':
|
||||
startWatch.elapsedMilliseconds - startLatency >
|
||||
configuration.observationSeconds * 1000 + 1000,
|
||||
'presentedFramesPerSecond':
|
||||
((after.presentedVideoFrameCount ?? 0) -
|
||||
(before.presentedVideoFrameCount ?? 0)) *
|
||||
1000 /
|
||||
(startWatch.elapsedMilliseconds - startLatency),
|
||||
'timelineAdvanceSeconds':
|
||||
after.position.seconds - before.position.seconds,
|
||||
'frames':
|
||||
(after.presentedVideoFrameCount ?? 0) -
|
||||
(before.presentedVideoFrameCount ?? 0),
|
||||
'maximumFrameGapMs': after.maximumVideoFrameGapMs,
|
||||
'maximumFrameGapScope': 'session cumulative',
|
||||
});
|
||||
await full.pause();
|
||||
save();
|
||||
}
|
||||
} finally {
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await full.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
const _source = String.fromEnvironment('CUTDEX_TEST_SOURCE');
|
||||
const _encodedSource = String.fromEnvironment('CUTDEX_TEST_SOURCE_BASE64');
|
||||
const _document = String.fromEnvironment('CUTDEX_TEST_SOURCE_DOCUMENT');
|
||||
|
||||
const hasNativeMediaFixture =
|
||||
_source != '' || _encodedSource != '' || _document != '';
|
||||
|
||||
/// Uses a host file, a sandbox document, or embedded media written to a temporary file.
|
||||
Future<File> nativeMediaFixture() async {
|
||||
if (_encodedSource.isEmpty) {
|
||||
if (_document.isEmpty) return File(_source).absolute;
|
||||
final directory = await getApplicationDocumentsDirectory();
|
||||
return File('${directory.path}/$_document');
|
||||
}
|
||||
final directory = await Directory.systemTemp.createTemp('cutdex-media-');
|
||||
addTearDown(() => directory.delete(recursive: true));
|
||||
return File('${directory.path}/source.mp4')
|
||||
.writeAsBytes(base64Decode(_encodedSource));
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/painting.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
Future<double> verifyEditedExport(
|
||||
CutdexRuntime runtime, {
|
||||
required Uri edited,
|
||||
required Uri baseline,
|
||||
}) async {
|
||||
final editedMedia = MediaReference(id: 'edited', uri: edited);
|
||||
final editedInfo = await runtime.probe(editedMedia);
|
||||
expect(editedInfo.duration.seconds, closeTo(4, .1));
|
||||
expect(editedInfo.audioTrackCount, 1);
|
||||
final thumbnail = await runtime.thumbnail(
|
||||
ThumbnailRequest(
|
||||
media: editedMedia,
|
||||
time: MediaTime(1, 1),
|
||||
maximumWidth: 320,
|
||||
maximumHeight: 180,
|
||||
),
|
||||
);
|
||||
final image = await decodeImageFromList(thumbnail.data);
|
||||
try {
|
||||
final pixels = (await image.toByteData(
|
||||
format: ui.ImageByteFormat.rawRgba,
|
||||
))!;
|
||||
// The authored half-size mask must leave the canvas corners black.
|
||||
for (final at in [
|
||||
0,
|
||||
(image.width - 1) * 4,
|
||||
(image.height - 1) * image.width * 4,
|
||||
]) {
|
||||
expect(
|
||||
pixels.getUint8(at) + pixels.getUint8(at + 1) + pixels.getUint8(at + 2),
|
||||
lessThan(35),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
image.dispose();
|
||||
}
|
||||
final originalWave = await runtime.waveform(
|
||||
WaveformRequest(
|
||||
media: MediaReference(id: 'baseline', uri: baseline),
|
||||
baseBucketCount: 64,
|
||||
levelCount: 1,
|
||||
),
|
||||
);
|
||||
final editedWave = await runtime.waveform(
|
||||
WaveformRequest(media: editedMedia, baseBucketCount: 64, levelCount: 1),
|
||||
);
|
||||
double rms(MediaWaveform wave) {
|
||||
final values = [
|
||||
for (final channel in wave.levels.first.channels)
|
||||
for (var i = 2; i < channel.length; i += 3) channel[i],
|
||||
];
|
||||
return math.sqrt(
|
||||
values.fold<double>(0, (sum, value) => sum + value * value) /
|
||||
values.length,
|
||||
);
|
||||
}
|
||||
|
||||
final baseRms = rms(originalWave);
|
||||
expect(baseRms, greaterThan(0));
|
||||
final ratio = rms(editedWave) / baseRms;
|
||||
expect(ratio, closeTo(math.pow(10, -6 / 20).toDouble(), .08));
|
||||
return ratio;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
final class RealMediaReport {
|
||||
RealMediaReport(this.file, {required Map<String, Object?> metadata})
|
||||
: metadata = Map.unmodifiable(metadata);
|
||||
|
||||
final File file;
|
||||
final Map<String, Object?> metadata;
|
||||
final files = <Map<String, Object?>>[];
|
||||
|
||||
void save() {
|
||||
final temporary = File('${file.path}.part');
|
||||
temporary.writeAsStringSync(
|
||||
const JsonEncoder.withIndent(' ').convert({...metadata, 'files': files}),
|
||||
);
|
||||
temporary.renameSync(file.path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class SavedEditValidation {
|
||||
final _edits = <String, Map<String, Map<String, Object?>>>{};
|
||||
|
||||
Future<Map<String, Object?>> capture(
|
||||
String projectPath,
|
||||
String timelineId,
|
||||
EditorSession session,
|
||||
SequenceId sequence,
|
||||
) async {
|
||||
final edits = await _editingState(session, sequence);
|
||||
_edits.putIfAbsent(projectPath, () => {})[timelineId] = edits;
|
||||
return edits;
|
||||
}
|
||||
|
||||
Future<void> verify({
|
||||
required Future<void> Function(Duration) wait,
|
||||
required void Function(
|
||||
String projectPath,
|
||||
String timelineId,
|
||||
Map<String, Object?> edits,
|
||||
)
|
||||
onVerified,
|
||||
}) async {
|
||||
for (final project in _edits.entries) {
|
||||
ProjectFile? reopened;
|
||||
final deadline = DateTime.now().add(const Duration(seconds: 40));
|
||||
while (reopened == null) {
|
||||
try {
|
||||
reopened = await ProjectFile.open(Directory(project.key));
|
||||
} on ProjectFileException catch (error) {
|
||||
if (error.code != ProjectFileError.conflict ||
|
||||
DateTime.now().isAfter(deadline)) {
|
||||
rethrow;
|
||||
}
|
||||
await wait(const Duration(milliseconds: 100));
|
||||
}
|
||||
}
|
||||
try {
|
||||
for (final entry in project.value.entries) {
|
||||
final session = EditorSession(
|
||||
document: await reopened.loadTimeline(entry.key),
|
||||
persistence: await reopened.openTimelineSaveSession(entry.key),
|
||||
);
|
||||
late Map<String, Object?> actual;
|
||||
try {
|
||||
actual = await _editingState(
|
||||
session,
|
||||
SequenceId(entry.value['sequenceId'] as String),
|
||||
);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
expect(
|
||||
actual,
|
||||
entry.value,
|
||||
reason: 'Edited timeline changed after close/reopen',
|
||||
);
|
||||
onVerified(project.key, entry.key, actual);
|
||||
}
|
||||
} finally {
|
||||
await reopened.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, Object?>> _editingState(
|
||||
EditorSession session,
|
||||
SequenceId sequence,
|
||||
) async {
|
||||
final result = await session.executeCommand(
|
||||
sequence,
|
||||
const QueryTimeline(),
|
||||
);
|
||||
// History availability and save status describe the current session.
|
||||
return Map<String, Object?>.of(result.data)
|
||||
..remove('canUndo')
|
||||
..remove('canRedo')
|
||||
..remove('saveState');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
import 'support/native_media_fixture.dart';
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
const concurrency = int.fromEnvironment(
|
||||
'CUTDEX_THUMBNAIL_CONCURRENCY',
|
||||
defaultValue: 2,
|
||||
);
|
||||
const batchSize = int.fromEnvironment(
|
||||
'CUTDEX_THUMBNAIL_BATCH_SIZE',
|
||||
defaultValue: 4,
|
||||
);
|
||||
|
||||
testWidgets('measure native request through painted timeline thumbnails', (
|
||||
tester,
|
||||
) async {
|
||||
final directory = await Directory.systemTemp.createTemp(
|
||||
'cutdex-thumbnail-',
|
||||
);
|
||||
final original = await nativeMediaFixture();
|
||||
final alias = File(
|
||||
'${directory.path}/source${original.uri.pathSegments.last.contains('.mp4') ? '.mp4' : '.mkv'}',
|
||||
);
|
||||
if (Platform.isIOS) {
|
||||
// AVFoundation denies this symlink on iOS; copy before starting the clock.
|
||||
await original.copy(alias.path);
|
||||
} else {
|
||||
await Link(alias.path).create(original.path);
|
||||
}
|
||||
addTearDown(() => directory.delete(recursive: true));
|
||||
|
||||
final clock = Stopwatch()..start();
|
||||
final channel = _ThumbnailTimingChannel(clock);
|
||||
final frames = RuntimeTimelineThumbnails(
|
||||
runtime: CutdexRuntime(channel: channel),
|
||||
resolveMedia: (_) => MediaReference(id: 'source', uri: alias.uri),
|
||||
resolveTrackSelection: (_) => TrackSelection.index(0),
|
||||
maximumConcurrent: concurrency,
|
||||
maximumBatchSize: batchSize,
|
||||
);
|
||||
addTearDown(frames.dispose);
|
||||
final element = ElementRecord(
|
||||
id: ElementId('clip'),
|
||||
structure: ElementStructure.content,
|
||||
sourceStart: 0,
|
||||
sourceDuration: TimelineClock.ticksPerSecond * 30,
|
||||
duration: TimelineClock.ticksPerSecond * 30,
|
||||
enabled: true,
|
||||
payloadRef: PayloadRef('source'),
|
||||
);
|
||||
final paintTimes = <int, double>{};
|
||||
final notifications = <Map<String, Object>>[];
|
||||
frames.addListener(() {
|
||||
final loaded = List.generate(9, (index) => index)
|
||||
.where(
|
||||
(index) =>
|
||||
frames.imageFor(
|
||||
element,
|
||||
TimelineClock.ticksPerSecond * (15 + index),
|
||||
sourceSpanTicks: 1,
|
||||
logicalSize: const Size(96, 54),
|
||||
devicePixelRatio: 2,
|
||||
) !=
|
||||
null,
|
||||
)
|
||||
.length;
|
||||
notifications.add({
|
||||
'count': loaded,
|
||||
'ms': clock.elapsedMicroseconds / 1000,
|
||||
});
|
||||
});
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
home: Center(
|
||||
child: SizedBox(
|
||||
width: 864,
|
||||
height: 54,
|
||||
child: CustomPaint(
|
||||
painter: _ThumbnailTimingPainter(frames, element, (count) {
|
||||
for (final target in [1, 5, 9]) {
|
||||
if (count >= target) {
|
||||
paintTimes.putIfAbsent(
|
||||
target,
|
||||
() => clock.elapsedMicroseconds / 1000,
|
||||
);
|
||||
}
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
for (
|
||||
var attempt = 0;
|
||||
attempt < 600 && !paintTimes.containsKey(9);
|
||||
attempt++
|
||||
) {
|
||||
await tester.pump(const Duration(milliseconds: 16));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 4));
|
||||
}
|
||||
expect(paintTimes[9], isNotNull);
|
||||
debugPrint(
|
||||
'THUMBNAIL_TIMING ${jsonEncode({'source': original.uri.pathSegments.last, 'concurrency': concurrency, 'batchSize': batchSize, 'paintMs': paintTimes.map((key, value) => MapEntry('$key', value)), 'nativeBatches': channel.batches, 'notifications': notifications})}',
|
||||
);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
}, skip: !hasNativeMediaFixture);
|
||||
}
|
||||
|
||||
final class _ThumbnailTimingChannel extends MethodChannel {
|
||||
_ThumbnailTimingChannel(this.clock) : super('cutdex_runtime');
|
||||
final Stopwatch clock;
|
||||
final batches = <Map<String, Object>>[];
|
||||
|
||||
@override
|
||||
Future<T?> invokeMethod<T>(String method, [dynamic arguments]) async {
|
||||
if (method != 'thumbnails') return super.invokeMethod<T>(method, arguments);
|
||||
final started = clock.elapsedMicroseconds / 1000;
|
||||
try {
|
||||
final result = await super.invokeMethod<T>(method, arguments);
|
||||
batches.add({
|
||||
'count': ((arguments as Map)['times'] as List).length,
|
||||
'startedMs': started,
|
||||
'returnedMs': clock.elapsedMicroseconds / 1000,
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
debugPrint('THUMBNAIL_REQUEST_FAILED $error');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class _ThumbnailTimingPainter extends CustomPainter {
|
||||
_ThumbnailTimingPainter(this.frames, this.element, this.onPaint)
|
||||
: super(repaint: frames);
|
||||
|
||||
final RuntimeTimelineThumbnails frames;
|
||||
final ElementRecord element;
|
||||
final void Function(int count) onPaint;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
var painted = 0;
|
||||
frames.beginFrame();
|
||||
for (var index = 0; index < 9; index++) {
|
||||
final image = frames.imageFor(
|
||||
element,
|
||||
TimelineClock.ticksPerSecond * (15 + index),
|
||||
sourceSpanTicks: 1,
|
||||
logicalSize: const Size(96, 54),
|
||||
devicePixelRatio: 2,
|
||||
);
|
||||
if (image == null) continue;
|
||||
painted++;
|
||||
canvas.drawImageRect(
|
||||
image,
|
||||
Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()),
|
||||
Rect.fromLTWH(index * 96, 0, 96, 54),
|
||||
Paint(),
|
||||
);
|
||||
}
|
||||
frames.endFrame();
|
||||
onPaint(painted);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_ThumbnailTimingPainter oldDelegate) => false;
|
||||
}
|
||||
@@ -0,0 +1,733 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
|
||||
// Opt-in validation of original audio through the real Windows editor/runtime.
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/properties/properties_panel.dart';
|
||||
import 'package:cutdex/features/timeline/timeline_panel.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/media_file_extensions.dart';
|
||||
import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex/workspace/preview_controller_registry.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import 'support/saved_edit_validation.dart';
|
||||
|
||||
double _rms(MediaWaveform wave) {
|
||||
final values = [
|
||||
for (final channel in wave.levels.first.channels)
|
||||
for (var i = 2; i < channel.length; i += 3) channel[i],
|
||||
];
|
||||
return math.sqrt(
|
||||
values.fold<double>(0, (sum, value) => sum + value * value) / values.length,
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
const source = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE');
|
||||
const output = String.fromEnvironment('CUTDEX_VALIDATION_ROOT');
|
||||
const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER');
|
||||
const metadataOnly = bool.fromEnvironment('CUTDEX_VALIDATION_METADATA_ONLY');
|
||||
testWidgets('Windows original audio: import, preview and editing', (
|
||||
tester,
|
||||
) async {
|
||||
expect(Platform.isWindows, isTrue);
|
||||
expect(source, isNotEmpty);
|
||||
expect(output, isNotEmpty);
|
||||
final paths =
|
||||
Directory(source)
|
||||
.listSync(recursive: true, followLinks: false)
|
||||
.whereType<File>()
|
||||
.where(
|
||||
(file) =>
|
||||
mediaKindForPath(file.path) != null &&
|
||||
(filter.isEmpty ||
|
||||
filter.split(',').any(p.basename(file.path).contains)),
|
||||
)
|
||||
.toList()
|
||||
..sort((a, b) => a.path.compareTo(b.path));
|
||||
expect(paths, isNotEmpty);
|
||||
final root = await Directory(output).create(recursive: true);
|
||||
final report = File(p.join(root.path, 'results.json'));
|
||||
final savedEdits = SavedEditValidation();
|
||||
final results = <Map<String, Object?>>[];
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
final container = ProviderContainer(
|
||||
overrides: [appDatabaseProvider.overrideWithValue(database)],
|
||||
);
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
final runtime = CutdexRuntime();
|
||||
addTearDown(database.close);
|
||||
var disposed = false;
|
||||
addTearDown(() {
|
||||
if (!disposed) container.dispose();
|
||||
});
|
||||
void save() => report.writeAsStringSync(
|
||||
const JsonEncoder.withIndent(' ').convert({
|
||||
'platform': 'windows',
|
||||
'source': source,
|
||||
'metadataOnly': metadataOnly,
|
||||
'method': 'Original files; production source-preview controller, import service and editor widgets; native waveform, preview and H.264/AAC exports. Isolated settings/projects. Source SHA-256 checked.',
|
||||
'files': results,
|
||||
}),
|
||||
);
|
||||
Future<void> until(
|
||||
bool Function() ready,
|
||||
String label, {
|
||||
int seconds = 60,
|
||||
}) async {
|
||||
final deadline = DateTime.now().add(Duration(seconds: seconds));
|
||||
while (!ready()) {
|
||||
if (DateTime.now().isAfter(deadline)) throw TimeoutException(label);
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
}
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
expect(
|
||||
await projects.open(
|
||||
p.join(
|
||||
root.path,
|
||||
'Audio-${DateTime.now().millisecondsSinceEpoch}.cutdex',
|
||||
),
|
||||
name: 'Windows 音频素材验证',
|
||||
initialTimelineName: '01',
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
var projectId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.activeProject!
|
||||
.id;
|
||||
for (var index = 0; index < paths.length; index++) {
|
||||
final file = paths[index];
|
||||
final before = await file.stat();
|
||||
final beforeHash = (await sha256.bind(file.openRead()).first).toString();
|
||||
final checks = <Map<String, Object?>>[];
|
||||
final result = <String, Object?>{
|
||||
'path': file.path,
|
||||
'sourceSha256': beforeHash,
|
||||
'checks': checks,
|
||||
'passed': false,
|
||||
};
|
||||
results.add(result);
|
||||
save();
|
||||
var stage = 'setup';
|
||||
String? testedTimeline;
|
||||
void Function()? releaseTimeline;
|
||||
Future<void> check(String name, Future<void> Function() action) async {
|
||||
stage = name;
|
||||
debugPrint(
|
||||
'AUDIO_MEDIA ${index + 1}/${paths.length} $name ${p.basename(file.path)}',
|
||||
);
|
||||
final clock = Stopwatch()..start();
|
||||
await action().timeout(const Duration(minutes: 4));
|
||||
expect(
|
||||
tester.takeException(),
|
||||
isNull,
|
||||
reason: 'Widget error during $name',
|
||||
);
|
||||
checks.add({
|
||||
'stage': name,
|
||||
'passed': true,
|
||||
'milliseconds': clock.elapsedMilliseconds,
|
||||
});
|
||||
save();
|
||||
}
|
||||
|
||||
try {
|
||||
if (index > 0) {
|
||||
if (container.read(projectsProvider).requireValue.timelines.length >=
|
||||
Projects.maxTimelineCount) {
|
||||
expect(
|
||||
await projects.open(
|
||||
p.join(
|
||||
root.path,
|
||||
'Audio-batch-${index + 1}-${DateTime.now().millisecondsSinceEpoch}.cutdex',
|
||||
),
|
||||
name: 'Windows 音频素材验证 ${index + 1}',
|
||||
initialTimelineName: '${index + 1}',
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
projectId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.activeProject!
|
||||
.id;
|
||||
} else {
|
||||
expect(await projects.createTimeline(name: '${index + 1}'), isTrue);
|
||||
}
|
||||
}
|
||||
final timelineId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timeline!
|
||||
.id;
|
||||
testedTimeline = timelineId;
|
||||
final retained = container.listen(
|
||||
editorTimelineProvider(projectId, timelineId),
|
||||
(_, _) {},
|
||||
);
|
||||
releaseTimeline = retained.close;
|
||||
final session = await container.read(
|
||||
editorTimelineProvider(projectId, timelineId).future,
|
||||
);
|
||||
final sequence = session.activeSequenceId!;
|
||||
final media = MediaReference(id: 'audio-source', uri: file.uri);
|
||||
late MediaInfo info;
|
||||
await check('probeOriginal', () async {
|
||||
info = await runtime.probe(media);
|
||||
expect(info.audioTrackCount, 1);
|
||||
expect(info.videoTrackCount, 0);
|
||||
expect(info.duration.seconds, greaterThan(10));
|
||||
expect(info.isProtected, isFalse);
|
||||
result['durationSeconds'] = info.duration.seconds;
|
||||
result['audioTracks'] = info.audioTracks
|
||||
.map(
|
||||
(track) => {
|
||||
'start': track.start.toMap(),
|
||||
'duration': track.duration.toMap(),
|
||||
},
|
||||
)
|
||||
.toList();
|
||||
});
|
||||
await check('fullSourceWaveform', () async {
|
||||
final wave = await runtime.waveform(
|
||||
WaveformRequest(
|
||||
media: media,
|
||||
trackSelection: const TrackSelection.defaultTrack(),
|
||||
baseBucketCount: 512,
|
||||
levelCount: 3,
|
||||
),
|
||||
);
|
||||
expect(wave.frameCount, greaterThan(0));
|
||||
expect(_rms(wave), greaterThan(.0001));
|
||||
result['waveform'] = {
|
||||
'sampleRate': wave.sampleRate,
|
||||
'channels': wave.levels.first.channels.length,
|
||||
'frames': wave.frameCount,
|
||||
'rms': _rms(wave),
|
||||
};
|
||||
expect(
|
||||
wave.frameCount / wave.sampleRate,
|
||||
closeTo(info.duration.seconds, .5),
|
||||
);
|
||||
});
|
||||
if (!metadataOnly) {
|
||||
await check('sourcePreviewPlayPauseAndSeek', () async {
|
||||
final controller = SourcePreviewController(
|
||||
loadMedia: <T>(action) => action(media),
|
||||
frameDuration: RationalTime(1, 30),
|
||||
rememberPosition: (_) {},
|
||||
runtime: runtime,
|
||||
);
|
||||
try {
|
||||
await controller.initialize(Future<void>.value());
|
||||
expect(controller.error, isNull);
|
||||
expect(controller.audioOnly, isTrue);
|
||||
expect(controller.canPlay, isTrue);
|
||||
final observations = <Map<String, Object?>>[];
|
||||
for (final at in [
|
||||
0.0,
|
||||
info.duration.seconds / 2,
|
||||
info.duration.seconds - 2,
|
||||
]) {
|
||||
await controller.session!.seek(
|
||||
MediaTime((at * 1000).round(), 1000),
|
||||
);
|
||||
await controller.togglePlayback();
|
||||
await until(() {
|
||||
if (controller.error != null) {
|
||||
throw StateError('${controller.error}');
|
||||
}
|
||||
return controller.playing &&
|
||||
controller.positionTick >
|
||||
(at + .4) * TimelineClock.ticksPerSecond;
|
||||
}, 'source playback at $at');
|
||||
final played = await controller.session!.refresh();
|
||||
expect(played.message, isNull);
|
||||
await controller.togglePlayback();
|
||||
final paused = await controller.session!.refresh();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
final still = await controller.session!.refresh();
|
||||
expect(still.state, PlaybackState.paused);
|
||||
expect(
|
||||
still.position.seconds,
|
||||
closeTo(paused.position.seconds, .05),
|
||||
);
|
||||
observations.add({
|
||||
'at': at,
|
||||
'playedTo': played.position.seconds,
|
||||
'pausedAt': paused.position.seconds,
|
||||
});
|
||||
}
|
||||
result['sourcePlayback'] = observations;
|
||||
} finally {
|
||||
await controller.close();
|
||||
controller.dispose();
|
||||
}
|
||||
});
|
||||
final clipId = ElementId('audio-clip');
|
||||
await check('importOriginalAndInsertAudio', () async {
|
||||
final imported = await projects.importExternalMedia(projectId, [
|
||||
ExternalMediaFile(path: file.path),
|
||||
]);
|
||||
expect(imported!.failures, isEmpty);
|
||||
final asset = imported.assets.firstWhere(
|
||||
(a) => a.name == p.basename(file.path),
|
||||
);
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
const SetProjectCanvas(width: 320, height: 180),
|
||||
);
|
||||
await session.commands.insertMedia(
|
||||
sequence: sequence,
|
||||
assetId: asset.id,
|
||||
clipId: clipId,
|
||||
index: 0,
|
||||
sourceStart: RationalTime.seconds(2),
|
||||
duration: RationalTime.seconds(8),
|
||||
);
|
||||
final binding = session.mediaBinding(
|
||||
session.persistence
|
||||
.timeline(sequence)
|
||||
.exportDto()
|
||||
.elements
|
||||
.single
|
||||
.payloadRef!,
|
||||
);
|
||||
expect(binding!.videoTrackIndex, isNull);
|
||||
expect(binding.audioTrackIndex, 0);
|
||||
});
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: EditorPreviewPanel(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 280,
|
||||
child: EditorPropertiesPanel(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: 210,
|
||||
child: EditorTimelinePanel(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await check('initializeEditorPreview', () async {
|
||||
await container.read(
|
||||
editorPreviewProvider(projectId, timelineId).future,
|
||||
);
|
||||
await until(() {
|
||||
final state = container.read(
|
||||
editorPreviewProvider(projectId, timelineId),
|
||||
);
|
||||
if (state.hasError) throw StateError('${state.error}');
|
||||
if (state.asData?.value?.error != null) {
|
||||
throw StateError('${state.asData!.value!.error}');
|
||||
}
|
||||
return state.asData?.value?.ready == true;
|
||||
}, 'editor preview initialization');
|
||||
});
|
||||
final preview = container
|
||||
.read(editorPreviewProvider(projectId, timelineId))
|
||||
.requireValue!;
|
||||
ElementRecord record() {
|
||||
final q = session.persistence.timeline(sequence).current.query();
|
||||
return q.element(q.elementById(clipId)!);
|
||||
}
|
||||
|
||||
Future<void> settled() async {
|
||||
await tester.pump();
|
||||
await until(
|
||||
() => !preview.busy && preview.ready,
|
||||
'preview synchronization',
|
||||
);
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
|
||||
Future<void> seek(double seconds) async {
|
||||
await preview.controlPreview(
|
||||
sequence,
|
||||
PreviewAction.seek,
|
||||
at: CommandTime((seconds * 1000).round(), 1000),
|
||||
);
|
||||
await settled();
|
||||
expect(
|
||||
(await preview.session!.refresh()).position.seconds,
|
||||
closeTo(seconds, .1),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> playback() async {
|
||||
await seek(0);
|
||||
await tester.tap(find.byTooltip('播放').first);
|
||||
await until(() {
|
||||
if (preview.error != null) throw StateError('${preview.error}');
|
||||
final snapshot = preview.session!.snapshot;
|
||||
if (snapshot?.message != null) {
|
||||
throw StateError('${snapshot!.message}');
|
||||
}
|
||||
return preview.playing &&
|
||||
preview.positionTick > TimelineClock.ticksPerSecond / 2;
|
||||
}, 'timeline playback');
|
||||
final playing = await preview.session!.refresh();
|
||||
await tester.tap(find.byTooltip('暂停播放').first);
|
||||
await until(
|
||||
() => !preview.playing && !preview.busy,
|
||||
'timeline pause',
|
||||
);
|
||||
final paused = await preview.session!.refresh();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
expect(
|
||||
(await preview.session!.refresh()).position.seconds,
|
||||
closeTo(paused.position.seconds, .05),
|
||||
);
|
||||
(result.putIfAbsent(
|
||||
'timelinePlayback',
|
||||
() => <Map<String, Object?>>[],
|
||||
) as List).add({
|
||||
'stage': stage,
|
||||
'playedTo': playing.position.seconds,
|
||||
});
|
||||
}
|
||||
|
||||
ExecutionPlan plan() => const ExecutionCompiler()
|
||||
.compile(
|
||||
ExecutionInput(
|
||||
timeline: session.persistence.timeline(sequence),
|
||||
media: {
|
||||
record().payloadRef!: ExecutionMediaBinding(
|
||||
media: media,
|
||||
videoTrackSelection: null,
|
||||
audioTrackSelection: TrackSelection.id(
|
||||
info.audioTrackIds.first!,
|
||||
),
|
||||
audioTiming: info.audioTracks.first,
|
||||
),
|
||||
},
|
||||
renderSize: RenderSize(320, 180),
|
||||
parameterTargets: {
|
||||
...ClipTransform.targets,
|
||||
...ClipAudioGain.targets,
|
||||
},
|
||||
editorOnlyParameters: const {ClipAudioGain.detachedId},
|
||||
),
|
||||
)
|
||||
.plan;
|
||||
Future<MediaWaveform> export(String suffix, double duration) async {
|
||||
final compiled = plan();
|
||||
expect(compiled.visualLayers, isEmpty);
|
||||
expect(compiled.audioLayers, hasLength(1));
|
||||
final destination = File(
|
||||
p.join(
|
||||
root.path,
|
||||
'${index.toString().padLeft(2, '0')}-$suffix.mp4',
|
||||
),
|
||||
).uri;
|
||||
final uri = await preview.session!.export(compiled, destination);
|
||||
final exported = MediaReference(id: suffix, uri: uri);
|
||||
final metadata = await runtime.probe(exported);
|
||||
expect(metadata.audioTrackCount, 1);
|
||||
expect(metadata.duration.seconds, closeTo(duration, .12));
|
||||
final wave = await runtime.waveform(
|
||||
WaveformRequest(
|
||||
media: exported,
|
||||
baseBucketCount: 64,
|
||||
levelCount: 1,
|
||||
),
|
||||
);
|
||||
expect(wave.frameCount / wave.sampleRate, closeTo(duration, .12));
|
||||
(result.putIfAbsent(
|
||||
'exports',
|
||||
() => <Map<String, Object?>>[],
|
||||
) as List).add({
|
||||
'kind': suffix,
|
||||
'path': uri.toFilePath(),
|
||||
'duration': metadata.duration.seconds,
|
||||
'rms': _rms(wave),
|
||||
});
|
||||
return wave;
|
||||
}
|
||||
|
||||
await check('editorPlayPauseAndScrub', () async {
|
||||
await playback();
|
||||
for (final at in [6.5, .5, 7.5, 2.0, 0.0]) {
|
||||
await seek(at);
|
||||
}
|
||||
});
|
||||
await check('splitToolbarUndoRedo', () async {
|
||||
preview.selectVisual(clipId);
|
||||
await seek(4);
|
||||
await tester.tap(find.byTooltip('在播放头处分割'));
|
||||
await settled();
|
||||
expect(record().duration, 4 * TimelineClock.ticksPerSecond);
|
||||
expect(
|
||||
session.persistence.timeline(sequence).exportDto().elements,
|
||||
hasLength(2),
|
||||
);
|
||||
await session.commands.executeEdit(sequence, const UndoEdit());
|
||||
await settled();
|
||||
expect(record().duration, 8 * TimelineClock.ticksPerSecond);
|
||||
await session.commands.executeEdit(sequence, const RedoEdit());
|
||||
await settled();
|
||||
final other = session.persistence
|
||||
.timeline(sequence)
|
||||
.exportDto()
|
||||
.elements
|
||||
.firstWhere((e) => e.id != clipId);
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
DeleteClip(other.id.value),
|
||||
);
|
||||
await settled();
|
||||
await playback();
|
||||
});
|
||||
late MediaWaveform baseline;
|
||||
await check('baselineExport', () async {
|
||||
baseline = await export('baseline', 4);
|
||||
expect(_rms(baseline), greaterThan(.0001));
|
||||
});
|
||||
await check('speedSliderAndRenderedHalfDouble', () async {
|
||||
preview.selectVisual(clipId);
|
||||
await seek(0);
|
||||
await tester.tap(find.byKey(const ValueKey('property-tab-speed')));
|
||||
await tester.pump();
|
||||
final slider = find.descendant(
|
||||
of: find.byKey(const Key('clip-speed-slider')),
|
||||
matching: find.byType(Slider),
|
||||
);
|
||||
expect(slider, findsOneWidget);
|
||||
for (final speed in [2.0, .5, 1.0]) {
|
||||
final bounds = tester.getRect(slider);
|
||||
final position = (math.log(speed) / math.ln10 + 1) / 3;
|
||||
final gesture = await tester.startGesture(
|
||||
Offset(
|
||||
bounds.left +
|
||||
12 +
|
||||
(bounds.width - 24) * tester.widget<Slider>(slider).value,
|
||||
bounds.center.dy,
|
||||
),
|
||||
);
|
||||
await gesture.moveTo(
|
||||
Offset(
|
||||
bounds.left + 12 + (bounds.width - 24) * position,
|
||||
bounds.center.dy,
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await gesture.up();
|
||||
await settled();
|
||||
expect(session.clipSpeed(record()), closeTo(speed, .05));
|
||||
expect(
|
||||
record().duration,
|
||||
closeTo(
|
||||
4 * TimelineClock.ticksPerSecond / speed,
|
||||
TimelineClock.ticksPerSecond / 4,
|
||||
),
|
||||
);
|
||||
await playback();
|
||||
if (speed != 1) {
|
||||
final wave = await export(
|
||||
'speed-$speed',
|
||||
record().duration / TimelineClock.ticksPerSecond,
|
||||
);
|
||||
expect(_rms(wave), greaterThan(.0001));
|
||||
}
|
||||
}
|
||||
session.setClipSpeed(sequence, clipId, 1);
|
||||
await settled();
|
||||
});
|
||||
await check('gainMuteAndRenderedAudio', () async {
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
const SetClipAudio(clipId: 'audio-clip', db: -6, muted: false),
|
||||
);
|
||||
await settled();
|
||||
await playback();
|
||||
final gained = await export('gain-minus6', 4);
|
||||
final ratio = _rms(gained) / _rms(baseline);
|
||||
expect(ratio, closeTo(math.pow(10, -6 / 20).toDouble(), .06));
|
||||
result['gainRmsRatio'] = ratio;
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
const SetClipAudio(clipId: 'audio-clip', db: -6, muted: true),
|
||||
);
|
||||
await settled();
|
||||
await playback();
|
||||
expect(
|
||||
_rms(await export('muted', 4)),
|
||||
lessThanOrEqualTo(1 / 32768),
|
||||
);
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
const SetClipAudio(clipId: 'audio-clip', db: 0, muted: false),
|
||||
);
|
||||
await settled();
|
||||
});
|
||||
await check('audioKeyframesInterpolationAndRenderedFade', () async {
|
||||
for (final entry in [(0, 0.0), (3500, -10.5)]) {
|
||||
await session.commands.executeEdit(
|
||||
sequence,
|
||||
EditKeyframe(
|
||||
clipId: 'audio-clip',
|
||||
parameterId: ClipAudioGain.gainId,
|
||||
at: CommandTime(entry.$1, 1000),
|
||||
action: KeyframeAction.set,
|
||||
value: entry.$2,
|
||||
interpolation: KeyInterpolation.linear,
|
||||
),
|
||||
);
|
||||
}
|
||||
await settled();
|
||||
final curve = record().parameters![ClipAudioGain.gainId]!;
|
||||
expect(curve.toDto().keyframes, hasLength(2));
|
||||
expect(
|
||||
curve.valueAt(
|
||||
record().sourceStart + TimelineClock.ticksPerSecond,
|
||||
),
|
||||
closeTo(-3, .01),
|
||||
);
|
||||
await playback();
|
||||
final faded = await export('keyframe-fade', 4);
|
||||
final reference = baseline.levels.first.channels.first;
|
||||
final rendered = faded.levels.first.channels.first;
|
||||
double ratioAt(int start, int end) {
|
||||
final ratios = <double>[];
|
||||
for (var bucket = start; bucket < end; bucket++) {
|
||||
final at = bucket * 3 + 2;
|
||||
if (reference[at] > .001) {
|
||||
ratios.add(rendered[at] / reference[at]);
|
||||
}
|
||||
}
|
||||
expect(ratios, isNotEmpty);
|
||||
return ratios.reduce((a, b) => a + b) / ratios.length;
|
||||
}
|
||||
|
||||
final early = ratioAt(4, 12);
|
||||
final late = ratioAt(48, 56);
|
||||
expect(early, closeTo(.84, .15));
|
||||
expect(late, closeTo(.33, .15));
|
||||
expect(late, lessThan(early * .65));
|
||||
result['keyframeRatios'] = {'early': early, 'late': late};
|
||||
});
|
||||
await check('saveAndReadPersistedAudioEdits', () async {
|
||||
await session.flush();
|
||||
expect(session.saveError, isNull);
|
||||
final projectPath = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.activeProject!
|
||||
.path;
|
||||
final edits = await savedEdits.capture(
|
||||
projectPath,
|
||||
timelineId,
|
||||
session,
|
||||
sequence,
|
||||
);
|
||||
expect(
|
||||
((edits['clips'] as List).single as Map)['parameters'],
|
||||
hasLength(greaterThanOrEqualTo(2)),
|
||||
);
|
||||
result['savedTimelineId'] = timelineId;
|
||||
result['savedProject'] = projectPath;
|
||||
});
|
||||
}
|
||||
result['passed'] = true;
|
||||
} catch (error, stack) {
|
||||
checks.add({
|
||||
'stage': stage,
|
||||
'passed': false,
|
||||
'error': '$error',
|
||||
'stack': '$stack',
|
||||
});
|
||||
debugPrint('AUDIO_MEDIA_FAILED $stage $error\n$stack');
|
||||
}
|
||||
final after = await file.stat();
|
||||
result['sourceUnchanged'] =
|
||||
before.size == after.size &&
|
||||
before.modified == after.modified &&
|
||||
beforeHash == (await sha256.bind(file.openRead()).first).toString();
|
||||
if (result['sourceUnchanged'] != true) result['passed'] = false;
|
||||
save();
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
if (testedTimeline != null) {
|
||||
await container.read(previewControllerRegistryProvider).invalidate((
|
||||
projectId,
|
||||
testedTimeline,
|
||||
));
|
||||
}
|
||||
releaseTimeline?.call();
|
||||
}
|
||||
container.dispose();
|
||||
disposed = true;
|
||||
await savedEdits.verify(
|
||||
wait: tester.pump,
|
||||
onVerified: (projectPath, timelineId, edits) {
|
||||
final result = results.singleWhere(
|
||||
(r) =>
|
||||
r['savedProject'] == projectPath &&
|
||||
r['savedTimelineId'] == timelineId,
|
||||
);
|
||||
result['savedEditsIdenticalAfterReopen'] = true;
|
||||
save();
|
||||
},
|
||||
);
|
||||
expect(
|
||||
results.where((file) => file['passed'] != true).toList(),
|
||||
isEmpty,
|
||||
reason: 'See ${report.path}',
|
||||
);
|
||||
}, timeout: const Timeout(Duration(minutes: 120)));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,203 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
import '../test/support/preview_fixture.dart';
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
const source = String.fromEnvironment('CUTDEX_SEEK_SOURCE');
|
||||
const report = String.fromEnvironment('CUTDEX_SEEK_REPORT');
|
||||
testWidgets('original source seek and live playhead timing', (tester) async {
|
||||
expect(
|
||||
report,
|
||||
isNotEmpty,
|
||||
reason: 'Set CUTDEX_SEEK_REPORT to an output file.',
|
||||
);
|
||||
final media = File(source);
|
||||
expect(await media.exists(), isTrue);
|
||||
final channel = _SeekChannel();
|
||||
final runtime = CutdexRuntime(channel: channel);
|
||||
final info = await runtime.probe(
|
||||
MediaReference(id: 'source', uri: media.uri),
|
||||
);
|
||||
expect(info.videoTrackCount, greaterThan(0));
|
||||
final duration = info.duration.seconds;
|
||||
expect(duration, greaterThanOrEqualTo(5));
|
||||
final start = duration * .01;
|
||||
final middle = duration * .5;
|
||||
final nearbyStep = math.min(1.0, duration * .01);
|
||||
final fixture = await createPreviewFixture(
|
||||
media.uri,
|
||||
hasAudio: info.audioTrackCount > 0,
|
||||
clipDuration: RationalTime(
|
||||
info.duration.numerator,
|
||||
info.duration.denominator,
|
||||
),
|
||||
renderSize: {'width': 1280, 'height': 720},
|
||||
);
|
||||
final preview = PreviewController(
|
||||
timeline: fixture.timeline,
|
||||
activeSequence: () => fixture.timeline.activeSequenceId,
|
||||
viewForSequence: fixture.timeline.view,
|
||||
runtime: runtime,
|
||||
);
|
||||
addTearDown(() async {
|
||||
await preview.close();
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
await preview.initialize();
|
||||
expect(preview.error, isNull);
|
||||
final project = fixture.workspace.project!.info.id;
|
||||
final view = fixture.timeline.view(fixture.timeline.activeSequenceId!);
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
editorTimelineProvider(
|
||||
project,
|
||||
'project',
|
||||
).overrideWith((ref) async => fixture.timeline),
|
||||
editorPreviewProvider(
|
||||
project,
|
||||
'project',
|
||||
).overrideWith((ref) async => preview),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: EditorPreviewPanel(projectId: project, timelineId: 'project'),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final samples = <Map<String, Object?>>[];
|
||||
Future<void> seek(double at) => preview.controlPreview(
|
||||
fixture.timeline.activeSequenceId!,
|
||||
PreviewAction.seek,
|
||||
at: CommandTime((at * 1000).round(), 1000),
|
||||
);
|
||||
for (final at in <double>[
|
||||
start,
|
||||
start + nearbyStep * .2,
|
||||
start + nearbyStep,
|
||||
start + nearbyStep * .9,
|
||||
start + nearbyStep * .8,
|
||||
middle,
|
||||
middle + nearbyStep * .2,
|
||||
middle + nearbyStep,
|
||||
middle + nearbyStep * .9,
|
||||
duration * .25,
|
||||
duration * .99,
|
||||
start,
|
||||
]) {
|
||||
final started = Stopwatch()..start();
|
||||
await seek(at);
|
||||
final acknowledged = started.elapsedMicroseconds / 1000;
|
||||
await tester.pump();
|
||||
samples.add({
|
||||
'at': at,
|
||||
'acknowledgedMs': acknowledged,
|
||||
'pumpedMs': started.elapsedMicroseconds / 1000,
|
||||
});
|
||||
expect(preview.error, isNull);
|
||||
}
|
||||
final drags = <Map<String, Object?>>[];
|
||||
for (final pattern in [
|
||||
(start, math.min(.05, duration * .01 / 59)),
|
||||
(middle, duration * .4 / 59),
|
||||
]) {
|
||||
await seek(pattern.$1);
|
||||
final started = Stopwatch()..start();
|
||||
final observations = <Map<String, Object?>>[];
|
||||
var previous = preview.session!.snapshot!.position.seconds;
|
||||
view.beginScrubbing();
|
||||
var target = pattern.$1;
|
||||
for (var index = 0; index < 120; index++) {
|
||||
target = pattern.$1 + (index < 60 ? index : 119 - index) * pattern.$2;
|
||||
view.seekTo((target * TimelineClock.ticksPerSecond).round());
|
||||
await tester.pump();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 16));
|
||||
final shown = preview.session!.snapshot!.position.seconds;
|
||||
if (shown != previous) {
|
||||
observations.add({
|
||||
'ms': started.elapsedMicroseconds / 1000,
|
||||
'requested': target,
|
||||
'nativeObserved': shown,
|
||||
});
|
||||
previous = shown;
|
||||
}
|
||||
}
|
||||
final release = Stopwatch()..start();
|
||||
view.endScrubbing();
|
||||
await seek(target);
|
||||
await preview.session!.refresh();
|
||||
expect(preview.session!.snapshot!.position.seconds, closeTo(target, .01));
|
||||
expect(preview.error, isNull);
|
||||
drags.add({
|
||||
'start': pattern.$1,
|
||||
'step': pattern.$2,
|
||||
'requests': 120,
|
||||
'durationMs': started.elapsedMicroseconds / 1000,
|
||||
'releaseMs': release.elapsedMicroseconds / 1000,
|
||||
'observations': observations,
|
||||
});
|
||||
}
|
||||
final output = File(report);
|
||||
await output.parent.create(recursive: true);
|
||||
await output.writeAsString(
|
||||
jsonEncode({
|
||||
'source': source,
|
||||
'durationSeconds': duration,
|
||||
'samples': samples,
|
||||
'drags': drags,
|
||||
'channelCalls': channel.samples,
|
||||
'error': preview.error?.toString(),
|
||||
'measurement': 'Real Profile preview panel and playhead controller; acknowledgment plus pumped frame, not physical display timestamp',
|
||||
}),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
}, skip: !Platform.isWindows || source.isEmpty);
|
||||
}
|
||||
|
||||
class _SeekChannel extends MethodChannel {
|
||||
_SeekChannel() : super('cutdex_runtime');
|
||||
final samples = <Map<String, Object?>>[];
|
||||
@override
|
||||
Future<T?> invokeMethod<T>(String method, [dynamic arguments]) async {
|
||||
final request = method == 'request'
|
||||
? jsonDecode(arguments['request'] as String) as Map
|
||||
: arguments as Map;
|
||||
final name = request['method'] ?? method;
|
||||
final started = Stopwatch()..start();
|
||||
final response = await super.invokeMethod<T>(method, arguments);
|
||||
if (['seek', 'skim', 'beginSkimming', 'endSkimming'].contains(name)) {
|
||||
samples.add({
|
||||
'method': name,
|
||||
'ms': started.elapsedMicroseconds / 1000,
|
||||
'time': request['time'],
|
||||
});
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user