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
597 lines
21 KiB
Dart
597 lines
21 KiB
Dart
import 'dart:convert';
|
||
import 'dart:io';
|
||
import 'dart:math' as math;
|
||
import 'dart:ui';
|
||
|
||
import 'package:cutdex/app/editor_theme.dart';
|
||
import 'package:cutdex/diagnostics/app_diagnostics.dart';
|
||
import 'package:cutdex/diagnostics/diagnostic_store.dart';
|
||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||
import 'package:cutdex/features/properties/speed_properties.dart';
|
||
import 'package:cutdex/features/timeline/timeline_panel.dart';
|
||
import 'package:cutdex/l10n/app_localizations.dart';
|
||
import 'package:cutdex/persistence/app_database.dart';
|
||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||
import 'package:cutdex/workspace/timeline_session.dart';
|
||
import 'package:cutdex_core/editor.dart';
|
||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||
import 'package:cutdex_core/project.dart';
|
||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||
import 'package:cutdex_core/timeline/model.dart';
|
||
import 'package:drift/native.dart';
|
||
import 'package:flutter/foundation.dart';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:flutter/scheduler.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||
import 'package:flutter_test/flutter_test.dart';
|
||
import 'package:integration_test/integration_test.dart';
|
||
import 'package:path/path.dart' as p;
|
||
|
||
import 'support/native_media_fixture.dart';
|
||
|
||
void main() {
|
||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||
const output = String.fromEnvironment('CUTDEX_TEST_REPORT');
|
||
const cadence = bool.fromEnvironment('CUTDEX_DIAGNOSTIC_CADENCE');
|
||
testWidgets(
|
||
'real editor diagnostics and logging performance comparison',
|
||
(tester) async {
|
||
expect(
|
||
kProfileMode || cadence,
|
||
isTrue,
|
||
reason: 'Use Profile for Flutter timings, or Debug with opt-in native cadence.',
|
||
);
|
||
final root = Directory(output)..createSync(recursive: true);
|
||
final source = await nativeMediaFixture();
|
||
final originalSource = await source.stat();
|
||
final store = DiagnosticStore(
|
||
Directory(
|
||
p.join(root.path, 'logs-${DateTime.now().microsecondsSinceEpoch}'),
|
||
),
|
||
);
|
||
final diagnostics = AppDiagnostics(
|
||
store,
|
||
metadata: {
|
||
'validation': 'real editor',
|
||
'platform': Platform.operatingSystem,
|
||
'buildMode': kProfileMode ? 'profile' : 'debug',
|
||
},
|
||
);
|
||
await diagnostics.readApplicationInfo();
|
||
var logging = true;
|
||
var measuring = false;
|
||
final recordCosts = <int>[];
|
||
void sink(DiagnosticEvent event) {
|
||
if (!logging) return;
|
||
final watch = Stopwatch()..start();
|
||
diagnostics.event(event);
|
||
if (measuring) recordCosts.add(watch.elapsedMicroseconds);
|
||
}
|
||
|
||
final runtime = CutdexRuntime(diagnostics: sink);
|
||
final probe = await runtime.probe(
|
||
MediaReference(id: 'media', uri: source.uri),
|
||
);
|
||
expect(probe.videoTrackCount, greaterThan(0));
|
||
expect(probe.duration.seconds, greaterThanOrEqualTo(25));
|
||
final sequence = SequenceId('sequence');
|
||
final clipId = ElementId('clip');
|
||
final duration = RationalTime(
|
||
probe.duration.numerator,
|
||
probe.duration.denominator,
|
||
);
|
||
final project = await ProjectFile.create(
|
||
Directory(
|
||
p.join(
|
||
root.path,
|
||
'Editing-${DateTime.now().microsecondsSinceEpoch}.cutdex',
|
||
),
|
||
),
|
||
name: 'Diagnostic validation',
|
||
);
|
||
await project.saveAsset(
|
||
AssetDocument(
|
||
id: 'media',
|
||
name: 'Generated test media',
|
||
storage: AssetStorage.external,
|
||
location: source.uri.toString(),
|
||
),
|
||
);
|
||
await project.saveTimeline(
|
||
TimelineDocument(
|
||
id: 'timeline',
|
||
name: 'Diagnostic validation',
|
||
defaultSequenceId: sequence,
|
||
settings: {
|
||
'renderSize': {'width': 1280, 'height': 720},
|
||
},
|
||
payloads: [
|
||
PayloadDocument(
|
||
id: 'video',
|
||
type: 'video',
|
||
assetIds: ['media'],
|
||
data: {
|
||
'videoTrackIndex': 0,
|
||
if (probe.audioTrackCount > 0) 'audioTrackIndex': 0,
|
||
},
|
||
),
|
||
],
|
||
sequences: [
|
||
TimelineDto(
|
||
id: sequence,
|
||
format: TimelineFormat.fps30,
|
||
primaryStorylineId: StorylineId('primary'),
|
||
storylines: [
|
||
StorylineDto(id: StorylineId('primary'), elementIds: [clipId]),
|
||
],
|
||
elements: [
|
||
ElementDto(
|
||
id: clipId,
|
||
structure: ElementStructure.content,
|
||
duration: duration,
|
||
sourceRange: TimeRange(
|
||
start: RationalTime.zero,
|
||
duration: duration,
|
||
),
|
||
mediaRange: TimeRange(
|
||
start: RationalTime.zero,
|
||
duration: duration,
|
||
),
|
||
payloadRef: PayloadRef('video'),
|
||
),
|
||
],
|
||
),
|
||
],
|
||
),
|
||
);
|
||
final session = _FaultingSession(
|
||
document: await project.loadTimeline('timeline'),
|
||
persistence: await project.openTimelineSaveSession('timeline'),
|
||
assetUris: {'media': source.uri},
|
||
diagnostics: (event) => withDiagnosticContext({
|
||
'projectId': project.info.id,
|
||
}, () => reportDiagnostic(sink, event)),
|
||
);
|
||
final preview = PreviewController(
|
||
timeline: session,
|
||
runtime: runtime,
|
||
activeSequence: () => session.activeSequenceId,
|
||
viewForSequence: session.view,
|
||
);
|
||
final database = AppDatabase(NativeDatabase.memory());
|
||
final frames = _FrameMeasurements();
|
||
addTearDown(() async {
|
||
SchedulerBinding.instance.removeTimingsCallback(frames.accept);
|
||
session.fault = null;
|
||
await preview.close();
|
||
await session.close();
|
||
await project.close();
|
||
await store.flush();
|
||
await database.close();
|
||
});
|
||
SchedulerBinding.instance.addTimingsCallback(frames.accept);
|
||
final faults = <Map<String, Object?>>[];
|
||
final runs = <Map<String, Object?>>[];
|
||
final report = File(p.join(root.path, 'results.json'));
|
||
var passed = false;
|
||
Map<String, Object?>? savedState;
|
||
void save() => report.writeAsStringSync(
|
||
const JsonEncoder.withIndent(' ').convert({
|
||
'at': DateTime.now().toUtc().toIso8601String(),
|
||
'passed': passed,
|
||
'platform': Platform.operatingSystem,
|
||
'dart': Platform.version,
|
||
'mode': kProfileMode ? 'profile' : 'debug',
|
||
'source': {
|
||
'path': source.path,
|
||
'durationSeconds': probe.duration.seconds,
|
||
'bytes': originalSource.size,
|
||
},
|
||
'method':
|
||
'Mounted production timeline toolbar, speed slider and native playback; '
|
||
'controlled failures at the authoritative commit boundary. Same-build alternating '
|
||
'diagnostic sink on/off; bounded 16 ms pumps during playback. '
|
||
'Flutter timings exclude independently rendered platform-view video. '
|
||
'Native cadence is available only in opt-in macOS Debug builds.',
|
||
'faults': faults,
|
||
'runs': runs,
|
||
'savedState': savedState,
|
||
'storage': {
|
||
'flushes': store.eventFlushes,
|
||
'bytes': store.eventBytesWritten,
|
||
'dropped': store.dropped,
|
||
'droppedErrors': store.droppedErrors,
|
||
'writeFailures': store.writeFailures,
|
||
},
|
||
}),
|
||
);
|
||
save();
|
||
await preview.initialize();
|
||
expect(preview.error, isNull);
|
||
await tester.pumpWidget(
|
||
ProviderScope(
|
||
overrides: [
|
||
appDatabaseProvider.overrideWithValue(database),
|
||
editorTimelineProvider(
|
||
project.info.id,
|
||
'timeline',
|
||
).overrideWith((ref) async => session),
|
||
editorPreviewProvider(
|
||
project.info.id,
|
||
'timeline',
|
||
).overrideWith((ref) async => preview),
|
||
],
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
theme: EditorTheme.penDark,
|
||
home: Scaffold(
|
||
body: Column(
|
||
children: [
|
||
Expanded(
|
||
child: Row(
|
||
children: [
|
||
Expanded(
|
||
child: EditorPreviewPanel(
|
||
projectId: project.info.id,
|
||
timelineId: 'timeline',
|
||
),
|
||
),
|
||
SizedBox(
|
||
width: 280,
|
||
child: SingleChildScrollView(
|
||
child: SpeedProperties(
|
||
session: session,
|
||
sequence: sequence,
|
||
clip: clipId,
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
SizedBox(
|
||
height: 260,
|
||
child: EditorTimelinePanel(
|
||
projectId: project.info.id,
|
||
timelineId: 'timeline',
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
await tester.pumpAndSettle();
|
||
expect(find.byType(RuntimePreview), findsOneWidget);
|
||
final view = session.view(sequence);
|
||
Future<void> until(bool Function() predicate, String label) async {
|
||
final watch = Stopwatch()..start();
|
||
while (!predicate()) {
|
||
if (preview.error != null) {
|
||
throw StateError('$label: ${preview.error}');
|
||
}
|
||
if (watch.elapsed > const Duration(seconds: 30)) {
|
||
throw StateError('Timed out: $label');
|
||
}
|
||
await tester.pump(const Duration(milliseconds: 30));
|
||
}
|
||
await tester.pump();
|
||
}
|
||
|
||
Future<void> settle() async {
|
||
await until(
|
||
() =>
|
||
preview.canPlay &&
|
||
!preview.busy &&
|
||
preview.durationTick == session.sequenceDurationTicks(sequence),
|
||
'native preview',
|
||
);
|
||
await tester.pump(const Duration(milliseconds: 100));
|
||
expect(preview.error, isNull);
|
||
}
|
||
|
||
Future<void> selectAt(double seconds) async {
|
||
final query = session.persistence.timeline(sequence).current.query();
|
||
view.setSelection([query.elementById(clipId)!]);
|
||
view.seekTo((seconds * TimelineClock.ticksPerSecond).round());
|
||
await settle();
|
||
}
|
||
|
||
Future<void> slider(double speed) async {
|
||
final finder = find.descendant(
|
||
of: find.byKey(const Key('clip-speed-slider')),
|
||
matching: find.byType(Slider),
|
||
);
|
||
expect(finder, findsOneWidget);
|
||
final rect = tester.getRect(finder);
|
||
final position = (math.log(speed) / math.ln10 + 1) / 3;
|
||
final old = tester.widget<Slider>(finder).value;
|
||
final start = Offset(
|
||
rect.left + 12 + (rect.width - 24) * old,
|
||
rect.center.dy,
|
||
);
|
||
final end = Offset(
|
||
rect.left + 12 + (rect.width - 24) * position,
|
||
rect.center.dy,
|
||
);
|
||
final gesture = await tester.startGesture(start);
|
||
for (var i = 1; i <= 12; i++) {
|
||
await gesture.moveTo(Offset.lerp(start, end, i / 12)!);
|
||
await tester.pump(const Duration(milliseconds: 16));
|
||
}
|
||
await gesture.up();
|
||
await tester.pump();
|
||
}
|
||
|
||
Future<void> edit(String operation) async {
|
||
switch (operation) {
|
||
case 'split':
|
||
await tester.tap(find.byTooltip('在播放头处分割'));
|
||
case 'trimLeft':
|
||
await tester.tap(find.byKey(const ValueKey('timeline-trim-left')));
|
||
case 'trimRight':
|
||
await tester.tap(find.byKey(const ValueKey('timeline-trim-right')));
|
||
case 'setSpeed':
|
||
await slider(2);
|
||
}
|
||
await tester.pump();
|
||
}
|
||
|
||
Future<Map<String, dynamic>> exported() async => jsonDecode(
|
||
await (await diagnostics.export(
|
||
Directory(p.join(root.path, 'exports')),
|
||
)).readAsString(),
|
||
) as Map<String, dynamic>;
|
||
for (final operation in ['split', 'trimLeft', 'trimRight', 'setSpeed']) {
|
||
await selectAt(5);
|
||
final before = session.version;
|
||
final marker = 'CONTROLLED_${operation.toUpperCase()}_STACK';
|
||
session.fault = marker;
|
||
try {
|
||
await withDiagnosticContext({
|
||
'validationScenario': operation,
|
||
}, () => edit(operation));
|
||
} finally {
|
||
session.fault = null;
|
||
}
|
||
expect(session.version, before);
|
||
final events = (await exported())['events'] as List;
|
||
final event = events.singleWhere(
|
||
(e) =>
|
||
(e as Map)['level'] == 'error' &&
|
||
(e['context'] as Map)['validationScenario'] == operation,
|
||
) as Map;
|
||
expect(
|
||
event['operation'],
|
||
operation.startsWith('trim') ? 'trim' : operation,
|
||
);
|
||
final context = event['context'] as Map;
|
||
expect(context['clipIds'], ['clip']);
|
||
expect(context['timelineId'], 'timeline');
|
||
expect(context['projectId'], project.info.id);
|
||
expect(context['operationId'], isNotEmpty);
|
||
expect(context['versionBefore'], before);
|
||
expect(context['versionAfter'], before);
|
||
expect(event['stackTrace'], marker);
|
||
faults.add({
|
||
'operation': operation,
|
||
'passed': true,
|
||
'operationId': context['operationId'],
|
||
'stack': event['stackTrace'],
|
||
});
|
||
// Recovery uses the same UI path with the failure removed.
|
||
await edit(operation);
|
||
expect(session.version, isNot(before));
|
||
await settle();
|
||
await tester.tap(find.byTooltip('撤销'));
|
||
await tester.pump();
|
||
await settle();
|
||
await session.flush();
|
||
save();
|
||
}
|
||
Future<Map<String, Object?>> nativeCadence() async {
|
||
if (!cadence) return {};
|
||
final values = (await const MethodChannel('cutdex_runtime')
|
||
.invokeListMethod<Object?>('_debugPreviewCadence'))!;
|
||
return values
|
||
.map((v) => Map<String, Object?>.from(v! as Map))
|
||
.singleWhere(
|
||
(v) => v['mounted'] == true && (v['rate']! as num) > 0,
|
||
);
|
||
}
|
||
|
||
Future<void> observe(Duration duration) async {
|
||
final watch = Stopwatch()..start();
|
||
while (watch.elapsed < duration) {
|
||
await tester.pump(const Duration(milliseconds: 16));
|
||
}
|
||
}
|
||
|
||
// Warm the native decoders and editor before collecting comparisons.
|
||
await selectAt(0);
|
||
await preview.togglePlayback();
|
||
await observe(const Duration(seconds: 2));
|
||
await preview.togglePlayback();
|
||
for (var round = 0; round < 6; round++) {
|
||
// Three paired comparisons; alternate pair order to reduce order bias.
|
||
logging = const [false, true, true, false, false, true][round];
|
||
await selectAt(5);
|
||
await session.flush();
|
||
await store.flush();
|
||
final initialFlushes = store.eventFlushes;
|
||
final initialBytes = store.eventBytesWritten;
|
||
recordCosts.clear();
|
||
frames.start();
|
||
measuring = true;
|
||
final watch = Stopwatch()..start();
|
||
for (final operation in ['split', 'trimLeft', 'trimRight']) {
|
||
await selectAt(5);
|
||
await edit(operation);
|
||
await settle();
|
||
await tester.tap(find.byTooltip('撤销'));
|
||
await tester.pump();
|
||
await settle();
|
||
}
|
||
await slider(2);
|
||
await settle();
|
||
final query = session.persistence.timeline(sequence).current.query();
|
||
expect(
|
||
session.clipSpeed(query.element(query.elementById(clipId)!)),
|
||
closeTo(2, 0.05),
|
||
);
|
||
await selectAt(0);
|
||
await preview.togglePlayback();
|
||
await observe(const Duration(milliseconds: 500));
|
||
final firstNative = await nativeCadence();
|
||
final firstPosition =
|
||
(await preview.session!.refresh()).position.seconds;
|
||
final playbackWatch = Stopwatch()..start();
|
||
await observe(const Duration(seconds: 3));
|
||
final lastNative = await nativeCadence();
|
||
final lastPosition =
|
||
(await preview.session!.refresh()).position.seconds;
|
||
playbackWatch.stop();
|
||
await preview.togglePlayback();
|
||
expect(lastPosition, greaterThan(firstPosition + 1));
|
||
expect(preview.error, isNull);
|
||
await tester.tap(find.text('1×'));
|
||
await settle();
|
||
await session.flush();
|
||
await store.flush();
|
||
await observe(const Duration(milliseconds: 150));
|
||
measuring = false;
|
||
final timing = frames.stop();
|
||
if (kProfileMode) expect(timing['count'], greaterThan(10));
|
||
final native = <String, Object?>{};
|
||
if (cadence) {
|
||
for (final value in [firstNative, lastNative]) {
|
||
expect(value['windowVisible'], isTrue);
|
||
expect(value['windowOccluded'], isFalse);
|
||
}
|
||
final frames =
|
||
(lastNative['frames']! as num) - (firstNative['frames']! as num);
|
||
final dropped =
|
||
(lastNative['dropped']! as num) -
|
||
(firstNative['dropped']! as num);
|
||
native.addAll({
|
||
'viewWidth': firstNative['width'],
|
||
'viewHeight': firstNative['height'],
|
||
'windowVisible': firstNative['windowVisible'],
|
||
'windowOccluded': firstNative['windowOccluded'],
|
||
'frames': frames,
|
||
'dropped': dropped,
|
||
'rendererFps': frames / (playbackWatch.elapsedMicroseconds / 1e6),
|
||
'displayedFps':
|
||
(frames - dropped) / (playbackWatch.elapsedMicroseconds / 1e6),
|
||
});
|
||
expect(frames, greaterThan(0));
|
||
}
|
||
runs.add({
|
||
'round': round,
|
||
'logging': logging,
|
||
'elapsedMs': watch.elapsedMicroseconds / 1000,
|
||
'flutterFrames': timing,
|
||
'nativeCadence': native,
|
||
'playbackSeconds': playbackWatch.elapsedMicroseconds / 1e6,
|
||
'playbackClockAdvanceSeconds': lastPosition - firstPosition,
|
||
'logCalls': recordCosts.length,
|
||
'recordP95Us': _percentile(recordCosts, .95),
|
||
'flushes': store.eventFlushes - initialFlushes,
|
||
'logBytes': store.eventBytesWritten - initialBytes,
|
||
});
|
||
expect(store.dropped, 0);
|
||
expect(store.writeFailures, 0);
|
||
save();
|
||
}
|
||
logging = true;
|
||
await session.flush();
|
||
final stored = await project.loadTimeline('timeline');
|
||
final savedClip = stored.sequences.single.elements.singleWhere(
|
||
(e) => e.id == clipId,
|
||
);
|
||
expect(savedClip.duration, duration);
|
||
expect(savedClip.sourceRange.duration, duration);
|
||
final bundle = await exported();
|
||
final errors = (bundle['events'] as List)
|
||
.where((e) => (e as Map)['level'] == 'error')
|
||
.toList();
|
||
expect(
|
||
errors,
|
||
hasLength(4),
|
||
reason: 'Only the four controlled failures are expected.',
|
||
);
|
||
savedState = {
|
||
'passed': true,
|
||
'durationSeconds': savedClip.duration.seconds,
|
||
'sourceDurationSeconds': savedClip.sourceRange.duration.seconds,
|
||
'errorEvents': errors.length,
|
||
};
|
||
final afterSource = await source.stat();
|
||
expect(afterSource.size, originalSource.size);
|
||
expect(afterSource.modified, originalSource.modified);
|
||
expect(tester.takeException(), isNull);
|
||
await tester.pumpWidget(const SizedBox.shrink());
|
||
passed = true;
|
||
save();
|
||
},
|
||
skip: output.isEmpty || !hasNativeMediaFixture,
|
||
timeout: const Timeout(Duration(minutes: 10)),
|
||
);
|
||
}
|
||
|
||
class _FaultingSession extends EditorTimelineSession {
|
||
_FaultingSession({
|
||
required super.document,
|
||
required super.persistence,
|
||
required super.assetUris,
|
||
super.diagnostics,
|
||
});
|
||
String? fault;
|
||
@override
|
||
T commit<T>(SequenceId? sequence, T Function() action) {
|
||
if (fault case final marker?) {
|
||
Error.throwWithStackTrace(
|
||
StateError('Controlled edit failure'),
|
||
StackTrace.fromString(marker),
|
||
);
|
||
}
|
||
return super.commit(sequence, action);
|
||
}
|
||
}
|
||
|
||
final class _FrameMeasurements {
|
||
final _frames = <FrameTiming>[];
|
||
var _active = false;
|
||
void accept(List<FrameTiming> frames) {
|
||
if (_active) _frames.addAll(frames);
|
||
}
|
||
|
||
void start() {
|
||
_frames.clear();
|
||
_active = true;
|
||
}
|
||
|
||
Map<String, Object?> stop() {
|
||
_active = false;
|
||
final build = _frames.map((f) => f.buildDuration.inMicroseconds).toList();
|
||
final raster = _frames.map((f) => f.rasterDuration.inMicroseconds).toList();
|
||
return {
|
||
'count': _frames.length,
|
||
'buildP95Us': _percentile(build, .95),
|
||
'rasterP95Us': _percentile(raster, .95),
|
||
'buildOver16ms': build.where((v) => v > 16667).length,
|
||
'rasterOver16ms': raster.where((v) => v > 16667).length,
|
||
};
|
||
}
|
||
}
|
||
|
||
int? _percentile(List<int> values, double fraction) {
|
||
if (values.isEmpty) return null;
|
||
final ordered = [...values]..sort();
|
||
return ordered[(ordered.length * fraction).ceil() - 1];
|
||
}
|