refactor(core): own editor UI and pin verified native releases
Gitea CI / Check code and tests (pull_request) Failing after 8s
Gitea CI / Build Android APK (pull_request) Skipped
Gitea CI / Build Windows x64 app (pull_request) Skipped
Gitea CI / Audit and package Windows x64 (pull_request) Skipped
Gitea CI / Assemble and validate CI artifacts (pull_request) Skipped
Gitea CI / Gitea CI passed (pull_request) Failing after 1s

This commit is contained in:
lingjhf committed 2026-10-12 03:20:29 +08:00
1 parent 796a3852a2
commit 38ca180cf7
354 files changed
+29841 -642

No files matched your search

@@ -0,0 +1,16 @@
import 'dart:async';
/// Release every owned resource, then report the first cleanup failure.
Future<void> completeCleanup(List<FutureOr<void> Function()> actions) async {
Object? failure;
StackTrace? trace;
for (final action in actions) {
try {
await action();
} catch (error, stack) {
failure ??= error;
trace ??= stack;
}
}
if (failure != null) Error.throwWithStackTrace(failure, trace!);
}
@@ -0,0 +1,353 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:cutdex_core/editor.dart';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'preview_controller.dart';
import 'selection_decoration.dart';
import 'preview_geometry.dart';
class MaskInteractionOverlay extends StatefulWidget {
const MaskInteractionOverlay({
super.key,
required this.controller,
required this.canvasRect,
this.obscure = false,
});
final PreviewController controller;
final Rect canvasRect;
final bool obscure;
@override
State<MaskInteractionOverlay> createState() => _MaskInteractionOverlayState();
}
class _MaskInteractionOverlayState extends State<MaskInteractionOverlay> {
final _focus = FocusNode();
late final _label = SelectionLabel(
onChanged: () {
if (mounted) setState(() {});
},
);
ClipMask? _base;
_MaskGeometry? _geometry;
Offset? _down;
int _handle = -1;
MouseCursor _cursor = SystemMouseCursors.basic;
int? _generation;
int get generation => widget.obscure
? widget.controller.obscureEditGeneration
: widget.controller.maskEditGeneration;
void cancel() => widget.obscure
? widget.controller.cancelObscureEdit()
: widget.controller.cancelMaskEdit();
void _cancel() {
if (_base == null) return;
_base = null;
if (_generation == generation) {
cancel();
}
}
@override
void dispose() {
_label.dispose();
final controller = widget.controller;
final generation = _generation;
final obscure = widget.obscure;
if (_base != null) {
scheduleMicrotask(() {
if (generation ==
(obscure
? controller.obscureEditGeneration
: controller.maskEditGeneration)) {
if (obscure) {
controller.cancelObscureEdit();
} else {
controller.cancelMaskEdit();
}
}
});
}
_focus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: Listenable.merge([
widget.controller,
widget.controller.positionChanges,
]),
builder: (context, _) {
final c = widget.controller;
final id = widget.obscure
? c.obscureEditingElement
: c.maskEditingElement;
final mask = id == null
? null
: (widget.obscure ? c.obscureFor(id) : c.maskFor(id));
final visual = id == null
? null
: c.visualsForSelection({id}).firstOrNull;
if (mask == null || visual == null) {
return const SizedBox.shrink();
}
final geometry = _MaskGeometry(visual, widget.canvasRect, c.canvas.width);
final points = geometry.handles(mask).take(4).toList();
return Focus(
focusNode: _focus,
onFocusChange: (focused) {
if (!focused) _cancel();
},
onKeyEvent: (_, event) {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape &&
_base != null) {
_cancel();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: MouseRegion(
cursor: _cursor,
onHover: (event) {
final cursor = selectionCursor(points, event.localPosition);
if (cursor != _cursor) setState(() => _cursor = cursor);
},
child: GestureDetector(
dragStartBehavior: DragStartBehavior.down,
key: widget.obscure ? const Key('obscure-interaction') : null,
behavior: HitTestBehavior.translucent,
onPanStart: c.canPlay
? (details) {
final p = details.localPosition;
_handle = selectionResizeCorner(points, p);
if (_handle < 0 &&
!widget.obscure &&
selectionRotationCorner(points, p) >= 0) {
_handle = 4;
}
if (_handle < 0 && !geometry.path(mask).contains(p)) return;
_focus.requestFocus();
_base = mask;
_geometry = geometry;
_down = p;
final preparing = widget.obscure
? c.beginObscureEdit()
: c.beginMaskEdit();
final started = _generation = generation;
unawaited(
preparing
.then((ready) {
if (!ready && started == generation) _cancel();
return ready;
})
.catchError((Object _) {
if (started == _generation &&
started == generation) {
_cancel();
}
return false;
}),
);
}
: null,
onPanUpdate: (details) {
final base = _base;
final g = _geometry;
if (base == null || g == null || _generation != generation) {
return;
}
final p = g.local(details.localPosition);
final start = g.local(_down!);
ClipMask value;
if (_handle == 4) {
final a = math.atan2(p.dy - base.y, (p.dx - base.x) * g.aspect);
final b = math.atan2(
start.dy - base.y,
(start.dx - base.x) * g.aspect,
);
var angle = base.rotation + (a - b) * 180 / math.pi;
if (HardwareKeyboard.instance.isShiftPressed) {
angle = (angle / 15).round() * 15.0;
}
value = base.copyWith(
rotation: normalizeRotationDegrees(angle),
);
} else if (_handle >= 0) {
final angle = base.rotation * math.pi / 180;
final d = Offset((p.dx - base.x) * g.aspect, p.dy - base.y);
final x = d.dx * math.cos(angle) + d.dy * math.sin(angle);
final y = -d.dx * math.sin(angle) + d.dy * math.cos(angle);
value = base.copyWith(
width: (x.abs() * 2 / g.aspect).clamp(
ClipMask.minExtent,
widget.obscure
? ClipObscureAnimation.maxExtent
: ClipMask.maxExtent,
),
height: (y.abs() * 2).clamp(
ClipMask.minExtent,
widget.obscure
? ClipObscureAnimation.maxExtent
: ClipMask.maxExtent,
),
);
} else {
value = base.copyWith(
x: (base.x + p.dx - start.dx).clamp(
ClipMask.minPosition,
ClipMask.maxPosition,
),
y: (base.y + p.dy - start.dy).clamp(
ClipMask.minPosition,
ClipMask.maxPosition,
),
);
}
if (widget.obscure) {
c.updateObscure(value);
} else {
c.updateMask(value);
}
},
onPanEnd: (_) {
if (_base != null) {
_base = null;
if (_generation == generation) {
if (widget.obscure) {
c.endObscureEdit();
} else {
c.endMaskEdit();
}
}
}
},
onPanCancel: _cancel,
child: CustomPaint(
painter: _MaskPainter(
geometry,
mask,
MediaQuery.devicePixelRatioOf(context),
_label,
),
size: Size.infinite,
),
),
),
);
},
);
}
class _MaskGeometry {
_MaskGeometry(PreviewVisual visual, Rect canvas, double canvasWidth) {
final scale = canvas.width / canvasWidth;
outputScale = scale;
final corners = visual.geometry.corners;
origin = canvas.topLeft + corners[0] * scale;
xAxis = (corners[1] - corners[0]) * scale;
yAxis = (corners[3] - corners[0]) * scale;
aspect =
(visual.geometry.size.width / visual.transform.scale) /
(visual.geometry.size.height / visual.transform.scaleY);
}
late final Offset origin, xAxis, yAxis;
late final double aspect, outputScale;
Offset project(Offset p) => origin + xAxis * p.dx + yAxis * p.dy;
Offset local(Offset p) {
final d = p - origin;
final det = xAxis.dx * yAxis.dy - xAxis.dy * yAxis.dx;
if (det.abs() < 1e-9) return const Offset(.5, .5);
return Offset(
(d.dx * yAxis.dy - d.dy * yAxis.dx) / det,
(xAxis.dx * d.dy - xAxis.dy * d.dx) / det,
);
}
Offset point(ClipMask mask, double x, double y) {
final angle = mask.rotation * math.pi / 180;
final dx = x * mask.width * aspect, dy = y * mask.height;
return project(
Offset(
mask.x + (dx * math.cos(angle) - dy * math.sin(angle)) / aspect,
mask.y + dx * math.sin(angle) + dy * math.cos(angle),
),
);
}
List<Offset> handles(ClipMask mask) {
return [
point(mask, -.5, -.5),
point(mask, .5, -.5),
point(mask, .5, .5),
point(mask, -.5, .5),
];
}
Path path(ClipMask mask) {
final points = mask.shape == ClipMaskShape.ellipse
? [
for (var i = 0; i < 96; i++)
point(
mask,
math.cos(i * math.pi / 48) / 2,
math.sin(i * math.pi / 48) / 2,
),
]
: handles(mask).take(4).toList();
return Path()..addPolygon(points, true);
}
}
class _MaskPainter extends CustomPainter {
_MaskPainter(this.geometry, this.mask, this.devicePixelRatio, this.label)
: labelRevision = label.revision;
final int labelRevision;
final SelectionLabel label;
final _MaskGeometry geometry;
final ClipMask mask;
final double devicePixelRatio;
@override
void paint(Canvas canvas, Size size) {
final corners = geometry.handles(mask);
if (mask.shape == ClipMaskShape.ellipse) {
canvas.drawPath(
geometry.path(mask),
Paint()
..color = selectionBlue
..style = PaintingStyle.stroke
..strokeWidth = 1,
);
}
paintSelectionDecoration(
canvas,
corners,
devicePixelRatio: devicePixelRatio,
labelLayout: label,
dimensions: Size(
(corners[1] - corners[0]).distance / geometry.outputScale,
(corners[3] - corners[0]).distance / geometry.outputScale,
),
);
}
@override
bool shouldRepaint(covariant _MaskPainter oldDelegate) =>
labelRevision != oldDelegate.labelRevision ||
devicePixelRatio != oldDelegate.devicePixelRatio ||
geometry.origin != oldDelegate.geometry.origin ||
geometry.xAxis != oldDelegate.geometry.xAxis ||
geometry.yAxis != oldDelegate.geometry.yAxis ||
geometry.aspect != oldDelegate.geometry.aspect ||
geometry.outputScale != oldDelegate.geometry.outputScale ||
mask.shape != oldDelegate.mask.shape ||
mask.x != oldDelegate.mask.x ||
mask.y != oldDelegate.mask.y ||
mask.width != oldDelegate.mask.width ||
mask.height != oldDelegate.mask.height ||
mask.rotation != oldDelegate.mask.rotation;
}
@@ -0,0 +1,66 @@
import 'package:flutter/material.dart';
/// Fits the output canvas within the workspace; native rendering fits media
/// within this canvas using its own source geometry (including rotation).
class PreviewCanvas extends StatelessWidget {
const PreviewCanvas({
super.key,
required this.aspectRatio,
required this.child,
this.overlayBuilder,
this.horizontalPadding = 16,
this.alignment = Alignment.topCenter,
this.backgroundColor = Colors.black,
});
final double aspectRatio;
final double horizontalPadding;
final Alignment alignment;
final Color backgroundColor;
final Widget child;
final Widget Function(Rect canvasRect)? overlayBuilder;
@override
Widget build(BuildContext context) => RepaintBoundary(
child: ColoredBox(
key: const Key('preview-surface'),
color: Theme.of(context).colorScheme.surface,
child: LayoutBuilder(
builder: (context, constraints) {
final available = Size(
(constraints.maxWidth - horizontalPadding * 2).clamp(
0,
double.infinity,
),
constraints.maxHeight,
);
final fitted = applyBoxFit(
BoxFit.contain,
Size(aspectRatio, 1),
available,
).destination;
final rect = alignment.inscribe(
fitted,
Offset.zero & constraints.biggest,
);
return Stack(
fit: StackFit.expand,
clipBehavior: Clip.hardEdge,
children: [
Positioned.fromRect(
rect: rect,
child: ColoredBox(
key: const Key('preview-canvas'),
color: backgroundColor,
child: ClipRect(child: child),
),
),
if (overlayBuilder != null && rect.width > 0 && rect.height > 0)
Positioned.fill(child: overlayBuilder!(rect)),
],
);
},
),
),
);
}
@@ -0,0 +1,67 @@
part of 'preview_controller.dart';
enum PreviewCanvasEditMode { mask, obscure, distortion }
/// A single canvas tool owns a clip until release, explicit selection change or removal.
@immutable
class PreviewCanvasEditing {
const PreviewCanvasEditing({
required this.mode,
required this.element,
this.owner,
this.perspective = false,
});
final PreviewCanvasEditMode mode;
final ElementId element;
final Object? owner;
final bool perspective;
}
extension on PreviewController {
ElementId? _editingElement(PreviewCanvasEditMode mode) =>
_canvasEditing?.mode == mode ? _canvasEditing?.element : null;
void _setCanvasEditing(
PreviewCanvasEditMode mode,
ElementId? element, {
Object? owner,
bool perspective = false,
}) {
if (_closed) return;
final current = _canvasEditing;
if (element == null) {
if (current?.mode != mode) return;
} else if (current?.mode == mode &&
current?.element == element &&
identical(current?.owner, owner) &&
current?.perspective == perspective) {
return;
}
// Invalidate preparation and discard pending gestures before changing tools.
cancelTransform();
_selectedMaskId = null;
_canvasEditing = element == null
? null
: PreviewCanvasEditing(
mode: mode,
element: element,
owner: owner,
perspective: perspective,
);
if (element != null) selectVisual(element);
_notify();
}
void _releaseCanvasEditing(PreviewCanvasEditMode mode, Object owner) {
if (_canvasEditing?.mode == mode &&
identical(_canvasEditing?.owner, owner)) {
_setCanvasEditing(mode, null);
}
}
void _clearCanvasEditing() {
_canvasEditing = null;
_selectedMaskId = null;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,460 @@
import 'dart:math' as math;
import 'dart:ui';
import 'package:cutdex_core/editor.dart';
import 'package:cutdex_core/execution.dart';
import 'package:cutdex_core/timeline/model.dart';
export 'package:cutdex_core/editor/commands.dart' show CanvasAlignment;
/// Canonical angle for interactive rotation, in the range [-180, 180).
double normalizeRotationDegrees(double degrees) => (degrees + 180) % 360 - 180;
ClipTransform alignToCanvas(
PreviewVisual visual,
Size canvas,
CanvasAlignment alignment,
) {
final bounds = visual.geometry.bounds;
final delta = switch (alignment) {
CanvasAlignment.left => Offset(-bounds.left, 0),
CanvasAlignment.horizontalCenter => Offset(
canvas.width / 2 - bounds.center.dx,
0,
),
CanvasAlignment.right => Offset(canvas.width - bounds.right, 0),
CanvasAlignment.top => Offset(0, -bounds.top),
CanvasAlignment.verticalCenter => Offset(
0,
canvas.height / 2 - bounds.center.dy,
),
CanvasAlignment.bottom => Offset(0, canvas.height - bounds.bottom),
};
final local = visual.geometry.localDelta(delta);
return visual.transform.copyWith(
x: visual.transform.x + local.dx / canvas.width,
y: visual.transform.y + local.dy / canvas.height,
);
}
/// Geometry in output pixels, independent of widget size and device pixel ratio.
class PreviewGeometry {
const PreviewGeometry({
required this.center,
required this.size,
this.rotation = 0,
this.distortion = const ClipDistortion(),
}) : _execution = null;
factory PreviewGeometry.fromExecution(ExecutionVisualGeometry geometry) {
final points = geometry.corners;
final x = points[1] - points[0];
final y = points[3] - points[0];
return PreviewGeometry._(
Offset((points[0].x + points[2].x) / 2, (points[0].y + points[2].y) / 2),
Size(x.magnitude, y.magnitude),
math.atan2(x.y, x.x) * 180 / math.pi,
geometry,
);
}
const PreviewGeometry._(
this.center,
this.size,
this.rotation,
this._execution,
) : distortion = const ClipDistortion();
final ExecutionVisualGeometry? _execution;
final Offset center;
final Size size;
final double rotation;
final ClipDistortion distortion;
Offset rotate(Offset p) {
final a = rotation * math.pi / 180;
return Offset(
p.dx * math.cos(a) - p.dy * math.sin(a),
p.dx * math.sin(a) + p.dy * math.cos(a),
);
}
List<Offset> get corners => _execution != null
? [for (final p in _execution.corners) Offset(p.x, p.y)]
: [
for (var i = 0; i < 4; i++)
center +
rotate(
Offset(
(i == 0 || i == 3 ? -.5 : .5) * size.width +
distortion.values[i * 2] * size.width,
(i < 2 ? -.5 : .5) * size.height +
distortion.values[i * 2 + 1] * size.height,
),
),
];
Rect get bounds {
final points = corners;
return Rect.fromLTRB(
points.map((p) => p.dx).reduce(math.min),
points.map((p) => p.dy).reduce(math.min),
points.map((p) => p.dx).reduce(math.max),
points.map((p) => p.dy).reduce(math.max),
);
}
/// Handles follow the video's local corners through rotation.
List<Offset> get selectionCorners => corners;
Size get distortionSize {
final s = _execution?.distortionSize;
return s == null ? size : Size(s.x, s.y);
}
Offset distortionDelta(Offset delta) {
final p = _execution?.distortionDelta(ExecutionPoint(delta.dx, delta.dy));
if (p != null) return Offset(p.x, p.y);
final a = -rotation * math.pi / 180;
return Offset(
(delta.dx * math.cos(a) - delta.dy * math.sin(a)) / size.width,
(delta.dx * math.sin(a) + delta.dy * math.cos(a)) / size.height,
);
}
bool contains(Offset p) {
final points = corners;
final first = points[1] - points[0], second = points[2] - points[1];
final sign = (first.dx * second.dy - first.dy * second.dx).sign;
if (sign == 0) return false;
for (var i = 0; i < 4; i++) {
final edge = points[(i + 1) % 4] - points[i], d = p - points[i];
if (sign * (edge.dx * d.dy - edge.dy * d.dx) < -1e-9) return false;
}
return true;
}
Offset localDelta(Offset delta) {
final mapped = _execution?.localDelta(ExecutionPoint(delta.dx, delta.dy));
return mapped == null ? delta : Offset(mapped.x, mapped.y);
}
PreviewGeometry changed(ClipTransform from, ClipTransform to, Size canvas) {
final execution = _execution;
if (execution != null) {
return PreviewGeometry.fromExecution(
execution.changed(
distortion: to.distortion,
x: to.x - from.x,
y: to.y - from.y,
scaleX: to.scale / from.scale,
scaleY: to.scaleY / from.scaleY,
rotation: to.rotation - from.rotation,
),
);
}
return PreviewGeometry(
center:
center +
Offset(
(to.x - from.x) * canvas.width,
(to.y - from.y) * canvas.height,
),
size: Size(
size.width * to.scale / from.scale,
size.height * to.scaleY / from.scaleY,
),
distortion: to.distortion,
rotation: rotation + to.rotation - from.rotation,
);
}
}
class PreviewVisual {
const PreviewVisual({
required this.layerId,
required this.elementId,
required this.geometry,
required this.transform,
required this.lane,
});
final String layerId;
final ElementId elementId;
final PreviewGeometry geometry;
final ClipTransform transform;
final int lane;
}
class CanvasSnap {
const CanvasSnap._(
this.delta,
this.verticalGuides,
this.horizontalGuides,
this._x,
this._y,
this._canvas,
);
final Offset delta;
final List<double> verticalGuides;
final List<double> horizontalGuides;
final _SnapMatch? _x;
final _SnapMatch? _y;
final Size _canvas;
factory CanvasSnap.guides(PreviewGeometry geometry, Size canvas) {
final b = geometry.bounds;
return CanvasSnap._(
Offset.zero,
_alignedGuides([b.left, b.center.dx, b.right], canvas.width, 0),
_alignedGuides([b.top, b.center.dy, b.bottom], canvas.height, 0),
null,
null,
canvas,
);
}
}
enum _SnapAnchor { start, center, end }
class _SnapMatch {
const _SnapMatch(this.anchor, this.target);
final _SnapAnchor anchor;
final _SnapAnchor target;
// Only break equal-distance ties; proximity still wins when acquiring a lock.
int get priority => anchor == target ? (anchor == .center ? 0 : 1) : 2;
}
/// Evaluate unsnapped pointer geometry, never the last corrected position.
/// Keep the previous anchor/target pair until it exceeds the release threshold.
/// Display guides are all exact alignments AFTER correction, not snap candidates.
CanvasSnap snapToCanvas(
PreviewGeometry geometry,
Size canvas,
double threshold, {
CanvasSnap? previous,
double? releaseThreshold,
}) {
final release = releaseThreshold ?? threshold * 5 / 3;
if (!threshold.isFinite ||
threshold <= 0 ||
!release.isFinite ||
release < threshold) {
throw ArgumentError(
'Snap thresholds must be finite, positive, and release >= entry',
);
}
if (previous?._canvas != canvas) previous = null;
final b = geometry.bounds;
final xs = [b.left, b.center.dx, b.right];
final ys = [b.top, b.center.dy, b.bottom];
final x = _snapAxis(xs, canvas.width, threshold, release, previous?._x);
final y = _snapAxis(ys, canvas.height, threshold, release, previous?._y);
return CanvasSnap._(
Offset(x.$1, y.$1),
_alignedGuides(xs, canvas.width, x.$1),
_alignedGuides(ys, canvas.height, y.$1),
x.$2,
y.$2,
canvas,
);
}
(double, _SnapMatch?) _snapAxis(
List<double> anchors,
double extent,
double entry,
double release,
_SnapMatch? previous,
) {
final targets = [0.0, extent / 2, extent];
double correction(_SnapMatch match) =>
targets[match.target.index] - anchors[match.anchor.index];
if (previous != null) {
final delta = correction(previous);
if (delta.abs() <= release) return (delta, previous);
}
_SnapMatch? best;
var delta = 0.0;
for (final target in _SnapAnchor.values) {
for (final anchor in _SnapAnchor.values) {
final candidate = _SnapMatch(anchor, target);
final next = correction(candidate);
if (next.abs() > entry) continue;
if (best == null ||
next.abs() < delta.abs() - 1e-9 ||
((next.abs() - delta.abs()).abs() <= 1e-9 &&
candidate.priority < best.priority)) {
best = candidate;
delta = next;
}
}
}
return (delta, best);
}
List<double> _alignedGuides(
List<double> anchors,
double extent,
double delta,
) => List.unmodifiable([
for (final target in [0.0, extent / 2, extent])
if (anchors.any((anchor) => (anchor + delta - target).abs() <= 1e-6))
target,
]);
/// Scale about the opposite corner. Solve in the transformed edge basis so
/// unlocked resizing also works through rotated and nonuniformly scaled groups.
ClipTransform scaleFromCorner(
PreviewVisual visual,
int corner,
Offset pointer,
Size canvas, {
bool locked = true,
}) {
final points = visual.geometry.selectionCorners;
final fixed = points[(corner + 2) % 4];
final diagonal = points[corner] - fixed;
final moved = pointer - fixed;
final factor =
((moved.dx * diagonal.dx + moved.dy * diagonal.dy) /
diagonal.distanceSquared)
.clamp(
math.max(
.01 / visual.transform.scale,
.01 / visual.transform.scaleY,
),
math.min(
100 / visual.transform.scale,
100 / visual.transform.scaleY,
),
)
.toDouble();
var factorX = factor;
var factorY = factor;
if (!locked) {
final localDiagonal = visual.geometry.distortionDelta(diagonal);
final localMoved = visual.geometry.distortionDelta(moved);
if (localDiagonal.dx.abs() < 1e-12 || localDiagonal.dy.abs() < 1e-12) {
return visual.transform;
}
factorX = (localMoved.dx / localDiagonal.dx).clamp(
.01 / visual.transform.scale,
100 / visual.transform.scale,
);
factorY = (localMoved.dy / localDiagonal.dy).clamp(
.01 / visual.transform.scaleY,
100 / visual.transform.scaleY,
);
}
final scaled = visual.transform.copyWith(
scale: visual.transform.scale * factorX,
scaleY: visual.transform.scaleY * factorY,
);
final delta = visual.geometry.localDelta(
fixed -
visual.geometry
.changed(visual.transform, scaled, canvas)
.corners[(corner + 2) % 4],
);
return scaled.copyWith(
x: visual.transform.x + delta.dx / canvas.width,
y: visual.transform.y + delta.dy / canvas.height,
);
}
/// Resize snapping changes scale, never translates the fixed opposite corner.
(ClipTransform, CanvasSnap) snapScaleToCanvas(
PreviewVisual visual,
int corner,
Offset pointer,
Size canvas,
double threshold, {
required bool locked,
CanvasSnap? previous,
}) {
if (!locked) {
final snap = snapToCanvas(
PreviewGeometry(center: pointer, size: Size.zero),
canvas,
threshold,
previous: previous,
);
return (
scaleFromCorner(
visual,
corner,
pointer + snap.delta,
canvas,
locked: false,
),
snap,
);
}
final raw = scaleFromCorner(visual, corner, pointer, canvas);
final factor = raw.scale / visual.transform.scale;
final points = visual.geometry.corners;
final fixed = points[(corner + 2) % 4];
final bounds = visual.geometry.bounds;
var bestDistance = double.infinity;
var bestFactor = factor;
_SnapMatch? bestX;
_SnapMatch? bestY;
var retained = false;
// Bounds are affine in a positive uniform scale about the fixed corner.
// Ignore stationary anchors, which must not mask a moving edge's snap.
for (final horizontal in [true, false]) {
final origin = horizontal ? fixed.dx : fixed.dy;
final anchors = horizontal
? [bounds.left, bounds.center.dx, bounds.right]
: [bounds.top, bounds.center.dy, bounds.bottom];
final extent = horizontal ? canvas.width : canvas.height;
final targets = [0.0, extent / 2, extent];
final old = previous?._canvas == canvas
? (horizontal ? previous?._x : previous?._y)
: null;
for (final anchor in _SnapAnchor.values) {
final slope = anchors[anchor.index] - origin;
if (slope.abs() < 1e-9) continue;
for (final target in _SnapAnchor.values) {
final keep = old?.anchor == anchor && old?.target == target;
final distance = (targets[target.index] - origin - slope * factor)
.abs();
final candidate = (targets[target.index] - origin) / slope;
if (distance > threshold * (keep ? 5 / 3 : 1) ||
candidate * visual.transform.scale < .01 ||
candidate * visual.transform.scale > 100 ||
candidate * visual.transform.scaleY < .01 ||
candidate * visual.transform.scaleY > 100) {
continue;
}
if ((keep && !retained) ||
(keep == retained && distance < bestDistance)) {
retained = keep;
bestDistance = distance;
bestFactor = candidate;
bestX = horizontal ? _SnapMatch(anchor, target) : null;
bestY = horizontal ? null : _SnapMatch(anchor, target);
}
}
}
}
final value = scaleFromCorner(
visual,
corner,
fixed + (points[corner] - fixed) * bestFactor,
canvas,
);
final guides = CanvasSnap.guides(
visual.geometry.changed(visual.transform, value, canvas),
canvas,
);
return (
value,
CanvasSnap._(
Offset.zero,
guides.verticalGuides,
guides.horizontalGuides,
bestX,
bestY,
canvas,
),
);
}
@@ -0,0 +1,465 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:cutdex_core/editor.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/services.dart';
import 'preview_controller.dart';
import 'selection_decoration.dart';
import 'preview_geometry.dart';
import 'preview_transform_session.dart';
class PreviewInteractionOverlay extends StatefulWidget {
const PreviewInteractionOverlay({
super.key,
required this.controller,
required this.canvasRect,
this.onError,
});
final PreviewController controller;
final Rect canvasRect;
final void Function(Object error)? onError;
@override
State<PreviewInteractionOverlay> createState() =>
_PreviewInteractionOverlayState();
}
enum _Operation { move, scale, rotate, distort }
class _Drag {
_Drag(
this.edit,
this.visual,
this.operation,
this.down,
this.corner,
this.inputOffset,
) : value = visual.transform;
final PreviewTransformEdit edit;
final PreviewVisual visual;
final _Operation operation;
final Offset down;
final int corner;
final Offset inputOffset;
ClipTransform value;
CanvasSnap? snap;
Offset? pointer;
}
class _PreviewInteractionOverlayState extends State<PreviewInteractionOverlay> {
final _focus = FocusNode();
late final _label = SelectionLabel(onChanged: _rendered);
MouseCursor _cursor = SystemMouseCursors.basic;
_Drag? _drag;
Offset? _down;
_Drag? _pointerDrag;
final _edits = <PreviewTransformEdit>{};
Size get _canvas =>
Size(widget.controller.canvas.width, widget.controller.canvas.height);
@override
void initState() {
super.initState();
// Scene synchronization can change geometry without moving the playhead
// or changing selection. Observe it directly even when the host filters
// those notifications to keep the surrounding canvas stable.
widget.controller.positionChanges.addListener(_rendered);
widget.controller.transforms.presentation.addListener(_rendered);
}
void _rendered() {
if (mounted) setState(() {});
}
double get _scale => widget.canvasRect.width / _canvas.width;
// Use 1% of the displayed short side, capped at six logical pixels.
double get _snapThreshold =>
math.min(6.0, widget.canvasRect.shortestSide * .01) / _scale;
Offset _output(Offset p) => (p - widget.canvasRect.topLeft) / _scale;
Offset _screen(Offset p) => widget.canvasRect.topLeft + p * _scale;
PreviewVisual? get _selected {
final ids = widget.controller.selectedVisualIds;
if (ids.isEmpty) return null;
return widget.controller.visualsForSelection(ids).lastOrNull;
}
PreviewVisual? _hit(Offset point) => widget.canvasRect.contains(point)
? widget.controller.visuals.reversed
.where((v) => _displayGeometry(v).contains(_output(point)))
.firstOrNull
: null;
PreviewGeometry _displayGeometry(PreviewVisual visual) =>
visual.geometry.changed(
visual.transform,
widget.controller.transforms.displayedValueFor(visual.elementId) ??
visual.transform,
_canvas,
);
void _start(DragStartDetails details) {
_pointerDrag = null;
if (_drag != null) return;
final point = _down ?? details.localPosition;
var visual = _selected;
var operation = _Operation.move;
var corner = -1;
var inputOffset = Offset.zero;
if (visual != null) {
final displayed = _displayGeometry(visual);
final corners = displayed.selectionCorners.map(_screen).toList();
corner = selectionResizeCorner(corners, point);
if (corner >= 0) {
operation =
widget.controller.distortionEditingElement == visual.elementId
? _Operation.distort
: _Operation.scale;
inputOffset =
visual.geometry.selectionCorners[corner] -
displayed.selectionCorners[corner];
} else if (widget.controller.distortionEditingElement == null &&
selectionRotationCorner(corners, point) >= 0) {
operation = _Operation.rotate;
inputOffset = visual.geometry.center - displayed.center;
} else {
visual = _hit(point);
}
} else {
visual = _hit(point);
}
if (visual == null || _scale <= 0) return;
final edit = widget.controller.transforms.begin(visual);
if (edit == null) return;
_edits.add(edit);
// Hit the completed frame, but retain queued authored edits as the gesture
// baseline. A fixed offset prevents a pending frame from jumping a handle.
final drag = _Drag(
edit,
visual,
operation,
_output(point) + inputOffset,
corner,
inputOffset,
);
_pointerDrag = drag;
setState(() => _drag = drag);
// Recognition can consume the only move event of a fast mouse drag.
_updateAt(details.localPosition);
unawaited(
edit.done.then((_) {
final owned = _edits.remove(edit);
if (!mounted || !owned) return;
if (identical(drag, _drag)) {
_pointerDrag = null;
setState(() => _drag = null);
}
if (edit.error != null) {
widget.onError?.call(edit.error!);
}
}),
);
}
void _update(DragUpdateDetails details) {
if (identical(_pointerDrag, _drag)) _updateAt(details.localPosition);
}
void _updateAt(Offset position) {
final drag = _drag;
if (drag == null || drag.edit.cancelled) return;
drag.pointer = position;
final pointer = _output(position) + drag.inputOffset;
final original = drag.visual.transform;
ClipTransform next;
CanvasSnap? snap;
switch (drag.operation) {
case _Operation.move:
final delta = drag.visual.geometry.localDelta(pointer - drag.down);
next = original.copyWith(
x: original.x + delta.dx / _canvas.width,
y: original.y + delta.dy / _canvas.height,
);
if (!HardwareKeyboard.instance.isAltPressed) {
snap = snapToCanvas(
drag.visual.geometry.changed(original, next, _canvas),
_canvas,
_snapThreshold,
previous: drag.snap,
);
final correction = drag.visual.geometry.localDelta(snap.delta);
next = next.copyWith(
x: next.x + correction.dx / _canvas.width,
y: next.y + correction.dy / _canvas.height,
);
}
case _Operation.scale:
if (HardwareKeyboard.instance.isAltPressed) {
next = scaleFromCorner(
drag.visual,
drag.corner,
pointer,
_canvas,
locked: widget.controller.aspectRatioLocked,
);
} else {
(next, snap) = snapScaleToCanvas(
drag.visual,
drag.corner,
pointer,
_canvas,
_snapThreshold,
locked: widget.controller.aspectRatioLocked,
previous: drag.snap,
);
}
case _Operation.distort:
final delta = drag.visual.geometry.distortionDelta(pointer - drag.down);
final offsets = original.distortion.corners;
final p = offsets[drag.corner];
var pose = original.distortion.withCorner(
drag.corner,
p.$1 + delta.dx,
p.$2 + delta.dy,
);
if (widget.controller.distortionPerspective) {
final linked = drag.corner ^ 1;
final q = offsets[linked];
pose = pose.withCorner(linked, q.$1 - delta.dx, q.$2 + delta.dy);
}
next = original.copyWith(
distortion: pose.constrained(from: original.distortion),
);
case _Operation.rotate:
final center = drag.visual.geometry.center;
final from = drag.visual.geometry.localDelta(drag.down - center);
final to = drag.visual.geometry.localDelta(pointer - center);
final delta = math.atan2(to.dy, to.dx) - math.atan2(from.dy, from.dx);
var angle = original.rotation + delta * 180 / math.pi;
if (HardwareKeyboard.instance.isShiftPressed) {
angle = (angle / 15).round() * 15.0;
}
next = original.copyWith(rotation: normalizeRotationDegrees(angle));
}
setState(() {
drag.value = next;
drag.snap = snap;
});
drag.edit.update(drag.value);
}
void _end() {
final drag = _pointerDrag;
_pointerDrag = null;
if (drag == null) return;
unawaited(drag.edit.end());
setState(() => _drag = null);
}
void _cancel() {
final drag = _drag;
_pointerDrag = null;
drag?.edit.cancel();
if (mounted) setState(() => _drag = null);
}
@override
void didUpdateWidget(covariant PreviewInteractionOverlay oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
oldWidget.controller.positionChanges.removeListener(_rendered);
oldWidget.controller.transforms.presentation.removeListener(_rendered);
widget.controller.positionChanges.addListener(_rendered);
widget.controller.transforms.presentation.addListener(_rendered);
oldWidget.controller.cancelTransform();
}
if (oldWidget.controller != widget.controller ||
oldWidget.canvasRect != widget.canvasRect) {
for (final edit in _edits.toList()) {
edit.cancel();
}
_edits.clear();
_cancel();
} else if (_drag?.edit.cancelled ?? false) {
_cancel();
}
}
@override
void dispose() {
_label.dispose();
widget.controller.positionChanges.removeListener(_rendered);
widget.controller.transforms.presentation.removeListener(_rendered);
for (final edit in _edits) {
scheduleMicrotask(edit.cancel);
}
_edits.clear();
_focus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final drag = _drag;
final visual = drag?.visual ?? _selected;
final geometry = visual == null ? null : _displayGeometry(visual);
return Focus(
focusNode: _focus,
onKeyEvent: (_, event) {
if (event.logicalKey == LogicalKeyboardKey.altLeft ||
event.logicalKey == LogicalKeyboardKey.altRight) {
if (_drag?.pointer case final pointer?) _updateAt(pointer);
}
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape) {
if (_drag != null) {
_cancel();
} else if (widget.controller.distortionEditingElement != null) {
widget.controller.setDistortionEditing(null);
} else {
widget.controller.selectVisual(null);
}
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: MouseRegion(
onHover: (event) {
final corners = geometry?.selectionCorners.map(_screen).toList();
final cursor = corners == null
? SystemMouseCursors.basic
: widget.controller.distortionEditingElement != null
? selectionResizeCorner(corners, event.localPosition) >= 0
? SystemMouseCursors.precise
: SystemMouseCursors.move
: selectionCursor(corners, event.localPosition);
if (_cursor != cursor) setState(() => _cursor = cursor);
},
onExit: (_) => setState(() => _cursor = SystemMouseCursors.basic),
cursor: drag != null ? SystemMouseCursors.grabbing : _cursor,
child: Listener(
behavior: HitTestBehavior.opaque,
onPointerDown: (_) => unawaited(
widget.controller.pauseForCanvasInteraction().catchError(
(Object _) {},
),
),
child: GestureDetector(
key: const Key('preview-interaction'),
behavior: HitTestBehavior.opaque,
onPanDown: (d) {
_down = d.localPosition;
_focus.requestFocus();
},
onTapUp: (d) => widget.controller.selectVisual(
_hit(d.localPosition)?.elementId,
),
onPanStart: _start,
onPanUpdate: _update,
onPanEnd: (_) => _end(),
onPanCancel: () {
if (_pointerDrag != null) _cancel();
},
child: CustomPaint(
painter: _SelectionPainter(
label: _label,
rect: widget.canvasRect,
scale: _scale,
devicePixelRatio: MediaQuery.devicePixelRatioOf(context),
geometry: geometry,
snap:
drag?.snap != null &&
geometry != null &&
!HardwareKeyboard.instance.isAltPressed
? CanvasSnap.guides(geometry, _canvas)
: null,
rotating: drag?.operation == _Operation.rotate,
),
),
),
),
),
);
}
}
class _SelectionPainter extends CustomPainter {
_SelectionPainter({
required this.label,
required this.rect,
required this.scale,
required this.devicePixelRatio,
required this.geometry,
required this.snap,
required this.rotating,
}) : labelRevision = label.revision;
final int labelRevision;
final Rect rect;
final SelectionLabel label;
final double scale;
final double devicePixelRatio;
final PreviewGeometry? geometry;
final CanvasSnap? snap;
final bool rotating;
@override
void paint(Canvas canvas, Size size) {
canvas.save();
canvas.clipRect(Offset.zero & size);
_paint(canvas);
canvas.restore();
}
void _paintGuides(Canvas canvas) {
final guide = Paint()
..color = const Color(0xFFFF55C8)
..strokeWidth = 1;
for (final x in snap?.verticalGuides ?? const <double>[]) {
final screenX = rect.left + x * scale;
canvas.drawLine(
Offset(screenX, rect.top),
Offset(screenX, rect.bottom),
guide,
);
}
for (final y in snap?.horizontalGuides ?? const <double>[]) {
final screenY = rect.top + y * scale;
canvas.drawLine(
Offset(rect.left, screenY),
Offset(rect.right, screenY),
guide,
);
}
}
void _paint(Canvas canvas) {
final g = geometry;
if (g == null) return;
Offset screen(Offset p) => rect.topLeft + p * scale;
final points = g.selectionCorners.map(screen).toList();
paintSelectionDecoration(
canvas,
points,
dimensions: g.size,
devicePixelRatio: devicePixelRatio,
rotation: rotating ? g.rotation : null,
labelLayout: label,
);
_paintGuides(canvas);
}
@override
bool shouldRepaint(covariant _SelectionPainter oldDelegate) {
if (geometry == null && oldDelegate.geometry == null) return false;
return rect != oldDelegate.rect ||
labelRevision != oldDelegate.labelRevision ||
scale != oldDelegate.scale ||
devicePixelRatio != oldDelegate.devicePixelRatio ||
rotating != oldDelegate.rotating ||
geometry?.size != oldDelegate.geometry?.size ||
geometry?.rotation != oldDelegate.geometry?.rotation ||
!listEquals(
geometry?.selectionCorners,
oldDelegate.geometry?.selectionCorners,
) ||
!listEquals(snap?.verticalGuides, oldDelegate.snap?.verticalGuides) ||
!listEquals(snap?.horizontalGuides, oldDelegate.snap?.horizontalGuides);
}
}
@@ -0,0 +1,111 @@
part of 'preview_controller.dart';
/// Uses the same retained GPU frame and deferred publication as mask editing.
extension PreviewObscureEditing on PreviewController {
bool get obscureDragging => _obscureBase != null;
ElementId? get obscureEditingElement =>
_editingElement(PreviewCanvasEditMode.obscure);
int get obscureEditGeneration => _obscureGeneration;
void setObscureEditing(ElementId? id, {Object? owner}) =>
_setCanvasEditing(PreviewCanvasEditMode.obscure, id, owner: owner);
void releaseObscureEditing(Object owner) =>
_releaseCanvasEditing(PreviewCanvasEditMode.obscure, owner);
ClipObscureAnimation? obscureAnimation(ElementId id) {
final stack = maskStackFor(id);
if (stack == null) return null;
final animation = ClipObscureAnimation(stack.record, stack.localTick);
return animation.exists ? animation : null;
}
ClipMask? obscureFor(ElementId id) =>
id == obscureEditingElement && _pendingObscure != null
? _pendingObscure
: obscureAnimation(id)?.value;
Map<String, double> _obscureValuesFor(ElementId id) => {
...?obscureAnimation(id)?.values,
if (id == obscureEditingElement && _pendingObscure != null)
for (final f in ClipObscureAnimation.channels.expand((c) => c))
'obscure.$f': _pendingObscure!.values[f]!,
};
Future<bool> beginObscureEdit() async {
final id = obscureEditingElement;
if (id == null ||
!canPlay ||
_view == null ||
obscureAnimation(id)?.containsPlayhead != true ||
!_nativeVisuals.any((v) => v.elementId == id)) {
return false;
}
if (transforms.hasPending || _keyframePreviewing) cancelTransform();
final generation = ++_obscureGeneration;
_obscureBase = _view!.version.kernelVersion;
_obscureTick = positionTick;
_pendingObscure = obscureAnimation(id)!.value;
final bool ready;
try {
ready = await transforms.ensureContext();
} catch (_) {
if (generation == _obscureGeneration) cancelObscureEdit();
rethrow;
}
if (!ready || _closed || generation != _obscureGeneration) {
if (generation == _obscureGeneration) cancelObscureEdit();
return false;
}
_renderObscure();
return true;
}
void _renderObscure() {
final id = obscureEditingElement;
if (id == null || _transformHandle == null) return;
final visual = visualForProperties(id);
if (visual != null) _updateTransform(id, visual.transform, () {});
}
void updateObscure(ClipMask next) {
if (_obscureBase == null ||
!next.isValid ||
next.width > 3 ||
next.height > 3) {
return;
}
_pendingObscure = next;
_renderObscure();
_notify();
}
void endObscureEdit() {
final id = obscureEditingElement, next = _pendingObscure;
try {
if (id != null &&
next != null &&
identical(_obscureBase, _view?.version.kernelVersion) &&
_obscureTick == positionTick) {
final curves = obscureAnimation(id)!.edit(next);
if (curves.isNotEmpty) {
void edit() =>
timeline.publishParameters(activeSequence()!, id, curves);
if (_nativeTransforming) {
_publishInteractiveParameters(edit);
} else {
edit();
}
}
}
} finally {
cancelObscureEdit();
}
}
void cancelObscureEdit() {
_obscureGeneration++;
_obscureBase = null;
_obscureTick = null;
_pendingObscure = null;
_renderObscure();
_notify();
}
}
@@ -0,0 +1,26 @@
import 'package:cutdex_native_flutter/contracts.dart';
/// Viewing assumptions; authored project settings take precedence.
final class PreviewPolicy {
const PreviewPolicy({
this.unknownVideoColorSpace =
RenderColorPolicy.defaultUnknownVideoColorSpace,
this.sourceHeadroom = RenderColorPolicy.defaultSourceHeadroom,
this.targetHeadroom = RenderColorPolicy.defaultTargetHeadroom,
this.skimmingMode = SkimmingMode.audible,
});
final RenderColorSpace? unknownVideoColorSpace;
final double sourceHeadroom;
final double targetHeadroom;
/// Selects silent or audible preview while dragging the playhead.
final SkimmingMode skimmingMode;
RenderColorPolicy get colorPolicy => RenderColorPolicy(
unknownVideoColorSpace: unknownVideoColorSpace,
sourceHeadroom: sourceHeadroom,
targetHeadroom: targetHeadroom,
);
RenderToneMapping get toneMapping =>
colorPolicy.toneMappingFor(supportsToneMapping: true);
}
@@ -0,0 +1,241 @@
import 'dart:async';
import 'dart:ui';
import 'package:cutdex_core/editor.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:flutter/foundation.dart';
import 'preview_geometry.dart';
/// A paused-frame editing context, independent of pointer and history lifetimes.
/// Preparation runs once; rendering follows latest values, never a FIFO of edits.
class PreviewTransformSession extends ChangeNotifier {
PreviewTransformSession({
required this.canBegin,
required this.select,
required this.prepareNative,
required this.updateNative,
required this.commit,
required this.cancelNative,
required this.failed,
required this.changed,
});
final bool Function() canBegin;
final void Function(ElementId) select;
final Future<bool> Function() prepareNative;
final void Function(ElementId, ClipTransform, VoidCallback onRendered)
updateNative;
final void Function(ElementId, ClipTransform) commit;
final void Function() cancelNative;
final void Function(Object) failed;
final void Function() changed;
final _values = <ElementId, ClipTransform>{};
final _displayed = <ElementId, ClipTransform>{};
final presentation = ValueNotifier<int>(0);
final _committed = <ElementId, ClipTransform>{};
PreviewTransformEdit? _active;
Future<bool>? _preparing;
bool _ready = false;
int _epoch = 0;
ClipTransform? valueFor(ElementId id) => _values[id];
/// Last native render submitted to its display layer, not a display timestamp.
ClipTransform? displayedValueFor(ElementId id) => _displayed[id];
void _changed() {
changed();
notifyListeners();
}
bool get hasPending => _active != null;
bool get hasContext => _preparing != null;
/// Render externally prepared parameter values without opening another edit.
/// The caller owns publication; native rendering keeps only the latest values.
void previewValues(Map<ElementId, ClipTransform> values) {
for (final entry in values.entries) {
if (!entry.value.isValid) {
throw ArgumentError('Invalid preview transform');
}
}
var changed = false;
for (final entry in values.entries) {
if (_values[entry.key] == entry.value) continue;
_values[entry.key] = entry.value;
_publish(entry.key, entry.value);
changed = true;
}
if (changed) _changed();
}
Future<void> get settled async {
await _preparing;
}
/// Selection alone can acquire the paused frame without opening history.
Future<bool> ensureContext() {
if (!canBegin()) return Future.value(false);
return _preparing ??= _prepare(_epoch);
}
PreviewTransformEdit? begin(PreviewVisual visual) {
if (!canBegin() || _active != null) return null;
final edit = PreviewTransformEdit._(this, visual);
_displayed.putIfAbsent(visual.elementId, () => visual.transform);
_active = edit;
select(visual.elementId);
_preparing ??= _prepare(_epoch);
edit._prepared = _preparing!.then((ready) => ready && !edit.cancelled);
_changed();
return edit;
}
Future<bool> _prepare(int epoch) async {
try {
final ready = await prepareNative();
if (epoch != _epoch) return false;
if (!ready) {
cancelAll();
return false;
}
_ready = true;
// Gestures may have ended while preparing. Only their latest combined
// state matters to rendering; history has already recorded each release.
for (final entry in _values.entries.toList()) {
_publish(entry.key, entry.value);
}
return true;
} catch (error) {
if (epoch == _epoch) {
cancelAll();
failed(error);
}
return false;
}
}
List<PreviewVisual> project(List<PreviewVisual> visuals, Size canvas) => [
for (final visual in visuals)
if (_values[visual.elementId] case final value?)
PreviewVisual(
layerId: visual.layerId,
elementId: visual.elementId,
lane: visual.lane,
transform: value,
geometry: visual.geometry.changed(visual.transform, value, canvas),
)
else
visual,
];
void _update(PreviewTransformEdit edit, ClipTransform value) {
if (!identical(_active, edit) || edit.released) return;
if (!value.isValid) {
throw ArgumentError('Invalid canvas transform');
}
edit._value = value;
_values[edit.initial.elementId] = value;
_publish(edit.initial.elementId, value);
// High-frequency values only notify consumers of the transform itself.
// Selection geometry listens to acknowledged renders separately.
notifyListeners();
}
void _publish(ElementId id, ClipTransform value) {
if (!_ready) return;
try {
final epoch = _epoch;
updateNative(id, value, () {
if (epoch != _epoch || identical(_displayed[id], value)) return;
_displayed[id] = value;
presentation.value++;
});
} catch (error) {
cancelAll();
failed(error);
}
}
void _end(PreviewTransformEdit edit) {
if (!identical(_active, edit)) return;
try {
commit(edit.initial.elementId, edit.value);
_committed[edit.initial.elementId] = edit.value;
_values[edit.initial.elementId] = edit.value;
_active = null;
edit._finish();
_changed();
} catch (error) {
edit._error = error;
_cancel(edit);
failed(error);
}
}
void _cancel(PreviewTransformEdit edit) {
if (!identical(_active, edit)) return;
_active = null;
edit._cancelled = true;
edit._finish();
final id = edit.initial.elementId;
final restored = _committed[id] ?? edit.initial.transform;
_values[id] = restored;
if (_committed.isEmpty) {
cancelAll();
} else {
_publish(id, restored);
_changed();
}
}
/// Invalidates this frame context, not the already committed timeline history.
void cancelAll() {
_epoch++;
_active?._cancelled = true;
_active?._finish();
_active = null;
_preparing = null;
_ready = false;
_values.clear();
_displayed.clear();
_committed.clear();
cancelNative();
_changed();
}
@override
void dispose() {
_epoch++;
presentation.dispose();
super.dispose();
}
}
class PreviewTransformEdit {
PreviewTransformEdit._(this._session, this.initial)
: _value = initial.transform;
final PreviewTransformSession _session;
final PreviewVisual initial;
ClipTransform _value;
ClipTransform get value => _value;
late final Future<bool> _prepared;
final _done = Completer<void>();
bool _cancelled = false;
Object? _error;
Future<bool> get prepared => _prepared;
Future<void> get done => _done.future;
bool get released => _done.isCompleted;
bool get cancelled => _cancelled;
Object? get error => _error;
void update(ClipTransform value) => _session._update(this, value);
Future<void> end() {
_session._end(this);
return done;
}
void cancel() => _session._cancel(this);
void _finish() {
if (!released) _done.complete();
}
}
@@ -0,0 +1,234 @@
import 'dart:math' as math;
import 'dart:ui' show Vertices;
import 'package:flutter/material.dart';
const selectionBlue = Color(0xFF0099FF);
/// One label layout owned and released by the overlay's widget state.
class SelectionLabel {
SelectionLabel({this.onChanged}) {
PaintingBinding.instance.systemFonts.addListener(_fontsChanged);
}
final VoidCallback? onChanged;
String? _label;
TextPainter? _painter;
int _revision = 0;
int get revision => _revision;
void _fontsChanged() {
_revision++;
_painter?.dispose();
_painter = null;
_label = null;
onChanged?.call();
}
TextPainter layout(String label) {
if (_label == label && _painter != null) return _painter!;
_painter?.dispose();
_label = label;
return _painter = TextPainter(
text: TextSpan(
text: label,
style: const TextStyle(color: Colors.white, fontSize: 12),
),
textDirection: TextDirection.ltr,
)..layout();
}
void dispose() {
PaintingBinding.instance.systemFonts.removeListener(_fontsChanged);
_painter?.dispose();
_painter = null;
_label = null;
}
}
/// Corner squares resize; the exterior sector around each corner rotates.
int selectionResizeCorner(List<Offset> corners, Offset pointer) =>
corners.indexWhere((p) => (p - pointer).distance <= 9);
int selectionRotationCorner(List<Offset> corners, Offset pointer) {
final path = Path()..addPolygon(corners, true);
if (path.contains(pointer)) return -1;
return corners.indexWhere((p) => (p - pointer).distance <= 26);
}
MouseCursor selectionCursor(List<Offset> corners, Offset pointer) {
final corner = selectionResizeCorner(corners, pointer);
if (corner >= 0) {
final diagonal = corners[corner] - corners[(corner + 2) % 4];
final sector =
(math.atan2(diagonal.dy, diagonal.dx) / (math.pi / 4)).round() % 4;
return switch (sector) {
0 => SystemMouseCursors.resizeLeftRight,
1 => SystemMouseCursors.resizeUpLeftDownRight,
2 => SystemMouseCursors.resizeUpDown,
_ => SystemMouseCursors.resizeUpRightDownLeft,
};
}
if (selectionRotationCorner(corners, pointer) >= 0) {
return SystemMouseCursors.grab;
}
return SystemMouseCursors.basic;
}
void paintSelectionDecoration(
Canvas canvas,
List<Offset> corners, {
required Size dimensions,
required double devicePixelRatio,
double? rotation,
SelectionLabel? labelLayout,
}) {
final physicalStrokeWidth = math.max(1, (1.5 * devicePixelRatio).round());
final outline = Paint()
..color = selectionBlue
..isAntiAlias = true
..style = PaintingStyle.stroke
..strokeWidth = physicalStrokeWidth / devicePixelRatio;
final angle = math.atan2(
(corners[1] - corners[0]).dy,
(corners[1] - corners[0]).dx,
);
final axisAligned =
(angle - (angle / (math.pi / 2)).round() * math.pi / 2).abs() < 1e-9;
// Align stroke boundaries to physical pixels only for axis-aligned bounds.
// Rotated edges retain their exact subpixel coordinates for antialiasing.
double align(double coordinate) =>
((coordinate * devicePixelRatio - physicalStrokeWidth / 2).round() +
physicalStrokeWidth / 2) /
devicePixelRatio;
final paintedCorners = axisAligned
? [for (final p in corners) Offset(align(p.dx), align(p.dy))]
: corners;
if (axisAligned) {
canvas.drawPath(Path()..addPolygon(paintedCorners, true), outline);
} else {
_paintSmoothOutline(canvas, corners, outline, devicePixelRatio);
}
final handleFill = Paint()..color = Colors.white;
for (final p in corners) {
canvas.save();
final Rect box;
if (axisAligned) {
box = Rect.fromLTRB(
align(p.dx - 4),
align(p.dy - 4),
align(p.dx + 4),
align(p.dy + 4),
);
} else {
canvas.translate(p.dx, p.dy);
canvas.rotate(angle);
box = const Rect.fromLTWH(-4, -4, 8, 8);
}
canvas.drawRect(box, handleFill);
if (axisAligned) {
canvas.drawRect(box, outline);
} else {
_paintSmoothOutline(
canvas,
[box.topLeft, box.topRight, box.bottomRight, box.bottomLeft],
outline,
devicePixelRatio,
);
}
canvas.restore();
}
final label = rotation == null
? '${dimensions.width.round()} × ${dimensions.height.round()}'
: '${rotation.toStringAsFixed(1)}°';
final layout = labelLayout ?? SelectionLabel();
final text = layout.layout(label);
final quarterTurns = ((angle + math.pi / 4) / (math.pi / 2)).floor();
final labelEdge = (2 - quarterTurns) % 4;
final edgeCenter = (corners[labelEdge] + corners[(labelEdge + 1) % 4]) / 2;
final oppositeCenter =
(corners[(labelEdge + 2) % 4] + corners[(labelEdge + 3) % 4]) / 2;
var outward = edgeCenter - oppositeCenter;
outward = outward / math.max(outward.distance, .001);
final center = edgeCenter + outward * (14 + text.height / 2);
canvas.save();
canvas.translate(center.dx, center.dy);
canvas.rotate(angle - quarterTurns * math.pi / 2);
final rect = Rect.fromCenter(
center: Offset.zero,
width: text.width + 12,
height: text.height + 6,
);
canvas.drawRRect(
RRect.fromRectAndRadius(rect, const Radius.circular(3)),
Paint()..color = selectionBlue,
);
text.paint(canvas, rect.topLeft + const Offset(6, 3));
canvas.restore();
if (labelLayout == null) layout.dispose();
}
/// Explicit opacity ramps smooth shallow diagonals.
void _paintSmoothOutline(
Canvas canvas,
List<Offset> corners,
Paint outline,
double devicePixelRatio,
) {
final halfWidth = outline.strokeWidth / 2;
final feather = math.min(outline.strokeWidth, 1.5 / devicePixelRatio);
final outer = halfWidth + feather / 2;
final core = halfWidth - feather / 2;
final center = (corners[0] + corners[2]) / 2;
final normals = <Offset>[];
for (var i = 0; i < 4; i++) {
final edge = corners[(i + 1) % 4] - corners[i];
if (edge.distance <= outer * 2) {
canvas.drawPath(Path()..addPolygon(corners, true), outline);
return;
}
var normal = Offset(edge.dy, -edge.dx) / edge.distance;
final outward = (corners[i] + corners[(i + 1) % 4]) / 2 - center;
if (normal.dx * outward.dx + normal.dy * outward.dy < 0) {
normal = -normal;
}
normals.add(normal);
}
final miters = <Offset>[];
for (var i = 0; i < 4; i++) {
final a = normals[(i + 3) % 4];
final b = normals[i];
miters.add((a + b) / math.max(1 + a.dx * b.dx + a.dy * b.dy, .001));
}
final positions = <Offset>[];
final colors = <Color>[];
final transparent = outline.color.withValues(alpha: 0);
for (final (distance, color) in [
(outer, transparent),
(core, outline.color),
(-core, outline.color),
(-outer, transparent),
]) {
for (var i = 0; i < 4; i++) {
positions.add(corners[i] + miters[i] * distance);
colors.add(color);
}
}
final indices = <int>[];
for (var ring = 0; ring < 3; ring++) {
for (var i = 0; i < 4; i++) {
final a = ring * 4 + i;
final b = ring * 4 + (i + 1) % 4;
final c = a + 4;
final d = b + 4;
indices.addAll([a, b, c, b, d, c]);
}
}
final vertices = Vertices(
VertexMode.triangles,
positions,
colors: colors,
indices: indices,
);
canvas.drawVertices(vertices, BlendMode.dst, Paint());
vertices.dispose();
}
@@ -0,0 +1,599 @@
import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:cutdex_core/editor/commands.dart';
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:flutter/foundation.dart';
import 'cleanup.dart';
import 'preview_policy.dart';
/// The host retains media access until the supplied action finishes.
typedef PreviewMediaLoader = Future<T> Function<T>(
Future<T> Function(MediaReference media) action,
);
/// Owns an independent source session and holds file access until it is closed.
class SourcePreviewController extends ChangeNotifier {
SourcePreviewController({
required this.loadMedia,
required this.frameDuration,
required this.rememberPosition,
int positionTick = 0,
this.policy = const PreviewPolicy(),
CutdexRuntime? runtime,
// Keep the public constructor argument separate from private storage.
// ignore: prefer_initializing_formals
}) : _positionTick = positionTick,
runtime = runtime ?? CutdexRuntime();
final PreviewMediaLoader loadMedia;
final PreviewPolicy policy;
final RationalTime frameDuration;
final void Function(int) rememberPosition;
final CutdexRuntime runtime;
RuntimeSession? _session;
RuntimeSession? get session => _session;
Uint8List? _image;
Uint8List? get image => _image;
double _aspectRatio = 16 / 9;
double get aspectRatio => _aspectRatio;
int _positionTick;
int get positionTick => _positionTick;
int _durationTick = 0;
int get durationTick => _durationTick;
bool _busy = true;
bool get busy => _busy;
bool _playing = false;
bool get playing => _playing;
bool _audioOnly = false;
bool get audioOnly => _audioOnly;
Object? _error;
Object? get error => _error;
bool _closed = false;
StreamSubscription<RuntimeSnapshot>? _events;
final _release = Completer<void>();
Future<void>? _lifetime;
bool get canPlay => !_closed && !busy && _error == null && session != null;
Future<void>? _opening;
Future<void>? _closing;
Future<void> initialize(Future<void> beforeOpen) {
if (_closed) return Future.error(StateError('Source preview is closed'));
if (_opening case final pending?) return pending;
final completion = Completer<void>();
_opening = completion.future;
_initialize(beforeOpen)
.then(completion.complete, onError: completion.completeError);
return completion.future;
}
Future<void> _initialize(Future<void> beforeOpen) async {
final ready = Completer<void>();
_lifetime = () async {
try {
await beforeOpen;
if (_closed) return;
await loadMedia((media) async {
try {
if (_closed) return;
if (media.isImage) {
final image = await _loadStillImage(media);
if (_closed) return;
_aspectRatio = image.aspectRatio;
_image = image.data;
} else {
final info = await runtime.probe(media);
if (_closed) return;
if (info.isProtected ||
(info.videoTrackCount == 0 && info.audioTrackCount == 0)) {
throw const RuntimeException(
code: 'unpreviewableMedia',
message: 'Media has no previewable audio or video tracks',
);
}
final size =
info.videoDisplaySizes.firstOrNull ?? RenderSize(1920, 1080);
_audioOnly = info.videoTrackCount == 0;
_aspectRatio = size.width / size.height;
_durationTick =
(info.duration.seconds * TimelineClock.ticksPerSecond)
.floor();
_positionTick = positionTick.clamp(0, durationTick);
final created = await runtime.createSession();
_session = created;
if (_closed) return;
_events = created.events.listen(
(snapshot) {
if (_closed) return;
if (!_scrubbing &&
_scrubEnd == null &&
_interactiveSeeks == 0) {
_positionTick =
(snapshot.position.seconds *
TimelineClock.ticksPerSecond)
.round()
.clamp(0, durationTick);
}
_playing = snapshot.state == PlaybackState.playing;
if (snapshot.state == PlaybackState.failed) {
_error = RuntimeException(
code: 'playbackFailed',
message: snapshot.message ?? 'Source preview failed',
);
}
rememberPosition(positionTick);
notifyListeners();
},
onError: (Object failure) {
if (!_closed) {
_error = failure;
notifyListeners();
}
},
);
final start = positionTick;
await created.load(
sourcePreviewPlan(media, info, frameDuration, policy: policy),
);
if (_closed) return;
await created.seek(
MediaTime(start, TimelineClock.ticksPerSecond),
);
_positionTick = start;
}
if (_closed) return;
_busy = false;
notifyListeners();
ready.complete();
await _release.future;
} finally {
await completeCleanup([
() async => _playback,
() async => _scrubStart,
() async => _scrubEnd,
() async => _events?.cancel(),
() async => session?.close(),
]);
}
});
} catch (failure) {
if (_closed) rethrow;
if (!_closed) {
_busy = false;
_error = failure;
notifyListeners();
}
} finally {
if (!ready.isCompleted) ready.complete();
}
}();
await ready.future;
}
Future<({Uint8List data, double aspectRatio})> _loadStillImage(
MediaReference media,
) async {
try {
final thumbnail = await runtime.thumbnail(
ThumbnailRequest(media: media, maximumWidth: 2048, maximumHeight: 2048),
);
final codec = await ui.instantiateImageCodec(thumbnail.data);
try {
final frame = await codec.getNextFrame();
try {
return (
data: thumbnail.data,
aspectRatio: frame.image.width / frame.image.height,
);
} finally {
frame.image.dispose();
}
} finally {
codec.dispose();
}
} catch (_) {
if (kIsWeb || media.uri.scheme != 'file') rethrow;
final bytes = await File.fromUri(media.uri).readAsBytes();
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
try {
final descriptor = await ui.ImageDescriptor.encoded(buffer);
try {
final scale = descriptor.width > descriptor.height
? (2048 / descriptor.width).clamp(0.0, 1.0)
: (2048 / descriptor.height).clamp(0.0, 1.0);
final codec = await descriptor.instantiateCodec(
targetWidth: (descriptor.width * scale).round().clamp(1, 2048),
targetHeight: (descriptor.height * scale).round().clamp(1, 2048),
);
try {
final frame = await codec.getNextFrame();
try {
final encoded = await frame.image.toByteData(
format: ui.ImageByteFormat.png,
);
if (encoded == null) throw StateError('Could not encode image');
return (
data: encoded.buffer.asUint8List(),
aspectRatio: descriptor.width / descriptor.height,
);
} finally {
frame.image.dispose();
}
} finally {
codec.dispose();
}
} finally {
descriptor.dispose();
}
} finally {
buffer.dispose();
}
}
}
/// A host preparation failure changes state through this boundary.
void reportFailure(Object failure, [StackTrace? stack]) {
if (_closed) return;
reportDiagnostic(
runtime.diagnostics,
DiagnosticEvent(
component: 'preview',
operation: 'sourceFailure',
error: failure,
stackTrace: stack,
context: {'nativeSessionId': session?.id},
),
);
_error = failure;
_busy = false;
notifyListeners();
}
bool _scrubbing = false;
Future<void>? _scrubStart;
Future<void>? _scrubEnd;
/// Uses the runtime's replaceable skim target, shared with timeline scrubbing.
void beginScrubbing() {
if (!canPlay || _scrubbing) return;
_interactiveSeek = null;
_scrubbing = true;
final native = session!;
final pendingEnd = _scrubEnd;
_scrubStart = () async {
await pendingEnd;
await _playback;
if (_closed) return;
await native.beginSkimming(mode: policy.skimmingMode);
}().catchError(_scrubFailed);
}
void updateScrubbing(int tick) {
if (!_scrubbing || _closed) return;
final frameTick = TimelineClock.standard.toTicks(frameDuration);
final last = durationTick > 0
? ((durationTick - 1) ~/ frameTick) * frameTick
: 0;
_positionTick = tick.clamp(0, last);
final native = session!;
final start = _scrubStart;
final time = MediaTime(_positionTick, TimelineClock.ticksPerSecond);
unawaited(
() async {
await start;
if (_closed || _error != null) return;
await native.skim(time);
}().catchError(_scrubFailed),
);
rememberPosition(_positionTick);
notifyListeners();
}
void endScrubbing() {
if (!_scrubbing) return;
_scrubbing = false;
final native = session!;
final start = _scrubStart;
_scrubStart = null;
final time = MediaTime(_positionTick, TimelineClock.ticksPerSecond);
final ending = () async {
await start;
if (_closed || _error != null) return;
await native.endSkimming(time);
}().catchError(_scrubFailed);
_scrubEnd = ending;
unawaited(
ending.whenComplete(() {
if (identical(_scrubEnd, ending)) _scrubEnd = null;
}),
);
}
void _scrubFailed(Object error) {
if (_closed || error is RuntimeException && error.code == 'cancelled') {
return;
}
reportFailure(error);
}
Future<void>? _playback;
_InteractiveSourceSeek? _interactiveSeek;
int _interactiveSeeks = 0;
/// UI navigation keeps one native seek and one replaceable next target.
/// The returned future settles when this burst's final target has rendered.
Future<void> seekInteractive(int requested) {
if (!canPlay) {
return Future.error(
const CommandRejected('sourceNotReady', 'Source preview is not ready'),
);
}
final frame = TimelineClock.standard.toTicks(frameDuration);
final last = durationTick > 0 ? ((durationTick - 1) ~/ frame) * frame : 0;
final tick = requested.clamp(0, last);
if (_scrubbing) endScrubbing();
var batch = _interactiveSeek;
if (batch == null) {
batch = _InteractiveSourceSeek();
_interactiveSeek = batch;
_interactiveSeeks++;
final previous = _playback ?? Future<void>.value();
final scrubEnd = _scrubEnd;
final owned = batch;
final pending = previous
.then((_) async {
try {
await scrubEnd;
while (owned.tick != null) {
final target = owned.tick!;
owned.tick = null;
if (_closed || _error != null) {
throw StateError('Source closed or failed during navigation');
}
await session!.seek(
MediaTime(target, TimelineClock.ticksPerSecond),
);
if (_closed) {
throw StateError('Source closed during navigation');
}
if (owned.tick == null &&
_interactiveSeeks == 1 &&
!_scrubbing &&
_scrubEnd == null) {
_positionTick = target;
rememberPosition(target);
}
}
} catch (failure) {
if (!_closed) _error = failure;
rethrow;
}
})
.whenComplete(() {
_interactiveSeeks--;
if (identical(_interactiveSeek, owned)) _interactiveSeek = null;
if (!_closed) notifyListeners();
});
owned.done = _trackPlayback(pending);
}
batch.tick = tick;
_positionTick = tick;
rememberPosition(tick);
notifyListeners();
return batch.done;
}
Future<void> togglePlayback() {
if (_interactiveSeek != null) {
return control(
playing ? SourcePreviewAction.pause : SourcePreviewAction.play,
);
}
if (_playback case final pending?) return pending;
if (!canPlay || _closed) return Future.value();
final completion = Completer<void>();
_playback = completion.future;
_togglePlayback().then(
(_) {
_playback = null;
completion.complete();
},
onError: (Object error, StackTrace stack) {
_playback = null;
completion.completeError(error, stack);
},
);
return completion.future;
}
Future<void> _togglePlayback() async {
if (!canPlay || _closed) return;
_busy = true;
notifyListeners();
try {
if (playing) {
await session!.pause();
} else {
if (positionTick >= durationTick) await session!.seek(MediaTime(0, 1));
if (!_closed) await session!.play();
}
} catch (failure) {
if (!_closed) _error = failure;
} finally {
_busy = false;
if (!_closed) notifyListeners();
}
}
/// Explicit controls reuse this player and are drained before media access releases.
Future<void> control(SourcePreviewAction action, {CommandTime? at}) {
// An exact command fences the interactive burst. Later UI targets enqueue
// after it instead of changing targets that precede the command.
_interactiveSeek = null;
final previous = _playback ?? Future<void>.value();
final pending = previous.then((_) async {
if (_closed || !canPlay) {
throw const CommandRejected(
'sourceNotReady',
'Source preview is not ready',
);
}
if (action == SourcePreviewAction.seek && at == null ||
action != SourcePreviewAction.seek && at != null ||
!{
SourcePreviewAction.play,
SourcePreviewAction.pause,
SourcePreviewAction.seek,
}.contains(action)) {
throw const CommandRejected(
'invalidArguments',
'Invalid source control',
);
}
final tick = at == null
? null
: TimelineClock.standard.toTicks(
RationalTime(at.numerator, at.denominator),
);
if (tick != null && tick > durationTick) {
throw const CommandRejected(
'invalidTime',
'Seek exceeds source duration',
);
}
_busy = true;
notifyListeners();
try {
switch (action) {
case SourcePreviewAction.play:
if (positionTick >= durationTick) {
await session!.seek(MediaTime(0, 1));
}
if (!_closed) await session!.play();
case SourcePreviewAction.pause:
await session!.pause();
_playing = false;
case SourcePreviewAction.seek:
await session!.seek(MediaTime(at!.numerator, at.denominator));
if (!_closed) {
_positionTick = tick!;
rememberPosition(tick);
}
default:
throw StateError('Unreachable source action');
}
} catch (failure) {
if (!_closed) _error = failure;
rethrow;
} finally {
_busy = false;
if (!_closed) notifyListeners();
}
if (_closed) throw StateError('Source closed during control');
});
return _trackPlayback(pending);
}
Future<void> _trackPlayback(Future<void> pending) {
_playback = pending;
unawaited(
pending.then<void>(
(_) {
if (identical(_playback, pending)) _playback = null;
},
onError: (Object _, StackTrace _) {
if (identical(_playback, pending)) _playback = null;
},
),
);
return pending;
}
Future<void> close() {
if (_closing case final pending?) return pending;
final completion = Completer<void>();
_closing = completion.future;
_closed = true;
completeCleanup([
() => rememberPosition(positionTick),
_release.complete,
() async => _lifetime,
]).then(completion.complete, onError: completion.completeError);
return completion.future;
}
}
class _InteractiveSourceSeek {
int? tick;
late final Future<void> done;
}
ExecutionPlan sourcePreviewPlan(
MediaReference media,
MediaInfo info,
RationalTime frame, {
PreviewPolicy policy = const PreviewPolicy(),
}) {
final range = MediaRange(start: MediaTime(0, 1), duration: info.duration);
final audio = info.audioTracks.firstOrNull;
MediaRange? audioRange;
if (audio != null) {
final assetEnd = RationalTime(
info.duration.numerator,
info.duration.denominator,
);
final start = RationalTime(audio.start.numerator, audio.start.denominator);
final end =
start +
RationalTime(audio.duration.numerator, audio.duration.denominator);
final clippedStart = start.isNegative ? RationalTime.zero : start;
final clippedEnd = end.compareTo(assetEnd) > 0 ? assetEnd : end;
if (clippedEnd.compareTo(clippedStart) > 0) {
final duration = clippedEnd - clippedStart;
audioRange = MediaRange(
start: MediaTime(clippedStart.numerator, clippedStart.denominator),
duration: MediaTime(duration.numerator, duration.denominator),
);
}
}
return ExecutionPlan(
duration: info.duration,
toneMapping:
{
RenderColorSpace.rec2020HLG,
RenderColorSpace.rec2020PQ,
RenderColorSpace.linearRec2020,
}.contains(info.videoColorSpaces.firstOrNull)
? policy.toneMapping
: const RenderToneMapping.none(),
renderSize: info.videoDisplaySizes.firstOrNull ?? RenderSize(1920, 1080),
frameDuration: MediaTime(frame.numerator, frame.denominator),
media: [media],
visualLayers: [
if (info.videoTrackCount > 0)
VisualLayer(
id: 'source-video',
mediaId: media.id,
sourceRange: range,
timelineRange: range,
inputColorSpace:
info.videoColorSpaces.firstOrNull ??
(info.videoColorSpaces.isNotEmpty
? policy.unknownVideoColorSpace
: null),
),
],
audioLayers: [
if (audioRange != null)
AudioLayer(
id: 'source-audio',
mediaId: media.id,
sourceRange: audioRange,
timelineRange: audioRange,
),
],
);
}