import 'package:cutdex/app/editor_theme.dart'; // Opt-in validation against complete, unmodified real media on Android. // Run with `flutter test --no-uninstall` to retain app data and source fixtures. import 'dart:io'; import 'dart:math' as math; 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_native/cutdex_native.dart'; import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/runtime.dart'; import 'package:cutdex_sdk/timeline/engine.dart'; import 'package:cutdex_sdk/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/android_preview_measurement.dart'; import 'support/real_media_export_checks.dart'; import 'support/real_media_report.dart'; import 'support/saved_edit_validation.dart'; 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 sampleStart = int.fromEnvironment( 'CUTDEX_VALIDATION_SAMPLE_START', defaultValue: 60, ); const previewWidth = int.fromEnvironment( 'CUTDEX_VALIDATION_PREVIEW_WIDTH', defaultValue: 640, ); const previewHeight = int.fromEnvironment( 'CUTDEX_VALIDATION_PREVIEW_HEIGHT', defaultValue: 360, ); const observationSeconds = int.fromEnvironment( 'CUTDEX_VALIDATION_OBSERVATION_SECONDS', defaultValue: 2, ); const concurrentIo = bool.fromEnvironment('CUTDEX_VALIDATION_CONCURRENT_IO'); const previewOnly = bool.fromEnvironment('CUTDEX_VALIDATION_PREVIEW_ONLY'); testWidgets( 'Android host registers native device facts and application info', (tester) async { expect(Platform.isAndroid, isTrue); await tester.pumpWidget(const SizedBox.shrink()); final device = await NativeDeviceInfo.read(); expect( device, isNotNull, reason: 'The application host must register cutdex_native.', ); expect(device!.displayShortestSideDp, greaterThan(0)); expect(device.interfaceIdiom, isNull); final application = await NativeDeviceInfo.readApplicationInfo(); expect(application['appVersion'], isNotEmpty); expect(int.tryParse(application['appBuild'] ?? ''), greaterThan(0)); }, ); testWidgets('Android real media: preview and editing through native runtime', ( tester, ) async { expect(Platform.isAndroid, isTrue); expect(source, isNotEmpty); expect(output, isNotEmpty); expect(previewWidth, greaterThan(0)); expect(previewHeight, greaterThan(0)); expect(observationSeconds, greaterThan(0)); final paths = Directory(source) .listSync() .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 = RealMediaReport( File(p.join(root.path, 'results.json')), metadata: { 'platform': 'android', 'source': source, 'previewOnly': previewOnly, 'previewSize': [previewWidth, previewHeight], 'playbackObservationSeconds': observationSeconds, 'concurrentFixtureTransfer': concurrentIo, 'frameTimingMethod': 'Native surface presentation counters in a debug integration build; ' 'not physical display refresh or speaker synchronization.', 'method': previewOnly ? 'Original files; probing, thumbnails and full-length native preview only. ' 'Editing and exports skipped. Settings database isolated in memory.' : '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.', }, ); final savedEdits = SavedEditValidation(); final results = report.files; final save = report.save; 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(); }); Future until( bool Function() ready, String label, { int seconds = 60, }) => pumpUntil(tester, ready, label, seconds: seconds); expect( await projects.open( p.join( root.path, 'Real-media-${DateTime.now().millisecondsSinceEpoch}.cutdex', ), name: 'Android 真实素材验证', initialTimelineName: '01', ), isTrue, ); final 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 checks = >[]; final result = { 'path': file.path, 'checks': checks, 'sourceStartSeconds': sampleStart, 'passed': false, }; 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) { 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 { try { info = await runtime.probe(media); } catch (_) { final raw = await runtime.invoke('probe', {'media': media.toMap()}); result['rawProbeMetadata'] = raw; // Preserve the actual wire-contract failure in the device report. MediaInfo.fromMap(raw! as Map); rethrow; } 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(); } }); await check( 'fullLengthPreviewStartMiddleAndEnd', () => measureAndroidFullLengthPreview( tester: tester, runtime: runtime, media: media, info: info, configuration: ( width: previewWidth, height: previewHeight, observationSeconds: observationSeconds, ), result: result, save: save, ), ); if (previewOnly) { final unchanged = await file.stat(); expect(unchanged.size, before.size); expect(unchanged.modified, before.modified); result['passed'] = true; result['sourceUnchanged'] = true; releaseTimeline(); save(); continue; } 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, SetProjectCanvas( width: previewWidth.toDouble(), height: previewHeight.toDouble(), ), ); await session.commands.insertMedia( sequence: sequence, assetId: asset.id, clipId: ElementId('real-clip'), index: 0, sourceStart: RationalTime.seconds(sampleStart), duration: 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: LayoutBuilder( builder: (context, constraints) { final narrow = constraints.maxWidth < 600; return Column( children: [ Expanded( child: Flex( direction: narrow ? Axis.vertical : Axis.horizontal, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: EditorPreviewPanel( projectId: projectId, timelineId: timelineId, ), ), SizedBox( width: narrow ? null : 280, height: narrow ? 200 : null, 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!; // Platform-view creation spans several Flutter frames on Android. await until( () => (preview.session?.snapshot?.presentedVideoFrameCount ?? 0) > 0, 'first preview frame', seconds: 90, ); 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() async { await seek(0); final beforePlay = await preview.session!.refresh(); await tester.tap(find.byTooltip('播放').first); 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}', ); } final reachedEnd = preview.durationTick > 0 && preview.positionTick >= preview.durationTick - TimelineClock.ticksPerSecond / 10; return (preview.playing || reachedEnd) && preview.positionTick > TimelineClock.ticksPerSecond / 2 && (native?.presentedVideoFrameCount ?? 0) > (beforePlay.presentedVideoFrameCount ?? 0); }, 'native playback clock'); await Future.delayed(const Duration(milliseconds: 250)); await tester.pump(); final playing = await preview.session!.refresh(); expect( playing.presentedVideoFrameCount, greaterThan(beforePlay.presentedVideoFrameCount ?? 0), ); final pause = find.byTooltip('暂停播放'); if (pause.evaluate().isNotEmpty) { await tester.tap(pause.first); } else { expect( preview.positionTick, greaterThanOrEqualTo( preview.durationTick - TimelineClock.ticksPerSecond / 10, ), ); } 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, }); } 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(); }); 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.index(0), inputColorSpace: info.videoColorSpaces[0] ?? RenderColorSpace.rec709, audioTrackSelection: TrackSelection.index(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('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('keyframeOnlyExport', () async { final uri = await export('keyframes'); final exported = await runtime.probe( MediaReference(id: 'keyframes', uri: uri), ); expect(exported.duration.seconds, closeTo(4, .1)); result['keyframeExport'] = uri.toFilePath(); }); 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('editedExportPixelsAudioAndPersistence', () async { final exportedUri = await export('edited'); result['editedExport'] = exportedUri.toFilePath(); result['audioRmsRatio'] = await verifyEditedExport( runtime, edited: exportedUri, baseline: baseline, ); 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(3)), ); 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; save(); }, ); expect( results.where((file) => file['passed'] != true).toList(), isEmpty, reason: 'See ${report.file.path}', ); }, timeout: const Timeout(Duration(minutes: 90))); }