Add the Flutter video editing application with project management, media import, timeline editing, preview, AI assistance, diagnostics and settings. Include shared UI and native host packages, platform runners, application tests and release tooling. Provide usage and contribution guides, the MIT license and third-party notices. Exclude local credentials, build outputs and validation data.
488 lines
15 KiB
Dart
488 lines
15 KiB
Dart
import 'dart:async';
|
|
import 'dart:math' as math;
|
|
import 'dart:ui' as ui;
|
|
|
|
import 'package:cutdex_sdk/runtime.dart';
|
|
import 'package:cutdex_sdk/timeline/engine.dart';
|
|
import 'package:cutdex_sdk/timeline/model.dart';
|
|
import 'package:cutdex_sdk/timeline_ui.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
typedef _MediaKey = ({Uri uri, TrackSelection? trackSelection, bool isImage});
|
|
typedef _FrameKey = ({
|
|
Uri uri,
|
|
TrackSelection? trackSelection,
|
|
bool isImage,
|
|
int tick,
|
|
int maximumEdge,
|
|
});
|
|
typedef _CachedFrame = ({_FrameKey key, ui.Image image});
|
|
|
|
/// One viewport's runtime requests and decoded-image cache; never project data.
|
|
/// Source URIs identify frames across provisional and imported asset IDs.
|
|
class RuntimeTimelineThumbnails extends ChangeNotifier
|
|
implements TimelineThumbnails {
|
|
RuntimeTimelineThumbnails({
|
|
required this.resolveMedia,
|
|
this.resolveTrackSelection,
|
|
CutdexRuntime? runtime,
|
|
this.maximumEntries = 256,
|
|
this.maximumDecodedBytes = 64 * 1024 * 1024,
|
|
this.maximumConcurrent = 2,
|
|
this.maximumBatchSize = 4,
|
|
}) : _runtime = runtime ?? CutdexRuntime() {
|
|
if (maximumEntries <= 0 ||
|
|
maximumDecodedBytes <= 0 ||
|
|
maximumConcurrent <= 0 ||
|
|
maximumBatchSize <= 0 ||
|
|
maximumBatchSize > 128) {
|
|
throw ArgumentError('Thumbnail limits must be positive and bounded');
|
|
}
|
|
}
|
|
|
|
static const _resolutionTiers = <int>[
|
|
64,
|
|
128,
|
|
192,
|
|
256,
|
|
384,
|
|
512,
|
|
768,
|
|
1024,
|
|
1536,
|
|
2048,
|
|
];
|
|
|
|
/// Selects the largest power-of-two source-tick interval covered by a tile.
|
|
static int samplingIntervalFor(int sourceSpanTicks) {
|
|
if (sourceSpanTicks <= 0) {
|
|
throw ArgumentError.value(sourceSpanTicks, 'sourceSpanTicks');
|
|
}
|
|
return 1 << (sourceSpanTicks.bitLength - 1);
|
|
}
|
|
|
|
/// Snaps nearby layout centers onto a cache-stable source-time grid. Bounds
|
|
/// describe the media asset, not its current edit window; an unknown upper
|
|
/// media boundary leaves the grid uncapped.
|
|
static int sampledTickFor({
|
|
required int sourceTick,
|
|
required int sourceSpanTicks,
|
|
required int minimumTick,
|
|
required int? maximumTickExclusive,
|
|
}) {
|
|
if (sourceTick < 0 ||
|
|
sourceSpanTicks <= 0 ||
|
|
minimumTick < 0 ||
|
|
(maximumTickExclusive != null && maximumTickExclusive <= minimumTick)) {
|
|
throw ArgumentError('Invalid thumbnail sampling range');
|
|
}
|
|
final interval = samplingIntervalFor(sourceSpanTicks);
|
|
final desired = maximumTickExclusive == null
|
|
? math.max(minimumTick, sourceTick)
|
|
: sourceTick.clamp(minimumTick, maximumTickExclusive - 1);
|
|
final lower = desired ~/ interval * interval;
|
|
final upper = lower + interval;
|
|
var sampled = desired - lower < upper - desired ? lower : upper;
|
|
if (sampled < minimumTick) return minimumTick;
|
|
if (maximumTickExclusive != null && sampled >= maximumTickExclusive) {
|
|
final lastGridTick = (maximumTickExclusive - 1) ~/ interval * interval;
|
|
sampled = lastGridTick >= minimumTick
|
|
? lastGridTick
|
|
: maximumTickExclusive - 1;
|
|
}
|
|
return sampled;
|
|
}
|
|
|
|
/// Quantizes painted device pixels so tiny layout changes reuse cache data.
|
|
static int maximumEdgeFor({
|
|
required ui.Size logicalSize,
|
|
required double devicePixelRatio,
|
|
}) {
|
|
if (!logicalSize.width.isFinite ||
|
|
!logicalSize.height.isFinite ||
|
|
logicalSize.width <= 0 ||
|
|
logicalSize.height <= 0 ||
|
|
!devicePixelRatio.isFinite ||
|
|
devicePixelRatio <= 0) {
|
|
throw ArgumentError(
|
|
'Thumbnail paint geometry must be finite and positive',
|
|
);
|
|
}
|
|
final requested =
|
|
(math.max(logicalSize.width, logicalSize.height) * devicePixelRatio)
|
|
.ceil();
|
|
for (final tier in _resolutionTiers) {
|
|
if (requested <= tier) return tier;
|
|
}
|
|
return _resolutionTiers.last;
|
|
}
|
|
|
|
final MediaReference? Function(PayloadRef) resolveMedia;
|
|
final TrackSelection? Function(PayloadRef)? resolveTrackSelection;
|
|
final CutdexRuntime _runtime;
|
|
final int maximumEntries;
|
|
final int maximumDecodedBytes;
|
|
final int maximumConcurrent;
|
|
final int maximumBatchSize;
|
|
final _cache = <_FrameKey, ui.Image?>{};
|
|
final _mediaFrames = <_MediaKey, Set<_FrameKey>>{};
|
|
|
|
_MediaKey _mediaKey(_FrameKey key) =>
|
|
(uri: key.uri, trackSelection: key.trackSelection, isImage: key.isImage);
|
|
final _aspectRatios = <_MediaKey, double>{};
|
|
final _wanted = <_FrameKey>{};
|
|
final _used = <_FrameKey>{};
|
|
final _inFlight = <_FrameKey>{};
|
|
var _decodedBytes = 0;
|
|
var _activeLoads = 0;
|
|
var _scheduled = false;
|
|
var _disposed = false;
|
|
|
|
@override
|
|
void beginFrame() {
|
|
_wanted.clear();
|
|
_used.clear();
|
|
}
|
|
|
|
@override
|
|
double? aspectRatioFor(ElementRecord element) {
|
|
if (_disposed || element.payloadRef == null) return null;
|
|
final media = resolveMedia(element.payloadRef!);
|
|
if (media == null) return null;
|
|
return _aspectRatios[(
|
|
uri: media.uri,
|
|
trackSelection: resolveTrackSelection?.call(element.payloadRef!),
|
|
isImage: media.isImage,
|
|
)];
|
|
}
|
|
|
|
@override
|
|
ui.Image? imageFor(
|
|
ElementRecord element,
|
|
int sourceTick, {
|
|
required int sourceSpanTicks,
|
|
required ui.Size logicalSize,
|
|
required double devicePixelRatio,
|
|
}) {
|
|
if (_disposed ||
|
|
sourceTick < 0 ||
|
|
sourceSpanTicks <= 0 ||
|
|
element.sourceStart < 0 ||
|
|
element.duration <= 0 ||
|
|
element.payloadRef == null) {
|
|
return null;
|
|
}
|
|
final media = resolveMedia(element.payloadRef!);
|
|
if (media == null) return null;
|
|
final sampledTick = media.isImage
|
|
? 0
|
|
: sampledTickFor(
|
|
sourceTick: sourceTick,
|
|
sourceSpanTicks: sourceSpanTicks,
|
|
minimumTick: math.max(0, element.mediaStart ?? 0),
|
|
maximumTickExclusive: element.mediaStart == null
|
|
? null
|
|
: element.mediaStart! + element.mediaDuration!,
|
|
);
|
|
final key = (
|
|
uri: media.uri,
|
|
trackSelection: resolveTrackSelection?.call(element.payloadRef!),
|
|
isImage: media.isImage,
|
|
tick: sampledTick,
|
|
maximumEdge: maximumEdgeFor(
|
|
logicalSize: logicalSize,
|
|
devicePixelRatio: devicePixelRatio,
|
|
),
|
|
);
|
|
final fallback =
|
|
_bestCached(key, touch: true) ??
|
|
_nearestCached(
|
|
key,
|
|
maximumTickDistance: math.max(
|
|
sourceSpanTicks,
|
|
samplingIntervalFor(sourceSpanTicks),
|
|
),
|
|
touch: true,
|
|
);
|
|
if (!_wanted.contains(key) && _wanted.length >= maximumEntries) {
|
|
if (fallback != null) _used.add(fallback.key);
|
|
return fallback?.image;
|
|
}
|
|
_wanted.add(key);
|
|
if (fallback != null) _used.add(fallback.key);
|
|
return fallback?.image;
|
|
}
|
|
|
|
@override
|
|
void endFrame() {
|
|
if (_disposed || _scheduled) return;
|
|
_scheduled = true;
|
|
scheduleMicrotask(() {
|
|
_scheduled = false;
|
|
_drain();
|
|
});
|
|
}
|
|
|
|
void _drain() {
|
|
if (_disposed) return;
|
|
while (_activeLoads < maximumConcurrent) {
|
|
_FrameKey? seed;
|
|
for (final key in _wanted) {
|
|
if (_needsLoad(key)) {
|
|
seed = key;
|
|
break;
|
|
}
|
|
}
|
|
if (seed == null) return;
|
|
final batch = <_FrameKey>[];
|
|
final mediaKey = _mediaKey(seed);
|
|
final firstForMedia =
|
|
!_mediaFrames.containsKey(mediaKey) &&
|
|
!_inFlight.any((key) => _mediaKey(key) == mediaKey);
|
|
final batchLimit = firstForMedia ? 1 : maximumBatchSize;
|
|
for (final key in _wanted) {
|
|
if (batch.length >= batchLimit) break;
|
|
if (key.uri == seed.uri &&
|
|
key.trackSelection == seed.trackSelection &&
|
|
key.isImage == seed.isImage &&
|
|
key.maximumEdge == seed.maximumEdge &&
|
|
_needsLoad(key)) {
|
|
batch.add(key);
|
|
}
|
|
}
|
|
_inFlight.addAll(batch);
|
|
_activeLoads++;
|
|
unawaited(_loadBatch(batch));
|
|
}
|
|
}
|
|
|
|
bool _needsLoad(_FrameKey key) {
|
|
if (_inFlight.contains(key) || _cache.containsKey(key)) return false;
|
|
final cached = _bestCached(key);
|
|
return cached == null || cached.key.maximumEdge < key.maximumEdge;
|
|
}
|
|
|
|
Future<void> _loadBatch(List<_FrameKey> keys) async {
|
|
final decoded = <_FrameKey, ui.Image?>{};
|
|
var aspectChanged = false;
|
|
var failed = false;
|
|
try {
|
|
final seed = keys.first;
|
|
final thumbnails = await _runtime.thumbnails(
|
|
ThumbnailBatchRequest(
|
|
media: MediaReference(
|
|
id: seed.uri.toString(),
|
|
uri: seed.uri,
|
|
isImage: seed.isImage,
|
|
),
|
|
trackSelection:
|
|
seed.trackSelection ?? const TrackSelection.defaultTrack(),
|
|
times: [
|
|
for (final key in keys)
|
|
MediaTime(key.tick, TimelineClock.ticksPerSecond),
|
|
],
|
|
maximumWidth: seed.maximumEdge,
|
|
maximumHeight: seed.maximumEdge,
|
|
tolerance: MediaTime(1, 4),
|
|
quality: 0.72,
|
|
),
|
|
);
|
|
final decodeOrder = <int>[
|
|
for (var index = 0; index < keys.length; index++)
|
|
if (_wanted.contains(keys[index])) index,
|
|
for (var index = 0; index < keys.length; index++)
|
|
if (!_wanted.contains(keys[index])) index,
|
|
];
|
|
for (final index in decodeOrder) {
|
|
final key = keys[index];
|
|
final thumbnail = thumbnails[index];
|
|
if (_disposed) break;
|
|
aspectChanged =
|
|
_rememberAspect(key, thumbnail.width, thumbnail.height) ||
|
|
aspectChanged;
|
|
try {
|
|
final codec = await ui.instantiateImageCodec(thumbnail.data);
|
|
try {
|
|
decoded[key] = (await codec.getNextFrame()).image;
|
|
} finally {
|
|
codec.dispose();
|
|
}
|
|
} catch (_) {
|
|
decoded[key] = null;
|
|
}
|
|
}
|
|
} catch (_) {
|
|
failed = true;
|
|
} finally {
|
|
_inFlight.removeAll(keys);
|
|
_activeLoads--;
|
|
if (_disposed) {
|
|
for (final image in decoded.values) {
|
|
image?.dispose();
|
|
}
|
|
} else {
|
|
var hasNewImage = false;
|
|
if (failed) {
|
|
for (final image in decoded.values) {
|
|
image?.dispose();
|
|
}
|
|
for (final key in keys) {
|
|
if (_wanted.contains(key)) _store(key, null);
|
|
}
|
|
} else {
|
|
for (final entry in decoded.entries) {
|
|
_store(entry.key, entry.value);
|
|
if (_wanted.contains(entry.key) && entry.value != null) {
|
|
hasNewImage = true;
|
|
}
|
|
}
|
|
}
|
|
if (hasNewImage || aspectChanged) notifyListeners();
|
|
_drain();
|
|
}
|
|
}
|
|
}
|
|
|
|
bool _rememberAspect(_FrameKey key, int width, int height) {
|
|
if (width <= 0 || height <= 0) return false;
|
|
final media = (
|
|
uri: key.uri,
|
|
trackSelection: key.trackSelection,
|
|
isImage: key.isImage,
|
|
);
|
|
final value = width / height;
|
|
final previous = _aspectRatios[media];
|
|
if (previous != null && (previous - value).abs() < 0.0001) return false;
|
|
_aspectRatios[media] = value;
|
|
return true;
|
|
}
|
|
|
|
_CachedFrame? _bestCached(_FrameKey desired, {bool touch = false}) {
|
|
final exact = _cache[desired];
|
|
if (exact != null) {
|
|
if (touch) _touch(desired);
|
|
return (key: desired, image: exact);
|
|
}
|
|
_CachedFrame? adequate;
|
|
_CachedFrame? fallback;
|
|
for (final key in _mediaFrames[_mediaKey(desired)] ?? const <_FrameKey>{}) {
|
|
final image = _cache[key];
|
|
if (image == null ||
|
|
key.uri != desired.uri ||
|
|
key.trackSelection != desired.trackSelection ||
|
|
key.isImage != desired.isImage ||
|
|
key.tick != desired.tick) {
|
|
continue;
|
|
}
|
|
final candidate = (key: key, image: image);
|
|
if (key.maximumEdge >= desired.maximumEdge) {
|
|
if (adequate == null || key.maximumEdge < adequate.key.maximumEdge) {
|
|
adequate = candidate;
|
|
}
|
|
} else if (fallback == null ||
|
|
key.maximumEdge > fallback.key.maximumEdge) {
|
|
fallback = candidate;
|
|
}
|
|
}
|
|
final result = adequate ?? fallback;
|
|
if (touch && result != null) _touch(result.key);
|
|
return result;
|
|
}
|
|
|
|
_CachedFrame? _nearestCached(
|
|
_FrameKey desired, {
|
|
required int maximumTickDistance,
|
|
bool touch = false,
|
|
}) {
|
|
_CachedFrame? result;
|
|
var bestDistance = maximumTickDistance + 1;
|
|
for (final key in _mediaFrames[_mediaKey(desired)] ?? const <_FrameKey>{}) {
|
|
final image = _cache[key];
|
|
if (image == null || key.uri != desired.uri) {
|
|
continue;
|
|
}
|
|
if (key.trackSelection != desired.trackSelection ||
|
|
key.isImage != desired.isImage) {
|
|
continue;
|
|
}
|
|
final distance = (key.tick - desired.tick).abs();
|
|
if (distance > maximumTickDistance || distance > bestDistance) continue;
|
|
if (distance == bestDistance &&
|
|
result != null &&
|
|
key.maximumEdge <= result.key.maximumEdge) {
|
|
continue;
|
|
}
|
|
result = (key: key, image: image);
|
|
bestDistance = distance;
|
|
}
|
|
if (touch && result != null) _touch(result.key);
|
|
return result;
|
|
}
|
|
|
|
void _store(_FrameKey key, ui.Image? image) {
|
|
if (_cache.containsKey(key)) {
|
|
final previous = _cache.remove(key);
|
|
if (previous != null) {
|
|
_decodedBytes -= _imageBytes(previous);
|
|
if (!identical(previous, image)) previous.dispose();
|
|
}
|
|
}
|
|
_cache[key] = image;
|
|
(_mediaFrames[_mediaKey(key)] ??= <_FrameKey>{}).add(key);
|
|
if (image != null) _decodedBytes += _imageBytes(image);
|
|
_trimCache();
|
|
}
|
|
|
|
void _touch(_FrameKey key) {
|
|
if (!_cache.containsKey(key)) return;
|
|
final image = _cache.remove(key);
|
|
_cache[key] = image;
|
|
}
|
|
|
|
void _trimCache() {
|
|
while ((_cache.length > maximumEntries ||
|
|
_decodedBytes > maximumDecodedBytes) &&
|
|
_cache.length > 1) {
|
|
_FrameKey? victim;
|
|
for (final key in _cache.keys) {
|
|
if (!_wanted.contains(key) &&
|
|
!_used.contains(key) &&
|
|
!_inFlight.contains(key)) {
|
|
victim = key;
|
|
break;
|
|
}
|
|
}
|
|
victim ??= _cache.keys.firstWhere(
|
|
(key) => !_inFlight.contains(key),
|
|
orElse: () => _cache.keys.first,
|
|
);
|
|
final image = _cache.remove(victim);
|
|
final media = _mediaKey(victim);
|
|
final frames = _mediaFrames[media]!;
|
|
frames.remove(victim);
|
|
if (frames.isEmpty) _mediaFrames.remove(media);
|
|
if (image != null) {
|
|
_decodedBytes -= _imageBytes(image);
|
|
image.dispose();
|
|
}
|
|
}
|
|
}
|
|
|
|
int _imageBytes(ui.Image image) => image.width * image.height * 4;
|
|
|
|
@override
|
|
void dispose() {
|
|
_disposed = true;
|
|
_wanted.clear();
|
|
_used.clear();
|
|
_aspectRatios.clear();
|
|
for (final image in _cache.values) {
|
|
image?.dispose();
|
|
}
|
|
_cache.clear();
|
|
_mediaFrames.clear();
|
|
_decodedBytes = 0;
|
|
super.dispose();
|
|
}
|
|
}
|