Files
cutdex/packages/cutdex_preview/test/source_preview_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

602 lines
21 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:cutdex_core/editor/commands.dart';
import 'package:cutdex_preview/cutdex_preview.dart';
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('cutdex_runtime');
const events = MethodChannel('cutdex_runtime/sessions/source-test');
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
final calls = <MethodCall>[];
final asset = (id: 'source', location: 'file:///source.mov');
final info = MediaInfo(
duration: MediaTime(10, 1),
videoTrackCount: 1,
videoTrackIds: [1],
audioTrackCount: 1,
audioTrackIds: [1],
isProtected: false,
videoDisplaySizes: [RenderSize(1080, 1920)],
audioTracks: [
MediaTrackTiming(start: MediaTime(1, 1), duration: MediaTime(8, 1)),
],
);
Completer<void>? blockedProbe;
Completer<void>? blockedPlay;
Completer<void>? blockedSkim;
Completer<void>? blockedSeek;
setUp(() {
calls.clear();
blockedProbe = null;
blockedPlay = null;
blockedSkim = null;
blockedSeek = null;
messenger.setMockMethodCallHandler(events, (call) async {
if (call.method == 'listen') {
scheduleMicrotask(
() => messenger.handlePlatformMessage(
events.name,
const StandardMethodCodec().encodeSuccessEnvelope({
'type': 'attached',
}),
(_) {},
),
);
}
return null;
});
messenger.setMockMethodCallHandler(channel, (call) async {
calls.add(call);
switch (call.method) {
case 'seek':
await blockedSeek?.future;
return null;
case 'skim':
await blockedSkim?.future;
return null;
case 'probe':
await blockedProbe?.future;
return {
'duration': info.duration.toMap(),
'videoTrackCount': 1,
'videoTrackIds': [1],
'audioTrackCount': 1,
'audioTrackIds': [1],
'isProtected': false,
'videoDisplaySizes': [
{'width': 1080.0, 'height': 1920.0},
],
'audioTracks': [
{
'start': MediaTime(1, 1).toMap(),
'duration': MediaTime(8, 1).toMap(),
},
],
};
case 'play':
await blockedPlay?.future;
return null;
case 'createSession':
return {'sessionId': 'source-test'};
case 'load':
return '1';
case 'thumbnail':
throw PlatformException(code: 'unsupported');
default:
return null;
}
});
});
tearDown(() {
messenger.setMockMethodCallHandler(channel, null);
messenger.setMockMethodCallHandler(events, null);
});
SourcePreviewController source() => SourcePreviewController(
frameDuration: RationalTime(1, 30),
rememberPosition: (_) {},
loadMedia: <T>(action) =>
action(MediaReference(id: asset.id, uri: Uri.parse(asset.location))),
);
Future<void> waitForSeek() async {
for (var i = 0; i < 100; i++) {
if (calls.any((c) => c.method == 'seek')) return;
await Future<void>.delayed(const Duration(milliseconds: 1));
}
fail('Native seek did not start');
}
List<double> seekTimes() => [
for (final call in calls.where((c) => c.method == 'seek'))
MediaTime.fromMap((call.arguments as Map)['time']).seconds,
];
test(
'interactive source navigation merges 100 targets before pause',
() async {
final controller = source();
await controller.initialize(Future.value());
calls.clear();
final block = blockedSeek = Completer<void>();
final first = controller.seekInteractive(TimelineClock.ticksPerSecond);
await waitForSeek();
final requests = <Future<void>>[first];
for (var i = 1; i <= 100; i++) {
requests.add(
controller.seekInteractive(
TimelineClock.ticksPerSecond +
i * TimelineClock.ticksPerSecond ~/ 30,
),
);
}
final pause = controller.control(SourcePreviewAction.pause);
expect(seekTimes(), [1]);
expect(controller.positionTick, TimelineClock.ticksPerSecond * 13 ~/ 3);
expect(calls.where((c) => c.method == 'pause'), isEmpty);
block.complete();
blockedSeek = null;
await Future.wait([...requests, pause]);
expect(seekTimes(), [1, closeTo(13 / 3, 1e-6)]);
expect(calls.last.method, 'pause');
expect(controller.error, isNull);
await controller.close();
controller.dispose();
},
);
test('exact source commands fence replaceable UI navigation', () async {
final controller = source();
await controller.initialize(Future.value());
calls.clear();
final block = blockedSeek = Completer<void>();
final first = controller.seekInteractive(TimelineClock.ticksPerSecond);
await waitForSeek();
final latest = controller.seekInteractive(2 * TimelineClock.ticksPerSecond);
final exact = controller.control(
SourcePreviewAction.seek,
at: CommandTime(3, 1),
);
final after = controller.seekInteractive(4 * TimelineClock.ticksPerSecond);
final afterLatest = controller.seekInteractive(
5 * TimelineClock.ticksPerSecond,
);
block.complete();
blockedSeek = null;
await Future.wait([first, latest, exact, after, afterLatest]);
expect(seekTimes(), [1, 2, 3, 5]);
expect(controller.positionTick, 5 * TimelineClock.ticksPerSecond);
await controller.close();
controller.dispose();
});
test(
'closing drains interactive navigation before releasing source',
() async {
final controller = source();
await controller.initialize(Future.value());
calls.clear();
final block = blockedSeek = Completer<void>();
final seeking = controller.seekInteractive(TimelineClock.ticksPerSecond);
await waitForSeek();
final seekFailure = expectLater(seeking, throwsStateError);
final closing = controller.close();
final closeFailure = expectLater(closing, throwsStateError);
await Future<void>.delayed(Duration.zero);
expect(calls.where((c) => c.method == 'close'), isEmpty);
block.complete();
blockedSeek = null;
await Future.wait([seekFailure, closeFailure]);
expect(calls.where((c) => c.method == 'close'), hasLength(1));
controller.dispose();
},
);
test('navigation and scrubbing settle in either handoff direction', () async {
final controller = source();
await controller.initialize(Future.value());
calls.clear();
final block = blockedSeek = Completer<void>();
final navigating = controller.seekInteractive(TimelineClock.ticksPerSecond);
await waitForSeek();
controller.beginScrubbing();
controller.updateScrubbing(2 * TimelineClock.ticksPerSecond);
block.complete();
blockedSeek = null;
await navigating;
expect(controller.positionTick, 2 * TimelineClock.ticksPerSecond);
// Navigation ends the scrub at its final target before the new exact frame.
await controller.seekInteractive(3 * TimelineClock.ticksPerSecond);
expect(controller.positionTick, 3 * TimelineClock.ticksPerSecond);
final end = calls.singleWhere((c) => c.method == 'endSkimming');
expect(MediaTime.fromMap((end.arguments as Map)['time']).seconds, 2);
expect(calls.last.method, 'seek');
expect(seekTimes(), [1, 3]);
expect(controller.error, isNull);
await controller.close();
controller.dispose();
});
test('local image preview survives native thumbnail failure', () async {
final directory = await Directory.systemTemp.createTemp('source-image-');
final file = File('${directory.path}/image.png');
await file.writeAsBytes(
base64Decode(
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR4nGP4z8AARAwQCgAf7gP9i18U1AAAAABJRU5ErkJggg==',
),
);
final controller = SourcePreviewController(
frameDuration: RationalTime(1, 30),
rememberPosition: (_) {},
loadMedia: <T>(action) =>
action(MediaReference(id: 'image', uri: file.uri, isImage: true)),
);
try {
await controller.initialize(Future.value());
expect(calls.where((call) => call.method == 'thumbnail'), hasLength(1));
expect(controller.error, isNull);
expect(controller.busy, isFalse);
expect(controller.image, isNotNull);
expect(controller.aspectRatio, 1);
expect(controller.session, isNull);
} finally {
await controller.close();
controller.dispose();
await directory.delete(recursive: true);
}
});
for (final mode in SkimmingMode.values) {
test(
'${mode.name} source scrubbing previews latest target and settles once',
() async {
final controller = SourcePreviewController(
frameDuration: RationalTime(1, 30),
policy: PreviewPolicy(skimmingMode: mode),
rememberPosition: (_) {},
loadMedia: <T>(action) => action(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
),
);
await controller.initialize(Future.value());
calls.clear();
blockedSkim = Completer<void>();
controller.beginScrubbing();
controller.updateScrubbing(TimelineClock.ticksPerSecond);
for (var i = 0; i < 100 && !calls.any((c) => c.method == 'skim'); i++) {
await Future<void>.delayed(const Duration(milliseconds: 1));
}
expect(calls.where((c) => c.method == 'skim'), hasLength(1));
controller.updateScrubbing(2 * TimelineClock.ticksPerSecond);
controller.updateScrubbing(3 * TimelineClock.ticksPerSecond);
await Future<void>.delayed(Duration.zero);
blockedSkim!.complete();
await Future<void>.delayed(const Duration(milliseconds: 20));
final skims = calls.where((c) => c.method == 'skim').toList();
expect(skims, hasLength(2));
expect(
MediaTime.fromMap((skims.last.arguments as Map)['time']).seconds,
3,
);
controller.endScrubbing();
await Future<void>.delayed(const Duration(milliseconds: 20));
expect(calls.where((c) => c.method == 'beginSkimming'), hasLength(1));
final begin = calls.singleWhere((c) => c.method == 'beginSkimming');
expect((begin.arguments as Map)['mode'], mode.name);
expect((begin.arguments as Map).containsKey('audible'), isFalse);
final end = calls.singleWhere((c) => c.method == 'endSkimming');
expect(MediaTime.fromMap((end.arguments as Map)['time']).seconds, 3);
expect(calls.where((c) => c.method == 'seek'), isEmpty);
expect(controller.error, isNull);
await controller.close();
controller.dispose();
},
);
}
test(
'explicit source controls pause before playback events and drain on close',
() async {
var retained = false;
final controller = SourcePreviewController(
frameDuration: RationalTime(1, 30),
rememberPosition: (_) {},
loadMedia: <T>(action) async {
retained = true;
try {
return await action(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
);
} finally {
retained = false;
}
},
);
await controller.initialize(Future.value());
await controller.control(SourcePreviewAction.play);
await controller.control(SourcePreviewAction.pause);
expect(calls.where((c) => c.method == 'pause'), hasLength(1));
await controller.control(SourcePreviewAction.seek, at: CommandTime(3, 2));
expect(controller.positionTick, 3 * TimelineClock.ticksPerSecond ~/ 2);
await expectLater(
controller.control(SourcePreviewAction.seek, at: CommandTime(11, 1)),
throwsA(isA<CommandRejected>()),
);
blockedPlay = Completer<void>();
final playing = controller.control(SourcePreviewAction.play);
final expected = expectLater(playing, throwsStateError);
for (
var i = 0;
i < 100 && calls.where((c) => c.method == 'play').length < 2;
i++
) {
await Future<void>.delayed(const Duration(milliseconds: 2));
}
final closing = controller.close();
final closed = closing.catchError((Object e) {
expect(e, isA<StateError>());
});
expect(retained, true);
blockedPlay!.complete();
await expected;
await closed;
expect(retained, false);
expect(calls.where((c) => c.method == 'close'), hasLength(1));
controller.dispose();
},
);
test(
'source opens paused at saved position and retains access until close',
() async {
var retained = false;
var remembered = 0;
final controller = SourcePreviewController(
frameDuration: RationalTime(1, 25),
positionTick: 2 * TimelineClock.ticksPerSecond,
rememberPosition: (tick) => remembered = tick,
loadMedia: <T>(action) async {
retained = true;
try {
return await action(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
);
} finally {
retained = false;
}
},
);
await controller.initialize(Future.value());
expect(retained, isTrue);
expect(controller.aspectRatio, 1080 / 1920);
expect(controller.durationTick, 10 * TimelineClock.ticksPerSecond);
expect(calls.where((c) => c.method == 'play'), isEmpty);
final seek = calls.singleWhere((c) => c.method == 'seek');
expect(MediaTime.fromMap((seek.arguments as Map)['time']).seconds, 2);
await controller.togglePlayback();
expect(calls.where((c) => c.method == 'play'), hasLength(1));
await controller.close();
expect(retained, isFalse);
expect(remembered, 2 * TimelineClock.ticksPerSecond);
expect(calls.where((c) => c.method == 'close'), hasLength(1));
controller.dispose();
},
);
test(
'switching away during probe never creates or plays a stale session',
() async {
blockedProbe = Completer<void>();
var released = false;
final controller = SourcePreviewController(
frameDuration: RationalTime(1, 30),
rememberPosition: (_) {},
loadMedia: <T>(action) async {
try {
return await action(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
);
} finally {
released = true;
}
},
);
final opening = controller.initialize(Future.value());
for (var i = 0; i < 100 && !calls.any((c) => c.method == 'probe'); i++) {
await Future<void>.delayed(const Duration(milliseconds: 1));
}
expect(calls.any((c) => c.method == 'probe'), isTrue);
final closing = controller.close();
blockedProbe!.complete();
await opening;
await closing;
expect(released, isTrue);
expect(
calls.where((c) => c.method == 'createSession' || c.method == 'play'),
isEmpty,
);
controller.dispose();
},
);
test('concurrent source startup retains only one loader', () async {
blockedProbe = Completer<void>();
var loads = 0;
final controller = SourcePreviewController(
frameDuration: RationalTime(1, 30),
rememberPosition: (_) {},
loadMedia: <T>(action) async {
loads++;
return action(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
);
},
);
final first = controller.initialize(Future.value());
final second = controller.initialize(Future.value());
while (loads == 0) {
await Future<void>.delayed(Duration.zero);
}
final closing = controller.close();
blockedProbe!.complete();
await Future.wait([first, second, closing]);
controller.dispose();
expect(loads, 1);
});
test('host position callback failure cannot leak source access', () async {
var retained = false;
final failure = StateError('host callback failed');
final controller = SourcePreviewController(
frameDuration: RationalTime(1, 30),
rememberPosition: (_) => throw failure,
loadMedia: <T>(action) async {
retained = true;
try {
return await action(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
);
} finally {
retained = false;
}
},
);
await controller.initialize(Future.value());
await expectLater(controller.close(), throwsA(same(failure)));
expect(retained, isFalse);
expect(calls.where((c) => c.method == 'close'), hasLength(1));
controller.dispose();
});
test(
'close retains source access until in-flight playback finishes',
() async {
blockedPlay = Completer<void>();
var retained = false;
final controller = SourcePreviewController(
frameDuration: RationalTime(1, 30),
rememberPosition: (_) {},
loadMedia: <T>(action) async {
retained = true;
try {
return await action(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
);
} finally {
retained = false;
}
},
);
await controller.initialize(Future.value());
final playing = controller.togglePlayback();
while (!calls.any((c) => c.method == 'play')) {
await Future<void>.delayed(Duration.zero);
}
final closing = controller.close();
await Future<void>.delayed(const Duration(milliseconds: 5));
final retainedDuringPlayback = retained;
final closedDuringPlayback = calls.any((c) => c.method == 'close');
blockedPlay!.complete();
await Future.wait([playing, closing]);
controller.dispose();
expect(retainedDuringPlayback, isTrue);
expect(closedDuringPlayback, isFalse);
expect(retained, isFalse);
},
);
test(
'audio sample endpoints stay exact without rounding beyond the track',
() {
final audio = MediaInfo(
duration: MediaTime(10, 1),
videoTrackCount: 0,
videoTrackIds: [],
audioTrackCount: 1,
audioTrackIds: [1],
isProtected: false,
audioTracks: [
MediaTrackTiming(
start: MediaTime(0, 1),
duration: MediaTime(479999, 48000),
),
],
);
final plan = sourcePreviewPlan(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
audio,
RationalTime(1, 30),
);
expect(plan.audioLayers.single.sourceRange.duration.numerator, 479999);
expect(plan.audioLayers.single.sourceRange.duration.denominator, 48000);
},
);
test(
'reported unknown source color uses the timeline Rec.709 viewing fallback',
() {
final unknown = MediaInfo(
duration: info.duration,
videoTrackCount: 1,
videoTrackIds: [1],
audioTrackCount: 0,
audioTrackIds: [],
isProtected: false,
audioTracks: [],
videoColorSpaces: [null],
);
final plan = sourcePreviewPlan(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
unknown,
RationalTime(1, 30),
);
expect(plan.visualLayers.single.inputColorSpace, RenderColorSpace.rec709);
expect(plan.toneMapping, const RenderToneMapping.none());
},
);
test('HDR source preview explicitly maps to SDR', () {
final hdr = MediaInfo(
duration: info.duration,
videoTrackCount: 1,
videoTrackIds: [1],
audioTrackCount: 0,
audioTrackIds: [],
isProtected: false,
audioTracks: [],
videoColorSpaces: [RenderColorSpace.rec2020HLG],
);
final plan = sourcePreviewPlan(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
hdr,
RationalTime(1, 30),
);
expect(plan.toneMapping.sourceHeadroom, 4);
expect(
plan.visualLayers.single.inputColorSpace,
RenderColorSpace.rec2020HLG,
);
});
test('source plan preserves native aspect and delayed audio alignment', () {
final plan = sourcePreviewPlan(
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
info,
RationalTime(1, 25),
);
expect(plan.renderSize.width, 1080);
expect(plan.renderSize.height, 1920);
expect(plan.audioLayers.single.sourceRange.start.seconds, 1);
expect(plan.audioLayers.single.timelineRange.start.seconds, 1);
expect(plan.audioLayers.single.timelineRange.duration.seconds, 8);
});
}