Files
cutdex/integration_test/windows_audio_media_test.dart
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

735 lines
27 KiB
Dart

import 'package:cutdex/app/editor_theme.dart';
// Opt-in validation of original audio through the real Windows editor/runtime.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'package:crypto/crypto.dart';
import 'package:cutdex/features/preview/preview_panel.dart';
import 'package:cutdex/features/properties/properties_panel.dart';
import 'package:cutdex/features/timeline/timeline_panel.dart';
import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex/persistence/app_database.dart';
import 'package:cutdex/workspace/media_file_extensions.dart';
import 'package:cutdex/workspace/media_import.dart';
import 'package:cutdex/workspace/preview_controller_registry.dart';
import 'package:cutdex/workspace/projects.dart';
import 'package:cutdex/workspace/timeline_provider.dart';
import 'package:cutdex_core/editor.dart';
import 'package:cutdex_preview/cutdex_preview.dart';
import 'package:cutdex_core/execution.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:drift/native.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:path/path.dart' as p;
import 'support/saved_edit_validation.dart';
double _rms(MediaWaveform wave) {
final values = [
for (final channel in wave.levels.first.channels)
for (var i = 2; i < channel.length; i += 3) channel[i],
];
return math.sqrt(
values.fold<double>(0, (sum, value) => sum + value * value) / values.length,
);
}
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
const source = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE');
const output = String.fromEnvironment('CUTDEX_VALIDATION_ROOT');
const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER');
const metadataOnly = bool.fromEnvironment('CUTDEX_VALIDATION_METADATA_ONLY');
testWidgets('Windows original audio: import, preview and editing', (
tester,
) async {
expect(Platform.isWindows, isTrue);
expect(source, isNotEmpty);
expect(output, isNotEmpty);
final paths =
Directory(source)
.listSync(recursive: true, followLinks: false)
.whereType<File>()
.where(
(file) =>
mediaKindForPath(file.path) != null &&
(filter.isEmpty ||
filter.split(',').any(p.basename(file.path).contains)),
)
.toList()
..sort((a, b) => a.path.compareTo(b.path));
expect(paths, isNotEmpty);
final root = await Directory(output).create(recursive: true);
final report = File(p.join(root.path, 'results.json'));
final savedEdits = SavedEditValidation();
final results = <Map<String, Object?>>[];
final database = AppDatabase(NativeDatabase.memory());
final container = ProviderContainer(
overrides: [appDatabaseProvider.overrideWithValue(database)],
);
final projects = container.read(projectsProvider.notifier);
final runtime = CutdexRuntime();
addTearDown(database.close);
var disposed = false;
addTearDown(() {
if (!disposed) container.dispose();
});
void save() => report.writeAsStringSync(
const JsonEncoder.withIndent(' ').convert({
'platform': 'windows',
'source': source,
'metadataOnly': metadataOnly,
'method': 'Original files; production source-preview controller, import service and editor widgets; native waveform, preview and H.264/AAC exports. Isolated settings/projects. Source SHA-256 checked.',
'files': results,
}),
);
Future<void> until(
bool Function() ready,
String label, {
int seconds = 60,
}) async {
final deadline = DateTime.now().add(Duration(seconds: seconds));
while (!ready()) {
if (DateTime.now().isAfter(deadline)) throw TimeoutException(label);
await tester.pump(const Duration(milliseconds: 50));
await Future<void>.delayed(const Duration(milliseconds: 10));
}
await tester.pump();
}
expect(
await projects.open(
p.join(
root.path,
'Audio-${DateTime.now().millisecondsSinceEpoch}.cutdex',
),
name: 'Windows 音频素材验证',
initialTimelineName: '01',
),
isTrue,
);
var projectId = container
.read(projectsProvider)
.requireValue
.activeProject!
.id;
for (var index = 0; index < paths.length; index++) {
final file = paths[index];
final before = await file.stat();
final beforeHash = (await sha256.bind(file.openRead()).first).toString();
final checks = <Map<String, Object?>>[];
final result = <String, Object?>{
'path': file.path,
'sourceSha256': beforeHash,
'checks': checks,
'passed': false,
};
results.add(result);
save();
var stage = 'setup';
String? testedTimeline;
void Function()? releaseTimeline;
Future<void> check(String name, Future<void> Function() action) async {
stage = name;
debugPrint(
'AUDIO_MEDIA ${index + 1}/${paths.length} $name ${p.basename(file.path)}',
);
final clock = Stopwatch()..start();
await action().timeout(const Duration(minutes: 4));
expect(
tester.takeException(),
isNull,
reason: 'Widget error during $name',
);
checks.add({
'stage': name,
'passed': true,
'milliseconds': clock.elapsedMilliseconds,
});
save();
}
try {
if (index > 0) {
if (container.read(projectsProvider).requireValue.timelines.length >=
Projects.maxTimelineCount) {
expect(
await projects.open(
p.join(
root.path,
'Audio-batch-${index + 1}-${DateTime.now().millisecondsSinceEpoch}.cutdex',
),
name: 'Windows 音频素材验证 ${index + 1}',
initialTimelineName: '${index + 1}',
),
isTrue,
);
projectId = container
.read(projectsProvider)
.requireValue
.activeProject!
.id;
} else {
expect(await projects.createTimeline(name: '${index + 1}'), isTrue);
}
}
final timelineId = container
.read(projectsProvider)
.requireValue
.timeline!
.id;
testedTimeline = timelineId;
final retained = container.listen(
editorTimelineProvider(projectId, timelineId),
(_, _) {},
);
releaseTimeline = retained.close;
final session = await container.read(
editorTimelineProvider(projectId, timelineId).future,
);
final sequence = session.activeSequenceId!;
final media = MediaReference(id: 'audio-source', uri: file.uri);
late MediaInfo info;
await check('probeOriginal', () async {
info = await runtime.probe(media);
expect(info.audioTrackCount, 1);
expect(info.videoTrackCount, 0);
expect(info.duration.seconds, greaterThan(10));
expect(info.isProtected, isFalse);
result['durationSeconds'] = info.duration.seconds;
result['audioTracks'] = info.audioTracks
.map(
(track) => {
'start': track.start.toMap(),
'duration': track.duration.toMap(),
},
)
.toList();
});
await check('fullSourceWaveform', () async {
final wave = await runtime.waveform(
WaveformRequest(
media: media,
trackSelection: const TrackSelection.defaultTrack(),
baseBucketCount: 512,
levelCount: 3,
),
);
expect(wave.frameCount, greaterThan(0));
expect(_rms(wave), greaterThan(.0001));
result['waveform'] = {
'sampleRate': wave.sampleRate,
'channels': wave.levels.first.channels.length,
'frames': wave.frameCount,
'rms': _rms(wave),
};
expect(
wave.frameCount / wave.sampleRate,
closeTo(info.duration.seconds, .5),
);
});
if (!metadataOnly) {
await check('sourcePreviewPlayPauseAndSeek', () async {
final controller = SourcePreviewController(
loadMedia: <T>(action) => action(media),
frameDuration: RationalTime(1, 30),
rememberPosition: (_) {},
runtime: runtime,
);
try {
await controller.initialize(Future<void>.value());
expect(controller.error, isNull);
expect(controller.audioOnly, isTrue);
expect(controller.canPlay, isTrue);
final observations = <Map<String, Object?>>[];
for (final at in [
0.0,
info.duration.seconds / 2,
info.duration.seconds - 2,
]) {
await controller.session!.seek(
MediaTime((at * 1000).round(), 1000),
);
await controller.togglePlayback();
await until(() {
if (controller.error != null) {
throw StateError('${controller.error}');
}
return controller.playing &&
controller.positionTick >
(at + .4) * TimelineClock.ticksPerSecond;
}, 'source playback at $at');
final played = await controller.session!.refresh();
expect(played.message, isNull);
await controller.togglePlayback();
final paused = await controller.session!.refresh();
await Future<void>.delayed(const Duration(milliseconds: 200));
final still = await controller.session!.refresh();
expect(still.state, PlaybackState.paused);
expect(
still.position.seconds,
closeTo(paused.position.seconds, .05),
);
observations.add({
'at': at,
'playedTo': played.position.seconds,
'pausedAt': paused.position.seconds,
});
}
result['sourcePlayback'] = observations;
} finally {
await controller.close();
controller.dispose();
}
});
final clipId = ElementId('audio-clip');
await check('importOriginalAndInsertAudio', () async {
final imported = await projects.importExternalMedia(projectId, [
ExternalMediaFile(path: file.path),
]);
expect(imported!.failures, isEmpty);
final asset = imported.assets.firstWhere(
(a) => a.name == p.basename(file.path),
);
await session.commands.executeEdit(
sequence,
const SetProjectCanvas(width: 320, height: 180),
);
await session.commands.insertMedia(
sequence: sequence,
assetId: asset.id,
clipId: clipId,
index: 0,
sourceStart: RationalTime.seconds(2),
duration: RationalTime.seconds(8),
);
final binding = session.mediaBinding(
session.persistence
.timeline(sequence)
.exportDto()
.elements
.single
.payloadRef!,
);
expect(binding!.videoTrackIndex, isNull);
expect(binding.audioTrackIndex, 0);
});
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'),
theme: EditorTheme.penLight,
home: Scaffold(
body: Column(
children: [
Expanded(
child: Row(
children: [
Expanded(
child: EditorPreviewPanel(
projectId: projectId,
timelineId: timelineId,
),
),
SizedBox(
width: 280,
child: EditorPropertiesPanel(
projectId: projectId,
timelineId: timelineId,
),
),
],
),
),
SizedBox(
height: 210,
child: EditorTimelinePanel(
projectId: projectId,
timelineId: timelineId,
),
),
],
),
),
),
),
);
await check('initializeEditorPreview', () async {
await container.read(
editorPreviewProvider(projectId, timelineId).future,
);
await until(() {
final state = container.read(
editorPreviewProvider(projectId, timelineId),
);
if (state.hasError) throw StateError('${state.error}');
if (state.asData?.value?.error != null) {
throw StateError('${state.asData!.value!.error}');
}
return state.asData?.value?.ready == true;
}, 'editor preview initialization');
});
final preview = container
.read(editorPreviewProvider(projectId, timelineId))
.requireValue!;
ElementRecord record() {
final q = session.persistence.timeline(sequence).current.query();
return q.element(q.elementById(clipId)!);
}
Future<void> settled() async {
await tester.pump();
await until(
() => !preview.busy && preview.ready,
'preview synchronization',
);
expect(preview.error, isNull);
}
Future<void> seek(double seconds) async {
await preview.controlPreview(
sequence,
PreviewAction.seek,
at: CommandTime((seconds * 1000).round(), 1000),
);
await settled();
expect(
(await preview.session!.refresh()).position.seconds,
closeTo(seconds, .1),
);
}
Future<void> playback() async {
await seek(0);
await tester.tap(find.byTooltip('播放').first);
await until(() {
if (preview.error != null) throw StateError('${preview.error}');
final snapshot = preview.session!.snapshot;
if (snapshot?.message != null) {
throw StateError('${snapshot!.message}');
}
return preview.playing &&
preview.positionTick > TimelineClock.ticksPerSecond / 2;
}, 'timeline playback');
final playing = await preview.session!.refresh();
await tester.tap(find.byTooltip('暂停播放').first);
await until(
() => !preview.playing && !preview.busy,
'timeline pause',
);
final paused = await preview.session!.refresh();
await Future<void>.delayed(const Duration(milliseconds: 200));
expect(
(await preview.session!.refresh()).position.seconds,
closeTo(paused.position.seconds, .05),
);
(result.putIfAbsent(
'timelinePlayback',
() => <Map<String, Object?>>[],
) as List).add({
'stage': stage,
'playedTo': playing.position.seconds,
});
}
ExecutionPlan plan() => const ExecutionCompiler()
.compile(
ExecutionInput(
timeline: session.persistence.timeline(sequence),
media: {
record().payloadRef!: ExecutionMediaBinding(
media: media,
videoTrackSelection: null,
audioTrackSelection: TrackSelection.id(
info.audioTrackIds.first!,
),
audioTiming: info.audioTracks.first,
),
},
renderSize: RenderSize(320, 180),
parameterTargets: {
...ClipTransform.targets,
...ClipAudioGain.targets,
},
editorOnlyParameters: const {ClipAudioGain.detachedId},
),
)
.plan;
Future<MediaWaveform> export(String suffix, double duration) async {
final compiled = plan();
expect(compiled.visualLayers, isEmpty);
expect(compiled.audioLayers, hasLength(1));
final destination = File(
p.join(
root.path,
'${index.toString().padLeft(2, '0')}-$suffix.mp4',
),
).uri;
final uri = await preview.session!.export(compiled, destination);
final exported = MediaReference(id: suffix, uri: uri);
final metadata = await runtime.probe(exported);
expect(metadata.audioTrackCount, 1);
expect(metadata.duration.seconds, closeTo(duration, .12));
final wave = await runtime.waveform(
WaveformRequest(
media: exported,
baseBucketCount: 64,
levelCount: 1,
),
);
expect(wave.frameCount / wave.sampleRate, closeTo(duration, .12));
(result.putIfAbsent(
'exports',
() => <Map<String, Object?>>[],
) as List).add({
'kind': suffix,
'path': uri.toFilePath(),
'duration': metadata.duration.seconds,
'rms': _rms(wave),
});
return wave;
}
await check('editorPlayPauseAndScrub', () async {
await playback();
for (final at in [6.5, .5, 7.5, 2.0, 0.0]) {
await seek(at);
}
});
await check('splitToolbarUndoRedo', () async {
preview.selectVisual(clipId);
await seek(4);
await tester.tap(find.byTooltip('在播放头处分割'));
await settled();
expect(record().duration, 4 * TimelineClock.ticksPerSecond);
expect(
session.persistence.timeline(sequence).exportDto().elements,
hasLength(2),
);
await session.commands.executeEdit(sequence, const UndoEdit());
await settled();
expect(record().duration, 8 * TimelineClock.ticksPerSecond);
await session.commands.executeEdit(sequence, const RedoEdit());
await settled();
final other = session.persistence
.timeline(sequence)
.exportDto()
.elements
.firstWhere((e) => e.id != clipId);
await session.commands.executeEdit(
sequence,
DeleteClip(other.id.value),
);
await settled();
await playback();
});
late MediaWaveform baseline;
await check('baselineExport', () async {
baseline = await export('baseline', 4);
expect(_rms(baseline), greaterThan(.0001));
});
await check('speedSliderAndRenderedHalfDouble', () async {
preview.selectVisual(clipId);
await seek(0);
await tester.tap(find.byKey(const ValueKey('property-tab-speed')));
await tester.pump();
final slider = find.descendant(
of: find.byKey(const Key('clip-speed-slider')),
matching: find.byType(Slider),
);
expect(slider, findsOneWidget);
for (final speed in [2.0, .5, 1.0]) {
final bounds = tester.getRect(slider);
final position = (math.log(speed) / math.ln10 + 1) / 3;
final gesture = await tester.startGesture(
Offset(
bounds.left +
12 +
(bounds.width - 24) * tester.widget<Slider>(slider).value,
bounds.center.dy,
),
);
await gesture.moveTo(
Offset(
bounds.left + 12 + (bounds.width - 24) * position,
bounds.center.dy,
),
);
await tester.pump();
await gesture.up();
await settled();
expect(session.clipSpeed(record()), closeTo(speed, .05));
expect(
record().duration,
closeTo(
4 * TimelineClock.ticksPerSecond / speed,
TimelineClock.ticksPerSecond / 4,
),
);
await playback();
if (speed != 1) {
final wave = await export(
'speed-$speed',
record().duration / TimelineClock.ticksPerSecond,
);
expect(_rms(wave), greaterThan(.0001));
}
}
session.setClipSpeed(sequence, clipId, 1);
await settled();
});
await check('gainMuteAndRenderedAudio', () async {
await session.commands.executeEdit(
sequence,
const SetClipAudio(clipId: 'audio-clip', db: -6, muted: false),
);
await settled();
await playback();
final gained = await export('gain-minus6', 4);
final ratio = _rms(gained) / _rms(baseline);
expect(ratio, closeTo(math.pow(10, -6 / 20).toDouble(), .06));
result['gainRmsRatio'] = ratio;
await session.commands.executeEdit(
sequence,
const SetClipAudio(clipId: 'audio-clip', db: -6, muted: true),
);
await settled();
await playback();
expect(
_rms(await export('muted', 4)),
lessThanOrEqualTo(1 / 32768),
);
await session.commands.executeEdit(
sequence,
const SetClipAudio(clipId: 'audio-clip', db: 0, muted: false),
);
await settled();
});
await check('audioKeyframesInterpolationAndRenderedFade', () async {
for (final entry in [(0, 0.0), (3500, -10.5)]) {
await session.commands.executeEdit(
sequence,
EditKeyframe(
clipId: 'audio-clip',
parameterId: ClipAudioGain.gainId,
at: CommandTime(entry.$1, 1000),
action: KeyframeAction.set,
value: entry.$2,
interpolation: KeyInterpolation.linear,
),
);
}
await settled();
final curve = record().parameters![ClipAudioGain.gainId]!;
expect(curve.toDto().keyframes, hasLength(2));
expect(
curve.valueAt(
record().sourceStart + TimelineClock.ticksPerSecond,
),
closeTo(-3, .01),
);
await playback();
final faded = await export('keyframe-fade', 4);
final reference = baseline.levels.first.channels.first;
final rendered = faded.levels.first.channels.first;
double ratioAt(int start, int end) {
final ratios = <double>[];
for (var bucket = start; bucket < end; bucket++) {
final at = bucket * 3 + 2;
if (reference[at] > .001) {
ratios.add(rendered[at] / reference[at]);
}
}
expect(ratios, isNotEmpty);
return ratios.reduce((a, b) => a + b) / ratios.length;
}
final early = ratioAt(4, 12);
final late = ratioAt(48, 56);
expect(early, closeTo(.84, .15));
expect(late, closeTo(.33, .15));
expect(late, lessThan(early * .65));
result['keyframeRatios'] = {'early': early, 'late': late};
});
await check('saveAndReadPersistedAudioEdits', () async {
await session.flush();
expect(session.saveError, isNull);
final projectPath = container
.read(projectsProvider)
.requireValue
.activeProject!
.path;
final edits = await savedEdits.capture(
projectPath,
timelineId,
session,
sequence,
);
expect(
((edits['clips'] as List).single as Map)['parameters'],
hasLength(greaterThanOrEqualTo(2)),
);
result['savedTimelineId'] = timelineId;
result['savedProject'] = projectPath;
});
}
result['passed'] = true;
} catch (error, stack) {
checks.add({
'stage': stage,
'passed': false,
'error': '$error',
'stack': '$stack',
});
debugPrint('AUDIO_MEDIA_FAILED $stage $error\n$stack');
}
final after = await file.stat();
result['sourceUnchanged'] =
before.size == after.size &&
before.modified == after.modified &&
beforeHash == (await sha256.bind(file.openRead()).first).toString();
if (result['sourceUnchanged'] != true) result['passed'] = false;
save();
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
if (testedTimeline != null) {
await container.read(previewControllerRegistryProvider).invalidate((
projectId,
testedTimeline,
));
}
releaseTimeline?.call();
}
container.dispose();
disposed = true;
await savedEdits.verify(
wait: tester.pump,
onVerified: (projectPath, timelineId, edits) {
final result = results.singleWhere(
(r) =>
r['savedProject'] == projectPath &&
r['savedTimelineId'] == timelineId,
);
result['savedEditsIdenticalAfterReopen'] = true;
save();
},
);
expect(
results.where((file) => file['passed'] != true).toList(),
isEmpty,
reason: 'See ${report.path}',
);
}, timeout: const Timeout(Duration(minutes: 120)));
}