import 'package:cutdex/app/editor_theme.dart'; // Opt-in Windows validation against original media; sources are read-only. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:math' as math; import 'dart:ui' as ui; 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/projects.dart'; import 'package:cutdex/workspace/preview_controller_registry.dart'; import 'package:cutdex/workspace/timeline_provider.dart'; import 'package:cutdex_core/editor.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'; void main() { final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); const source = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE'); const output = String.fromEnvironment('CUTDEX_VALIDATION_ROOT'); const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER'); const previewObservationSeconds = int.fromEnvironment( 'CUTDEX_VALIDATION_PREVIEW_SECONDS', defaultValue: 2, ); const longSpeedOnly = bool.fromEnvironment( 'CUTDEX_VALIDATION_LONG_SPEED_ONLY', ); const fullPreviewAudio = bool.fromEnvironment( 'CUTDEX_VALIDATION_FULL_PREVIEW_AUDIO', defaultValue: true, ); const fullPreviewMuted = bool.fromEnvironment( 'CUTDEX_VALIDATION_FULL_PREVIEW_MUTE', ); const muteDamagedAsf = bool.fromEnvironment( 'CUTDEX_VALIDATION_MUTE_DAMAGED_ASF', ); const sourceRoots = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE_ROOTS'); testWidgets('Windows real media: preview, transport and editing through native runtime', ( tester, ) async { expect(Platform.isWindows, isTrue); expect(sourceRoots.isEmpty ? source : sourceRoots, isNotEmpty); expect(output, isNotEmpty); final paths = (sourceRoots.isEmpty ? [source] : sourceRoots.split(';')) .expand( (root) => Directory(root).listSync(recursive: true, followLinks: false), ) .whereType() .where( (file) => mediaKindForPath(file.path) == 'video' && (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 results = >[]; final savedEdits = SavedEditValidation(); 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', 'fullPreviewAudio': fullPreviewAudio, 'fullPreviewMuted': fullPreviewMuted, 'longSpeedOnly': longSpeedOnly, 'source': source, 'method': 'Original files; production import service, real editor widgets, ' 'split toolbar and speed slider; command service for keyframes/audio/masks; ' 'native preview, thumbnails and export. Settings database isolated in memory.', 'files': results, }), ); Future 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.delayed(const Duration(milliseconds: 10)); } await tester.pump(); } expect( await projects.open( p.join( root.path, 'Real-media-${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 muteFullSource = fullPreviewMuted || (muteDamagedAsf && p.extension(file.path).toLowerCase() == '.asf'); final before = await file.stat(); final checks = >[]; final result = { 'path': file.path, 'checks': checks, 'passed': false, 'fullSourceMuted': muteFullSource, }; results.add(result); save(); var stage = 'setup'; String? testedTimeline; void Function()? releaseTimeline; Future check(String name, Future Function() action) async { stage = name; debugPrint( 'REAL_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, 'Real-media-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 retainedTimeline = container.listen( editorTimelineProvider(projectId, timelineId), (_, _) {}, ); releaseTimeline = retainedTimeline.close; final session = await container.read( editorTimelineProvider(projectId, timelineId).future, ); final sequence = session.activeSequenceId!; final view = session.view(sequence); final media = MediaReference(id: 'real-source', uri: file.uri); late MediaInfo info; await check('probeOriginalAndSeekThumbnails', () async { info = await runtime.probe(media); expect(info.videoTrackCount, greaterThan(0)); expect(info.audioTrackCount, greaterThan(0)); expect(info.duration.seconds, greaterThan(120)); result['durationSeconds'] = info.duration.seconds; result['audioTracks'] = info.audioTrackCount; result['displaySizes'] = [ for (final size in info.videoDisplaySizes) [size.width, size.height], ]; for (final seconds in [ 60.0, info.duration.seconds / 2, info.duration.seconds - 5, ]) { final thumbnail = await runtime.thumbnail( ThumbnailRequest( media: media, time: MediaTime((seconds * 1000).round(), 1000), maximumWidth: 320, maximumHeight: 180, ), ); expect(thumbnail.data, isNotEmpty); final image = await decodeImageFromList(thumbnail.data); expect(image.width, greaterThan(0)); image.dispose(); } }); if (!longSpeedOnly) { await check('fullLengthPreviewStartMiddleAndEnd', () async { final full = await runtime.createSession(); try { final duration = MediaTime( (math.min( info.duration.seconds, info.audioTracks.first.duration.seconds, ) * 1000) .floor() - 100, 1000, ); final range = MediaRange( start: MediaTime(0, 1), duration: duration, ); await full.load( ExecutionPlan( duration: duration, renderSize: RenderSize(640, 360), frameDuration: MediaTime(1, 30), media: [media], visualLayers: [ VisualLayer( id: 'full-video', mediaId: media.id, sourceRange: range, timelineRange: range, inputColorSpace: info.videoColorSpaces[0] ?? RenderColorSpace.rec709, ), ], audioLayers: [ if (fullPreviewAudio) AudioLayer( id: 'full-audio', volume: muteFullSource ? 0 : 1, mediaId: media.id, sourceRange: range, timelineRange: range, ), ], ), ); for (var i = 0; i < 3; i++) { await full.pause(); await Future.delayed(const Duration(milliseconds: 100)); expect((await full.refresh()).message, isNull); } await tester.pumpWidget( MaterialApp( home: Center( child: SizedBox( width: 640, height: 360, child: RuntimePreview(session: full), ), ), ), ); await full.play(); await until( () => (full.snapshot?.presentedVideoFrameCount ?? 0) > 0, 'full-length first playback frames', seconds: 90, ); await full.pause(); final observations = >[]; for (final seconds in [ 60.0, duration.seconds / 2, duration.seconds - math.max(5, previewObservationSeconds + 3), duration.seconds / 4, ]) { await full.seek(MediaTime((seconds * 1000).round(), 1000)); await full.play(); final before = await full.refresh(); final uiTimings = []; void collectTimings(List timings) { uiTimings.addAll(timings); } WidgetsBinding.instance.addTimingsCallback(collectTimings); // Native textures can redraw without a Dart frame. Refresh the // viewport continuously so Profile runs also measure Flutter's // raster cost instead of treating missing timings as zero cost. final previousPolicy = binding.framePolicy; binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; final viewportRefresh = Timer.periodic( const Duration(milliseconds: 16), (_) => binding.scheduleFrame(), ); final startUnixMs = DateTime.now().millisecondsSinceEpoch; final observed = Stopwatch()..start(); try { await Future.delayed( const Duration(seconds: previewObservationSeconds), ); await tester.pump(); } finally { viewportRefresh.cancel(); binding.framePolicy = previousPolicy; WidgetsBinding.instance.removeTimingsCallback(collectTimings); } final after = await full.refresh(); final observation = { 'pid': pid, 'startUnixMs': startUnixMs, 'endUnixMs': DateTime.now().millisecondsSinceEpoch, 'at': seconds, 'position': after.position.seconds, 'beforeFrames': before.presentedVideoFrameCount, 'frames': (after.presentedVideoFrameCount ?? 0) - (before.presentedVideoFrameCount ?? 0), 'maximumFrameGapMs': after.maximumVideoFrameGapMs, 'droppedFrames': after.droppedVideoFrameCount, 'observationSeconds': observed.elapsedMicroseconds / 1000000, 'deliveredFramesPerSecond': ((after.presentedVideoFrameCount ?? 0) - (before.presentedVideoFrameCount ?? 0)) / (observed.elapsedMicroseconds / 1000000), 'message': after.message, 'flutterFrameTimingCount': uiTimings.length, 'flutterTimingMode': 'continuous viewport refresh', 'flutterBuildOver16ms': uiTimings .where( (timing) => timing.buildDuration.inMicroseconds > 16667, ) .length, 'flutterRasterOver16ms': uiTimings .where( (timing) => timing.rasterDuration.inMicroseconds > 16667, ) .length, 'flutterMaximumBuildMs': uiTimings.fold( 0, (maximum, timing) => math.max( maximum, timing.buildDuration.inMicroseconds / 1000, ), ), 'flutterMaximumRasterMs': uiTimings.fold( 0, (maximum, timing) => math.max( maximum, timing.rasterDuration.inMicroseconds / 1000, ), ), }; observations.add(observation); result['fullLengthPlayback'] = observations; debugPrint('REAL_MEDIA_FULL_PLAYBACK $observation'); expect(after.message, isNull); expect(after.position.seconds, greaterThan(seconds + .5)); expect( after.presentedVideoFrameCount, greaterThan(before.presentedVideoFrameCount ?? 0), ); await full.pause(); } result['fullLengthPlayback'] = observations; } finally { await tester.pumpWidget(const SizedBox.shrink()); await full.close(); } }); } await check('importOriginalAndInsertSourceRange', () 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: 640, height: 360), ); await session.commands.insertMedia( sequence: sequence, assetId: asset.id, clipId: ElementId('real-clip'), index: 0, sourceStart: RationalTime.seconds(longSpeedOnly ? 0 : 60), duration: longSpeedOnly ? RationalTime( (math.min( info.duration.seconds, info.audioTracks.first.duration.seconds, ) * 1000) .floor() - 100, 1000, ) : RationalTime.seconds(8), ); }); 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('initializeNativePreview', () async { final initialized = await container .read(editorPreviewProvider(projectId, timelineId).future) .timeout(const Duration(minutes: 2)); if (initialized == null) { throw StateError( 'Preview is empty; timeline duration ${session.sequenceDurationTicks(sequence)}', ); } debugPrint( 'REAL_MEDIA_INITIALIZED ready=${initialized.ready} busy=${initialized.busy} error=${initialized.error} duration=${initialized.durationTick}', ); await until( () { final state = container.read( editorPreviewProvider(projectId, timelineId), ); if (state.hasError) { throw StateError('Native preview startup: ${state.error}'); } final value = state.asData?.value; if (value?.error != null) { throw StateError('Native preview: ${value!.error}'); } return value?.ready == true; }, 'preview initialized', seconds: 180, ); }); final preview = container .read(editorPreviewProvider(projectId, timelineId)) .requireValue!; // Windows counts presented frames while the playback clock runs. await preview.controlPreview(sequence, PreviewAction.play); await until( () => (preview.session?.snapshot?.presentedVideoFrameCount ?? 0) > 0, 'first preview frame', seconds: 90, ); await preview.controlPreview(sequence, PreviewAction.pause); final clipId = ElementId('real-clip'); ElementRecord record() { final q = session.persistence.timeline(sequence).current.query(); return q.element(q.elementById(clipId)!); } Future settled() async { await tester.pump(); await until( () => !preview.busy && preview.ready, 'preview synchronization: ${preview.error}', ); expect(preview.error, isNull); } Future 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, .15), ); } Future playback({double start = 0}) async { await seek(start); await tester.tap(find.byTooltip('播放').first); await until(() => preview.playing, 'play control accepted'); final beforePlay = await preview.session!.refresh(); var nextLog = DateTime.now(); await until(() { if (preview.error != null) { throw StateError('Preview playback: ${preview.error}'); } final native = preview.session!.snapshot; if (native?.message != null) { throw StateError('Native playback: ${native!.message}'); } if (DateTime.now().isAfter(nextLog)) { nextLog = DateTime.now().add(const Duration(seconds: 2)); debugPrint( 'REAL_MEDIA_CLOCK ui=${preview.playing}/${preview.positionTick} native=${native?.state}/${native?.position.seconds}/${native?.presentedVideoFrameCount} busy=${preview.busy}', ); } return preview.playing && preview.positionTick > (start + .5) * TimelineClock.ticksPerSecond && (native?.presentedVideoFrameCount ?? 0) > (beforePlay.presentedVideoFrameCount ?? 0); }, 'native playback clock'); await Future.delayed( const Duration(milliseconds: longSpeedOnly ? 1800 : 250), ); await tester.pump(); final playing = await preview.session!.refresh(); expect( playing.presentedVideoFrameCount, greaterThan(beforePlay.presentedVideoFrameCount ?? 0), ); await tester.tap(find.byTooltip('暂停播放').first); await until(() => !preview.playing && !preview.busy, 'native pause'); final at = preview.positionTick; await tester.pump(const Duration(milliseconds: 250)); expect( (preview.positionTick - at).abs(), lessThan(TimelineClock.ticksPerSecond / 10), ); expect(preview.error, isNull); (result.putIfAbsent( 'playback', () => >[], ) as List).add({ 'stage': stage, 'positionSeconds': playing.position.seconds, 'frames': playing.presentedVideoFrameCount, 'dropped': playing.droppedVideoFrameCount, 'maximumGapMs': playing.maximumVideoFrameGapMs, 'rssBytes': ProcessInfo.currentRss, }); } if (longSpeedOnly) { await check( 'fullLengthPitchPreservingSpeedAndWindowCrossing', () async { final sourceStart = record().sourceStart; final sourceDuration = record().sourceDuration; final speeds = >[]; for (final speed in [2.0, .5, 1.0]) { session.setClipSpeed(sequence, clipId, speed); await settled(); expect(session.clipSpeed(record()), speed); expect(record().sourceStart, sourceStart); expect(record().sourceDuration, sourceDuration); expect(record().duration, closeTo(sourceDuration / speed, 1)); final clock = Stopwatch()..start(); await playback(); await playback(start: 29.5); speeds.add({ 'speed': speed, 'sourceTicks': sourceDuration, 'timelineTicks': record().duration, 'playbackMs': clock.elapsedMilliseconds, }); } result['fullLengthSpeeds'] = speeds; }, ); } else { await check('nativePreviewPlayPauseAndScrub', () async { expect(find.byType(RuntimePreview), findsOneWidget); 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 .length, 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(); }); await check('speedSliderHalfDoubleAndNormal', () 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 requested in [2.0, .5, 1.0]) { final bounds = tester.getRect(slider); final position = (math.log(requested) / math.ln10 + 1) / 3; final gesture = await tester.startGesture( Offset( bounds.left + 12 + (bounds.width - 24) * tester.widget(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(requested, .05)); expect( record().duration, closeTo( 4 * TimelineClock.ticksPerSecond / requested, TimelineClock.ticksPerSecond / 4, ), ); await playback(); } // Keep exact source timing for subsequent pixel/audio comparisons. session.setClipSpeed(sequence, clipId, 1); await settled(); }); await check('segmentedSpeedSourceClockAndRestore', () async { await seek(0); final originalSource = record().sourceStart; final originalDuration = record().sourceDuration; session.splitClipSpeedAt( sequence, clipId, 2 * TimelineClock.ticksPerSecond, ); await settled(); expect(session.clipSpeedSegments(record()), hasLength(2)); session.setClipSpeedSegmentDuration( sequence, clipId, 1, TimelineClock.ticksPerSecond, ); await settled(); expect(record().duration, 3 * TimelineClock.ticksPerSecond); expect(record().sourceDuration, originalDuration); expect( TimelineSourceClock(record()) .nearestSourceTick(TimelineClock.ticksPerSecond * 5 ~/ 2), originalSource + 3 * TimelineClock.ticksPerSecond, ); await seek(2.5); await playback(); await session.commands.executeEdit(sequence, const UndoEdit()); await settled(); expect(record().duration, 4 * TimelineClock.ticksPerSecond); session.setClipSpeed(sequence, clipId, 1); await settled(); expect(session.clipSpeedSegments(record()), hasLength(1)); expect(record().sourceDuration, originalDuration); }); Future export(String suffix, {int audioOrdinal = 0}) async { final plan = const ExecutionCompiler() .compile( ExecutionInput( timeline: session.persistence.timeline(sequence), media: { record().payloadRef!: ExecutionMediaBinding( media: media, videoTrackSelection: TrackSelection.id( info.videoTrackIds.first!, ), inputColorSpace: info.videoColorSpaces[0] ?? RenderColorSpace.rec709, audioTrackSelection: TrackSelection.id( info.audioTrackIds[audioOrdinal]!, ), audioTiming: info.audioTracks[audioOrdinal], ), }, renderSize: RenderSize(320, 180), parameterTargets: { ...ClipTransform.targets, ...ClipAudioGain.targets, }, editorOnlyParameters: const {ClipAudioGain.detachedId}, ), ) .plan; return preview.session!.export( plan, File( p.join( root.path, '${index.toString().padLeft(2, '0')}-$suffix.mp4', ), ).uri, ); } late Uri baseline; await check('baselineExportAndAudio', () async { baseline = await export('baseline'); final exported = await runtime.probe( MediaReference(id: 'baseline', uri: baseline), ); expect(exported.videoTrackCount, 1); expect(exported.audioTrackCount, 1); expect(exported.duration.seconds, closeTo(4, .1)); result['baselineExport'] = baseline.toFilePath(); }); if (info.audioTrackCount > 1) { await check('alternateAudioTrackExportAndDecode', () async { final uri = await export('audio-track-1', audioOrdinal: 1); final alternate = MediaReference(id: 'alternate-audio', uri: uri); final wave = await runtime.waveform( WaveformRequest( media: alternate, baseBucketCount: 64, levelCount: 1, ), ); expect(wave.levels.first.channels.length, 2); expect( wave.levels.first.channels .expand((values) => values) .any((value) => value.abs() > .0001), isTrue, ); result['alternateAudioExport'] = uri.toFilePath(); }); } await check('staticTransformExportAndReset', () async { await session.commands.executeEdit( sequence, SetClipTransform( clipId: 'real-clip', at: CommandTime(0, 1), x: 32, y: -18, scaleX: .5, scaleY: .75, rotation: 30, ), ); await settled(); final value = ClipTransform.fromRecord(record()); expect(value.x, closeTo(.05, .000001)); expect(value.y, closeTo(-.05, .000001)); expect(value.scale, .5); expect(value.scaleY, .75); expect(value.rotation, 30); await playback(); final uri = await export('transform'); result['transformExport'] = uri.toFilePath(); await session.commands.executeEdit( sequence, SetClipTransform( clipId: 'real-clip', at: CommandTime(0, 1), x: 0, y: 0, scaleX: 1, scaleY: 1, rotation: 0, ), ); await settled(); }); await check('multiChannelKeyframesInterpolationAndClear', () async { final channels = { 'canvas.position.y': (0, .1), 'canvas.scale.x': (1, .5), 'canvas.scale.y': (1, .75), 'canvas.rotation': (0, 30), }; for (final channel in channels.entries) { for (final key in [ (0, channel.value.$1), (2, channel.value.$2), ]) { await session.commands.executeEdit( sequence, EditKeyframe( clipId: 'real-clip', parameterId: channel.key, at: CommandTime(key.$1, 1), action: KeyframeAction.set, value: key.$2, interpolation: KeyInterpolation.linear, ), ); } } await settled(); await seek(1); final q = session.persistence.timeline(sequence).current.query(); final value = ClipAnimation.at( q, q.elementById(clipId)!, TimelineClock.ticksPerSecond, TimelineClock.ticksPerSecond ~/ 30, ).value; expect(value.y, closeTo(-.05, .001)); expect(value.scale, closeTo(.75, .001)); expect(value.scaleY, closeTo(.875, .001)); expect(value.rotation, closeTo(15, .001)); await playback(); for (final channel in channels.keys) { await session.commands.executeEdit( sequence, EditKeyframe( clipId: 'real-clip', parameterId: channel, at: CommandTime(0, 1), action: KeyframeAction.clear, ), ); } await session.commands.executeEdit( sequence, SetClipTransform( clipId: 'real-clip', at: CommandTime(0, 1), x: 0, y: 0, scaleX: 1, scaleY: 1, rotation: 0, ), ); await settled(); }); await check('audioGainMuteAndRestore', () async { await session.commands.executeEdit( sequence, const SetClipAudio(clipId: 'real-clip', db: -6, muted: true), ); await settled(); expect(ClipAudioGain.fromRecord(record()).muted, isTrue); await playback(); await session.commands.executeEdit( sequence, const SetClipAudio(clipId: 'real-clip', db: -6, muted: false), ); await settled(); expect(ClipAudioGain.fromRecord(record()).db, -6); }); await check('transformKeyframesAndInterpolation', () async { for (final entry in [(0, 0.0), (2, .1)]) { await session.commands.executeEdit( sequence, EditKeyframe( clipId: 'real-clip', parameterId: 'canvas.position.x', at: CommandTime(entry.$1, 1), action: KeyframeAction.set, value: entry.$2, interpolation: KeyInterpolation.linear, ), ); } await settled(); await seek(1); final animation = ClipAnimation.at( view.version.kernelVersion.query(), view.version.kernelVersion.query().elementById(clipId)!, TimelineClock.ticksPerSecond, TimelineClock.ticksPerSecond ~/ 30, ); expect(animation.value.x, closeTo(.05, .001)); await playback(); }); await check('rectangleEllipseFeatherAndInvertedMasks', () async { await seek(0); await session.commands.executeEdit( sequence, EditMask( clipId: 'real-clip', at: CommandTime(0, 1), action: MaskAction.add, maskId: 'real-mask', shape: MaskShape.rectangle, x: .5, y: .5, width: .5, height: .5, ), ); await settled(); for (final inverted in [false, true]) { await session.commands.executeEdit( sequence, EditMask( clipId: 'real-clip', at: CommandTime(0, 1), action: MaskAction.set, maskId: 'real-mask', shape: MaskShape.ellipse, inverted: inverted, feather: .1, ), ); await settled(); expect( ClipMaskStack(record(), 0).layers.single.mask.inverted, inverted, ); await playback(); } await session.commands.executeEdit( sequence, EditMask( clipId: 'real-clip', at: CommandTime(0, 1), action: MaskAction.set, maskId: 'real-mask', shape: MaskShape.rectangle, inverted: false, feather: 0, ), ); await settled(); }); await check('maskAnimationStackAndRestore', () async { final layer = ClipMaskStack(record(), 0).layers.single; for (final key in [(0, .5), (2, .7)]) { await session.commands.executeEdit( sequence, EditKeyframe( clipId: 'real-clip', parameterId: layer.target('center.x'), at: CommandTime(key.$1, 1), action: KeyframeAction.set, value: key.$2, interpolation: KeyInterpolation.linear, ), ); } await settled(); await seek(1); expect( ClipMaskStack( record(), TimelineClock.ticksPerSecond, ).layers.single.mask.x, closeTo(.6, .001), ); await playback(); await session.commands.executeEdit( sequence, EditMask( clipId: 'real-clip', at: CommandTime(0, 1), action: MaskAction.add, maskId: 'second-mask', shape: MaskShape.ellipse, mode: MaskMode.intersect, width: .8, height: .8, ), ); await session.commands.executeEdit( sequence, EditMask( clipId: 'real-clip', at: CommandTime(0, 1), action: MaskAction.reorder, maskIds: ['second-mask', 'real-mask'], ), ); await settled(); expect(ClipMaskStack(record(), 0).layers.map((l) => l.id), [ 'second-mask', 'real-mask', ]); await playback(); await session.commands.executeEdit( sequence, EditMask( clipId: 'real-clip', at: CommandTime(0, 1), action: MaskAction.setEnabled, maskId: 'second-mask', enabled: false, ), ); await settled(); expect(ClipMaskStack(record(), 0).layers.first.enabled, isFalse); await session.commands.executeEdit( sequence, EditMask( clipId: 'real-clip', at: CommandTime(0, 1), action: MaskAction.remove, maskId: 'second-mask', ), ); await session.commands.executeEdit( sequence, EditKeyframe( clipId: 'real-clip', parameterId: layer.target('center.x'), at: CommandTime(0, 1), action: KeyframeAction.clear, ), ); await session.commands.executeEdit( sequence, EditMask( clipId: 'real-clip', at: CommandTime(0, 1), action: MaskAction.set, maskId: 'real-mask', x: .5, ), ); await settled(); expect(ClipMaskStack(record(), 0).layers, hasLength(1)); }); await check('editedExportPixelsAudioAndPersistence', () async { final exportedUri = await export('edited'); result['editedExport'] = exportedUri.toFilePath(); final editedMedia = MediaReference(id: 'edited', uri: exportedUri); final editedInfo = await runtime.probe(editedMedia); expect(editedInfo.duration.seconds, closeTo(4, .1)); expect(editedInfo.audioTrackCount, 1); final thumbnail = await runtime.thumbnail( ThumbnailRequest( media: editedMedia, time: MediaTime(1, 1), maximumWidth: 320, maximumHeight: 180, ), ); final image = await decodeImageFromList(thumbnail.data); final pixels = (await image.toByteData( format: ui.ImageByteFormat.rawRgba, ))!; // The authored half-size mask must leave the canvas corners black. for (final at in [ 0, (image.width - 1) * 4, (image.height - 1) * image.width * 4, ]) { expect( pixels.getUint8(at) + pixels.getUint8(at + 1) + pixels.getUint8(at + 2), lessThan(35), ); } image.dispose(); final originalWave = await runtime.waveform( WaveformRequest( media: MediaReference(id: 'baseline', uri: baseline), baseBucketCount: 64, levelCount: 1, ), ); final editedWave = await runtime.waveform( WaveformRequest( media: editedMedia, baseBucketCount: 64, levelCount: 1, ), ); 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(0, (sum, value) => sum + value * value) / values.length, ); } final baseRms = rms(originalWave); final editedRms = rms(editedWave); if (baseRms <= 1 / 32768) { // Silent source intervals have no measurable gain ratio. expect(editedRms, lessThanOrEqualTo(1 / 32768)); result['audioObservation'] = 'baseline interval is silent; edited interval remains silent'; } else { final ratio = editedRms / baseRms; expect(ratio, closeTo(math.pow(10, -6 / 20).toDouble(), .08)); result['audioRmsRatio'] = ratio; } }); } await check('saveEditedTimeline', () 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, ); if (!longSpeedOnly) { expect( ((edits['clips'] as List).single as Map)['parameters'], hasLength(greaterThan(2)), ); } result['savedTimelineId'] = timelineId; result['savedProject'] = projectPath; }); result['passed'] = true; } catch (error, stack) { checks.add({ 'stage': stage, 'passed': false, 'error': '$error', 'stack': '$stack', }); debugPrint('REAL_MEDIA_FAILED $stage $error\n$stack'); } final after = await file.stat(); result['sourceUnchanged'] = before.size == after.size && before.modified == after.modified; 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; File( p.join(root.path, 'reopened-edits-$timelineId.json'), ).writeAsStringSync(const JsonEncoder.withIndent(' ').convert(edits)); save(); }, ); expect( results.where((file) => file['passed'] != true).toList(), isEmpty, reason: 'See ${report.path}', ); }, timeout: const Timeout(Duration(minutes: 240))); }