Files
cutdex/test/timeline_thumbnails_test.dart
T
lingjhf 38ca180cf7
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
refactor(core): own editor UI and pin verified native releases
2026-10-12 03:20:29 +08:00

775 lines
24 KiB
Dart

import 'dart:async';
import 'dart:ui' as ui;
import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart';
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
import 'package:cutdex_core/timeline/engine.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('cutdex_runtime');
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
final element = ElementRecord(
id: ElementId('clip'),
structure: ElementStructure.content,
sourceStart: 0,
sourceDuration: TimelineClock.ticksPerSecond * 10,
duration: TimelineClock.ticksPerSecond * 10,
enabled: true,
payloadRef: PayloadRef('payload'),
);
RuntimeTimelineThumbnails create({
int limit = 256,
int concurrency = 2,
int batchSize = 4,
}) => RuntimeTimelineThumbnails(
resolveMedia: (_) =>
MediaReference(id: 'source', uri: Uri.file('/source.mov')),
maximumEntries: limit,
maximumConcurrent: concurrency,
maximumBatchSize: batchSize,
);
ui.Image? demand(
RuntimeTimelineThumbnails frames,
int tick, {
int sourceSpanTicks = 1,
ui.Size logicalSize = const ui.Size(80, 40),
double devicePixelRatio = 2,
}) => frames.imageFor(
element,
tick,
sourceSpanTicks: sourceSpanTicks,
logicalSize: logicalSize,
devicePixelRatio: devicePixelRatio,
);
tearDown(() => messenger.setMockMethodCallHandler(channel, null));
test('sampling uses finite media bounds or an uncapped source grid', () {
int sample(int tick, int? end) => RuntimeTimelineThumbnails.sampledTickFor(
sourceTick: tick,
sourceSpanTicks: 8,
minimumTick: 3,
maximumTickExclusive: end,
);
expect(sample(0, 22), 3);
expect(sample(35, 22), 16);
expect(sample(0, null), 3);
expect(sample(21, null), 24);
});
testWidgets('a freeze frame with zero source span still requests its image', (
tester,
) async {
var calls = 0;
messenger.setMockMethodCallHandler(channel, (_) async {
calls++;
throw PlatformException(code: 'unavailable');
});
final frames = create();
addTearDown(frames.dispose);
final tick = 10 * TimelineClock.ticksPerSecond;
final frozen = element.copyWith(
sourceStart: tick,
sourceDuration: 0,
mediaStart: 0,
mediaDuration: 30 * TimelineClock.ticksPerSecond,
retime: RetimeMapRecord([
RetimeSegmentRecord(
projectDuration: element.duration,
sourceStart: tick,
sourceDelta: 0,
),
]),
);
frames.beginFrame();
frames.imageFor(
frozen,
tick,
sourceSpanTicks: 1,
logicalSize: const Size(80, 40),
devicePixelRatio: 2,
);
frames.endFrame();
await tester.pump();
expect(calls, 1);
});
for (final leading in [true, false]) {
testWidgets('trimmed media keeps the same cached cell: leading $leading', (
tester,
) async {
var calls = 0;
messenger.setMockMethodCallHandler(channel, (_) async {
calls++;
throw PlatformException(code: 'unavailable');
});
final frames = create();
addTearDown(frames.dispose);
final clip = element.copyWith(
sourceStart: 5 * TimelineClock.ticksPerSecond,
sourceDuration: 10 * TimelineClock.ticksPerSecond,
mediaStart: 0,
mediaDuration: 30 * TimelineClock.ticksPerSecond,
);
final tick = ((leading ? 5.25 : 14.75) * TimelineClock.ticksPerSecond)
.round();
void paint(ElementRecord record) {
frames.beginFrame();
frames.imageFor(
record,
tick,
sourceSpanTicks: TimelineClock.ticksPerSecond,
logicalSize: const Size(80, 40),
devicePixelRatio: 2,
);
frames.endFrame();
}
paint(clip);
await tester.pump();
await tester.pump();
expect(calls, 1);
for (final removed in [0.5, 1.0, 1.5]) {
final delta = (removed * TimelineClock.ticksPerSecond).round();
paint(
clip.copyWith(
sourceStart: clip.sourceStart + (leading ? delta : 0),
sourceDuration: clip.sourceDuration - delta,
duration: clip.duration - delta,
),
);
await tester.pump();
await tester.pump();
expect(
calls,
1,
reason: 'Cropping a cell must not change its cache key',
);
}
});
}
test(
'thumbnail requests and cached failures are isolated by selected track',
() async {
var index = 0;
final indices = <int>[];
messenger.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'capabilities') {
return {
'contractVersion': 1,
'features': {'media.trackSelection': 'available'},
};
}
indices.add(
((call.arguments as Map)['trackSelection'] as Map)['index'] as int,
);
throw PlatformException(code: 'unavailable');
});
final frames = RuntimeTimelineThumbnails(
resolveMedia: (_) =>
MediaReference(id: 'shared', uri: Uri.file('/shared.mov')),
resolveTrackSelection: (_) => TrackSelection.index(index),
);
addTearDown(frames.dispose);
for (index = 0; index < 2; index++) {
frames.beginFrame();
demand(frames, 0);
frames.endFrame();
await Future<void>.delayed(Duration.zero);
await Future<void>.delayed(Duration.zero);
}
expect(indices, [0, 1]);
},
);
testWidgets('still image tiles share one source-time request', (
tester,
) async {
final calls = <List<Object?>>[];
final media = <Object?>[];
messenger.setMockMethodCallHandler(channel, (call) async {
media.add((call.arguments as Map)['media']);
calls.add((call.arguments as Map)['times'] as List<Object?>);
throw PlatformException(code: 'unavailable');
});
final frames = RuntimeTimelineThumbnails(
resolveMedia: (_) => MediaReference(
id: 'still',
uri: Uri.file('/still.heic'),
isImage: true,
),
);
frames.beginFrame();
for (final tick in [0, 100, TimelineClock.ticksPerSecond * 9]) {
demand(frames, tick);
}
frames.endFrame();
await tester.pump();
expect(calls, [
[MediaTime(0, TimelineClock.ticksPerSecond).toMap()],
]);
expect(media.single, containsPair('isImage', true));
frames.dispose();
});
test('painted device pixels are quantized to stable resolution tiers', () {
expect(
RuntimeTimelineThumbnails.maximumEdgeFor(
logicalSize: const ui.Size(82, 46),
devicePixelRatio: 2,
),
192,
);
expect(
RuntimeTimelineThumbnails.maximumEdgeFor(
logicalSize: const ui.Size(26, 46),
devicePixelRatio: 2,
),
128,
);
expect(
() => RuntimeTimelineThumbnails.maximumEdgeFor(
logicalSize: ui.Size.zero,
devicePixelRatio: 2,
),
throwsArgumentError,
);
});
test('nearby zoom centers snap to a stable source-time pyramid', () {
final frames = create();
addTearDown(frames.dispose);
expect(frames.maximumBatchSize, 4);
final span = TimelineClock.ticksPerSecond * 3 ~/ 5;
final interval = RuntimeTimelineThumbnails.samplingIntervalFor(span);
expect(interval, lessThanOrEqualTo(span));
expect(interval * 2, greaterThan(span));
final first = RuntimeTimelineThumbnails.sampledTickFor(
sourceTick: TimelineClock.ticksPerSecond * 3,
sourceSpanTicks: span,
minimumTick: 0,
maximumTickExclusive: TimelineClock.ticksPerSecond * 10,
);
final nearby = RuntimeTimelineThumbnails.sampledTickFor(
sourceTick: TimelineClock.ticksPerSecond * 3 + interval ~/ 16,
sourceSpanTicks: span - 1,
minimumTick: 0,
maximumTickExclusive: TimelineClock.ticksPerSecond * 10,
);
expect(nearby, first);
});
testWidgets(
'visible requests are bounded, old pending work is discarded, and late disposal is safe',
(tester) async {
final calls = <List<int>>[];
final waiting = <Completer<Object?>>[];
messenger.setMockMethodCallHandler(channel, (call) {
expectSync(call.method, 'thumbnails');
final args = call.arguments as Map;
calls.add([
for (final time in args['times'] as List)
int.parse((time as Map)['numerator'] as String),
]);
expectSync(args['maximumWidth'], 192);
expectSync(args['maximumHeight'], 192);
expectSync(args['tolerance'], MediaTime(1, 4).toMap());
final result = Completer<Object?>();
waiting.add(result);
return result.future;
});
final frames = create(limit: 3, concurrency: 1);
frames.beginFrame();
for (var i = 0; i < 6; i++) {
demand(frames, i);
}
frames.endFrame();
await tester.pump();
expect(calls, [
[0],
]);
frames.beginFrame();
demand(frames, 50);
frames.endFrame();
waiting.first.completeError(PlatformException(code: 'unavailable'));
await tester.pump();
expect(calls, [
[0],
[50],
]);
frames.dispose();
waiting.last.completeError(PlatformException(code: 'unavailable'));
await tester.pump();
expect(calls, [
[0],
[50],
]);
expect(tester.takeException(), isNull);
},
);
testWidgets('large visible ranges load in small progressive batches', (
tester,
) async {
final calls = <List<int>>[];
final waiting = <Completer<Object?>>[];
messenger.setMockMethodCallHandler(channel, (call) {
final args = call.arguments as Map;
calls.add([
for (final time in args['times'] as List)
int.parse((time as Map)['numerator'] as String),
]);
final result = Completer<Object?>();
waiting.add(result);
return result.future;
});
final frames = create(limit: 32, concurrency: 1);
addTearDown(frames.dispose);
frames.beginFrame();
for (var tick = 0; tick < 17; tick++) {
demand(frames, tick);
}
frames.endFrame();
await tester.pump();
expect(calls.map((batch) => batch.length), [1]);
waiting[0].completeError(PlatformException(code: 'unavailable'));
await tester.pump();
expect(calls.map((batch) => batch.length), [1, 4]);
waiting[1].completeError(PlatformException(code: 'unavailable'));
await tester.pump();
expect(calls.map((batch) => batch.length), [1, 4, 4]);
waiting[2].completeError(PlatformException(code: 'unavailable'));
await tester.pump();
expect(calls.map((batch) => batch.length), [1, 4, 4, 4]);
waiting[3].completeError(PlatformException(code: 'unavailable'));
await tester.pump();
expect(calls.map((batch) => batch.length), [1, 4, 4, 4, 4]);
waiting[4].completeError(PlatformException(code: 'unavailable'));
await tester.pump();
expect(tester.takeException(), isNull);
});
testWidgets('first visible tile is requested ahead of its batch', (
tester,
) async {
final calls = <List<int>>[];
final pending = <Completer<Object?>>[];
messenger.setMockMethodCallHandler(channel, (call) {
final times = (call.arguments as Map)['times'] as List;
calls.add([
for (final time in times)
int.parse((time as Map)['numerator'] as String),
]);
final completion = Completer<Object?>();
pending.add(completion);
return completion.future;
});
final frames = create(concurrency: 2);
addTearDown(frames.dispose);
frames.beginFrame();
for (var tick = 0; tick < 6; tick++) {
demand(frames, tick);
}
frames.endFrame();
await tester.pump();
expect(calls, [
[0],
[1, 2, 3, 4],
]);
for (final completion in List.of(pending)) {
completion.completeError(PlatformException(code: 'unavailable'));
}
await tester.pump();
expect(calls, [
[0],
[1, 2, 3, 4],
[5],
]);
pending.last.completeError(PlatformException(code: 'unavailable'));
await tester.pump();
expect(tester.takeException(), isNull);
});
testWidgets(
'decoded images repaint once, retain aspect ratio and are reused until eviction',
(tester) async {
final recorder = ui.PictureRecorder();
Canvas(recorder).drawColor(Colors.green, BlendMode.src);
final picture = recorder.endRecording();
final bytes = await tester.runAsync(() async {
final image = await picture.toImage(9, 16);
try {
return (await image.toByteData(format: ui.ImageByteFormat.png))!
.buffer
.asUint8List();
} finally {
image.dispose();
picture.dispose();
}
});
var calls = 0;
messenger.setMockMethodCallHandler(channel, (call) async {
calls++;
final times = (call.arguments as Map)['times'] as List;
return [
for (final time in times)
{
'requestedTime': time,
'actualTime': time,
'width': 9,
'height': 16,
'format': 'jpeg',
'data': bytes,
},
];
});
final frames = create(limit: 1);
var repaints = 0;
Completer<void>? ready;
frames.addListener(() {
repaints++;
ready?.complete();
});
addTearDown(frames.dispose);
await tester.runAsync(() async {
ready = Completer<void>();
frames.beginFrame();
demand(frames, 123);
frames.endFrame();
await ready!.future.timeout(const Duration(seconds: 5));
});
frames.beginFrame();
final first = demand(frames, 123)!;
expect(first.width, 9);
expect(first.height, 16);
expect(frames.aspectRatioFor(element), 9 / 16);
frames.endFrame();
await tester.pump();
expect(calls, 1);
expect(repaints, 1);
await tester.runAsync(() async {
ready = Completer<void>();
frames.beginFrame();
demand(frames, 456);
frames.endFrame();
await ready!.future.timeout(const Duration(seconds: 5));
});
expect(calls, 2);
expect(first.debugDisposed, isTrue);
},
);
testWidgets('imported media keeps preview frames and aspect ratio', (
tester,
) async {
final recorder = ui.PictureRecorder();
Canvas(recorder).drawColor(Colors.blue, BlendMode.src);
final picture = recorder.endRecording();
final bytes = await tester.runAsync(() async {
final image = await picture.toImage(16, 9);
try {
return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer
.asUint8List();
} finally {
image.dispose();
picture.dispose();
}
});
var calls = 0;
messenger.setMockMethodCallHandler(channel, (call) async {
calls++;
return [
for (final time in (call.arguments as Map)['times'] as List)
{
'requestedTime': time,
'actualTime': time,
'width': 16,
'height': 9,
'format': 'jpeg',
'data': bytes,
},
];
});
var media = MediaReference(id: '/source.mov', uri: Uri.file('/source.mov'));
final frames = RuntimeTimelineThumbnails(resolveMedia: (_) => media);
addTearDown(frames.dispose);
late Completer<void> ready;
frames.addListener(() {
if (!ready.isCompleted) ready.complete();
});
await tester.runAsync(() async {
ready = Completer<void>();
frames.beginFrame();
demand(frames, 123);
frames.endFrame();
await ready.future.timeout(const Duration(seconds: 5));
});
frames.beginFrame();
final preview = demand(frames, 123);
expect(preview, isNotNull);
frames.endFrame();
media = MediaReference(id: 'imported-asset', uri: media.uri);
frames.beginFrame();
expect(demand(frames, 123), same(preview));
expect(frames.aspectRatioFor(element), 16 / 9);
frames.endFrame();
await tester.pump();
expect(calls, 1);
// Reusing an asset ID for a different file must still invalidate the cache.
media = MediaReference(id: media.id, uri: Uri.file('/other.mov'));
frames.beginFrame();
expect(demand(frames, 123), isNull);
expect(frames.aspectRatioFor(element), isNull);
});
testWidgets('a lower tier stays visible while a higher DPR tier loads', (
tester,
) async {
final recorder = ui.PictureRecorder();
Canvas(recorder).drawColor(Colors.blue, BlendMode.src);
final picture = recorder.endRecording();
final bytes = await tester.runAsync(() async {
final image = await picture.toImage(16, 9);
try {
return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer
.asUint8List();
} finally {
image.dispose();
picture.dispose();
}
});
final edges = <int>[];
messenger.setMockMethodCallHandler(channel, (call) async {
final args = call.arguments as Map;
edges.add(args['maximumWidth'] as int);
return [
for (final time in args['times'] as List)
{
'requestedTime': time,
'actualTime': time,
'width': 16,
'height': 9,
'format': 'jpeg',
'data': bytes,
},
];
});
final frames = create(limit: 2);
addTearDown(frames.dispose);
Completer<void>? ready;
frames.addListener(() => ready?.complete());
await tester.runAsync(() async {
ready = Completer<void>();
frames.beginFrame();
demand(frames, 123, logicalSize: const ui.Size(20, 20));
frames.endFrame();
await ready!.future.timeout(const Duration(seconds: 5));
});
frames.beginFrame();
final low = demand(frames, 123, logicalSize: const ui.Size(80, 40));
frames.endFrame();
expect(
low,
isNotNull,
reason: 'The loaded lower tier should be a fallback',
);
await tester.runAsync(() async {
ready = Completer<void>();
await ready!.future.timeout(const Duration(seconds: 5));
});
frames.beginFrame();
final high = demand(frames, 123, logicalSize: const ui.Size(80, 40));
frames.endFrame();
expect(edges, [64, 192]);
expect(high, isNotNull);
expect(identical(high, low), isFalse);
});
testWidgets(
'a nearby cached sample stays visible across pyramid level changes',
(tester) async {
final recorder = ui.PictureRecorder();
Canvas(recorder).drawColor(Colors.purple, BlendMode.src);
final picture = recorder.endRecording();
final bytes = await tester.runAsync(() async {
final image = await picture.toImage(16, 9);
try {
return (await image.toByteData(format: ui.ImageByteFormat.png))!
.buffer
.asUint8List();
} finally {
image.dispose();
picture.dispose();
}
});
final requestedTicks = <int>[];
messenger.setMockMethodCallHandler(channel, (call) async {
final args = call.arguments as Map;
expect(args['tolerance'], MediaTime(1, 4).toMap());
final times = args['times'] as List;
requestedTicks.addAll([
for (final time in times)
int.parse((time as Map)['numerator'] as String),
]);
return [
for (final time in times)
{
'requestedTime': time,
'actualTime': time,
'width': 16,
'height': 9,
'format': 'jpeg',
'data': bytes,
},
];
});
final frames = create(concurrency: 1);
addTearDown(frames.dispose);
Completer<void>? ready;
frames.addListener(() {
if (ready case final pending? when !pending.isCompleted) {
pending.complete();
}
});
final coarseSpan = TimelineClock.ticksPerSecond;
final coarseTick = RuntimeTimelineThumbnails.sampledTickFor(
sourceTick: TimelineClock.ticksPerSecond * 3,
sourceSpanTicks: coarseSpan,
minimumTick: 0,
maximumTickExclusive: TimelineClock.ticksPerSecond * 10,
);
await tester.runAsync(() async {
ready = Completer<void>();
frames.beginFrame();
demand(frames, coarseTick, sourceSpanTicks: coarseSpan);
frames.endFrame();
await ready!.future.timeout(const Duration(seconds: 5));
});
final fineSpan = coarseSpan ~/ 2;
final fineTick =
coarseTick + RuntimeTimelineThumbnails.samplingIntervalFor(fineSpan);
ui.Image? fallback;
await tester.runAsync(() async {
ready = Completer<void>();
frames.beginFrame();
fallback = demand(frames, fineTick, sourceSpanTicks: fineSpan);
frames.endFrame();
await ready!.future.timeout(const Duration(seconds: 5));
});
expect(
fallback,
isNotNull,
reason: 'A pyramid transition must not expose an empty tile',
);
frames.beginFrame();
final replacement = demand(frames, fineTick, sourceSpanTicks: fineSpan);
frames.endFrame();
expect(requestedTicks, [coarseTick, fineTick]);
expect(replacement, isNotNull);
expect(identical(replacement, fallback), isFalse);
},
);
testWidgets(
'completed batches retain frames that just moved outside the viewport',
(tester) async {
final recorder = ui.PictureRecorder();
Canvas(recorder).drawColor(Colors.orange, BlendMode.src);
final picture = recorder.endRecording();
final bytes = await tester.runAsync(() async {
final image = await picture.toImage(16, 9);
try {
return (await image.toByteData(format: ui.ImageByteFormat.png))!
.buffer
.asUint8List();
} finally {
image.dispose();
picture.dispose();
}
});
var calls = 0;
late final RuntimeTimelineThumbnails frames;
messenger.setMockMethodCallHandler(channel, (call) async {
calls++;
final requestedTimes = (call.arguments as Map)['times'] as List;
// Simulate a pan while this native request is in flight.
frames.beginFrame();
demand(frames, 20);
frames.endFrame();
return [
for (final time in requestedTimes)
{
'requestedTime': time,
'actualTime': time,
'width': 16,
'height': 9,
'format': 'jpeg',
'data': bytes,
},
];
});
frames = create(limit: 4, concurrency: 1);
addTearDown(frames.dispose);
Completer<void>? ready;
frames.addListener(() {
if (ready case final pending? when !pending.isCompleted) {
pending.complete();
}
});
await tester.runAsync(() async {
ready = Completer<void>();
frames.beginFrame();
demand(frames, 10);
demand(frames, 20);
frames.endFrame();
await ready!.future.timeout(const Duration(seconds: 5));
});
expect(calls, 2);
frames.beginFrame();
expect(
demand(frames, 10),
isNotNull,
reason: 'A completed neighboring frame should remain in the LRU cache',
);
frames.endFrame();
await tester.pump();
expect(calls, 2);
},
);
testWidgets(
'failed frames do not trigger repeated native requests on repaint',
(tester) async {
var calls = 0;
messenger.setMockMethodCallHandler(channel, (_) async {
calls++;
throw PlatformException(code: 'unsupported');
});
final frames = create();
addTearDown(frames.dispose);
for (var i = 0; i < 3; i++) {
frames.beginFrame();
demand(frames, 12);
frames.endFrame();
await tester.pump();
}
expect(calls, 1);
},
);
}