feat: initial Cutdex application
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.
This commit is contained in:
commit
27e77fff39
718 files changed
+183958
No files matched your search
@@ -0,0 +1,71 @@
|
||||
import 'dart:io';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
import 'export_publication.dart';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
|
||||
/// Native session and output-file adapter. Compilation belongs to editor.
|
||||
final class RuntimeEditorExport implements RecoverableEditorExportService {
|
||||
const RuntimeEditorExport(this.runtime);
|
||||
final CutdexRuntime runtime;
|
||||
|
||||
@override
|
||||
Future<MediaInfo?> probe(MediaReference media) => runtime.probe(media);
|
||||
|
||||
@override
|
||||
Future<EditorExportCapabilities> capabilities() async {
|
||||
final features = await runtime.capabilities();
|
||||
return EditorExportCapabilities(
|
||||
imageProbe:
|
||||
features.query('media.imageProbe') ==
|
||||
CapabilityAvailability.available,
|
||||
toneMapping:
|
||||
features.query('render.toneMapping') ==
|
||||
CapabilityAvailability.available,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Uri?> recoverExport(Uri destination, String operationId) =>
|
||||
ExportPublication(destination, operationId).recover();
|
||||
|
||||
@override
|
||||
Future<Uri> exportRecoverable(
|
||||
ExecutionPlan plan,
|
||||
Uri destination,
|
||||
String operationId,
|
||||
) => ExportPublication(destination, operationId).run(
|
||||
sha256.convert(utf8.encode(jsonEncode(plan.toMap()))).toString(),
|
||||
(staging) => export(plan, staging),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Uri> export(ExecutionPlan plan, Uri destination) async {
|
||||
if (await FileSystemEntity.type(
|
||||
destination.toFilePath(),
|
||||
followLinks: false,
|
||||
) !=
|
||||
FileSystemEntityType.notFound) {
|
||||
throw const CommandRejected(
|
||||
'destinationExists',
|
||||
'Destination already exists',
|
||||
);
|
||||
}
|
||||
if (!await File.fromUri(destination).parent.exists()) {
|
||||
throw const CommandRejected(
|
||||
'invalidDestination',
|
||||
'Destination directory does not exist',
|
||||
);
|
||||
}
|
||||
final session = await runtime.createSession();
|
||||
try {
|
||||
return await session.export(plan, destination);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// A completed staging file and its digest are durable before publication.
|
||||
/// Only this operation's recorded output is eligible for recovery.
|
||||
final class ExportPublication {
|
||||
ExportPublication(this.destination, this.operationId);
|
||||
final Uri destination;
|
||||
final String operationId;
|
||||
File get output => File.fromUri(destination);
|
||||
Directory get directory => Directory(
|
||||
p.join(
|
||||
output.parent.path,
|
||||
'.cutdex-export-${sha256.convert(utf8.encode('$operationId|$destination'))}',
|
||||
),
|
||||
);
|
||||
File get staged => File(p.join(directory.path, 'output.mp4'));
|
||||
File get receipt => File(p.join(directory.path, 'receipt.json'));
|
||||
|
||||
Future<String> _digest(File file) async =>
|
||||
(await sha256.bind(file.openRead()).first).toString();
|
||||
Future<void> _save(Map<String, Object?> value) async {
|
||||
final temporary = File('${receipt.path}.tmp');
|
||||
await temporary.writeAsString(jsonEncode(value), flush: true);
|
||||
await temporary.rename(receipt.path);
|
||||
}
|
||||
|
||||
Future<Uri?> recover() async {
|
||||
if (!await receipt.exists()) return null;
|
||||
final value = (jsonDecode(await receipt.readAsString()) as Map)
|
||||
.cast<String, Object?>();
|
||||
if (value['operationId'] != operationId ||
|
||||
value['destination'] != destination.toString()) {
|
||||
throw const CommandRejected(
|
||||
'operationIdConflict',
|
||||
'Export receipt belongs to another request',
|
||||
);
|
||||
}
|
||||
if (value['sha256'] == null) return null;
|
||||
final candidate = await output.exists() ? output : staged;
|
||||
if (!await candidate.exists() ||
|
||||
await candidate.length() != value['bytes'] ||
|
||||
await _digest(candidate) != value['sha256']) {
|
||||
throw const CommandRejected(
|
||||
'exportArtifactChanged',
|
||||
'Export output is missing or changed; choose a new destination to retry',
|
||||
);
|
||||
}
|
||||
if (candidate.path == staged.path) await staged.rename(output.path);
|
||||
return destination;
|
||||
}
|
||||
|
||||
Future<Uri> run(String fingerprint, Future<Uri> Function(Uri) encode) async {
|
||||
if (await receipt.exists()) {
|
||||
final value = jsonDecode(await receipt.readAsString()) as Map;
|
||||
if (value['fingerprint'] != fingerprint) {
|
||||
throw const CommandRejected(
|
||||
'operationIdConflict',
|
||||
'Export snapshot changed',
|
||||
);
|
||||
}
|
||||
}
|
||||
final recovered = await recover();
|
||||
if (recovered != null) return recovered;
|
||||
if (await output.exists()) {
|
||||
throw const CommandRejected(
|
||||
'destinationExists',
|
||||
'Destination already exists',
|
||||
);
|
||||
}
|
||||
if (!await output.parent.exists()) {
|
||||
throw const CommandRejected(
|
||||
'invalidDestination',
|
||||
'Destination directory does not exist',
|
||||
);
|
||||
}
|
||||
if (await receipt.exists()) {
|
||||
throw const CommandRejected(
|
||||
'exportInterrupted',
|
||||
'Export was interrupted before publication; explicitly retry with a new operation',
|
||||
);
|
||||
}
|
||||
await directory.create();
|
||||
final record = <String, Object?>{
|
||||
'operationId': operationId,
|
||||
'destination': destination.toString(),
|
||||
'fingerprint': fingerprint,
|
||||
};
|
||||
await _save(record);
|
||||
await encode(staged.uri);
|
||||
final handle = await staged.open(mode: FileMode.append);
|
||||
try {
|
||||
await handle.flush();
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
await _save({
|
||||
...record,
|
||||
'bytes': await staged.length(),
|
||||
'sha256': await _digest(staged),
|
||||
});
|
||||
return (await recover())!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import 'media_thumbnails.dart';
|
||||
import 'media_waveforms.dart';
|
||||
|
||||
part 'media_presentations.g.dart';
|
||||
|
||||
@riverpod
|
||||
Future<Uint8List?> mediaCover(
|
||||
Ref ref,
|
||||
AssetDocument asset, {
|
||||
int timeMilliseconds = 0,
|
||||
}) => ref
|
||||
.watch(mediaThumbnailsProvider)
|
||||
.load(asset, timeMilliseconds: timeMilliseconds);
|
||||
|
||||
@riverpod
|
||||
Future<double?> mediaDuration(Ref ref, AssetDocument asset) =>
|
||||
ref.watch(mediaThumbnailsProvider).duration(asset);
|
||||
|
||||
@riverpod
|
||||
Future<TimelineWaveform?> mediaWaveform(Ref ref, AssetDocument asset) =>
|
||||
ref.watch(mediaWaveformsProvider).load(asset);
|
||||
@@ -0,0 +1,241 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'media_presentations.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(mediaCover)
|
||||
final mediaCoverProvider = MediaCoverFamily._();
|
||||
|
||||
final class MediaCoverProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<Uint8List?>,
|
||||
Uint8List?,
|
||||
FutureOr<Uint8List?>
|
||||
>
|
||||
with $FutureModifier<Uint8List?>, $FutureProvider<Uint8List?> {
|
||||
MediaCoverProvider._({
|
||||
required MediaCoverFamily super.from,
|
||||
required (AssetDocument, {int timeMilliseconds}) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'mediaCoverProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mediaCoverHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'mediaCoverProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<Uint8List?> $createElement($ProviderPointer pointer) =>
|
||||
$FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<Uint8List?> create(Ref ref) {
|
||||
final argument = this.argument as (AssetDocument, {int timeMilliseconds});
|
||||
return mediaCover(
|
||||
ref,
|
||||
argument.$1,
|
||||
timeMilliseconds: argument.timeMilliseconds,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is MediaCoverProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$mediaCoverHash() => r'34b3ae0fa1106a3448028e34ca2f0c64838a3d6a';
|
||||
|
||||
final class MediaCoverFamily extends $Family
|
||||
with
|
||||
$FunctionalFamilyOverride<
|
||||
FutureOr<Uint8List?>,
|
||||
(AssetDocument, {int timeMilliseconds})
|
||||
> {
|
||||
MediaCoverFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'mediaCoverProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
MediaCoverProvider call(AssetDocument asset, {int timeMilliseconds = 0}) =>
|
||||
MediaCoverProvider._(
|
||||
argument: (asset, timeMilliseconds: timeMilliseconds),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'mediaCoverProvider';
|
||||
}
|
||||
|
||||
@ProviderFor(mediaDuration)
|
||||
final mediaDurationProvider = MediaDurationFamily._();
|
||||
|
||||
final class MediaDurationProvider
|
||||
extends $FunctionalProvider<AsyncValue<double?>, double?, FutureOr<double?>>
|
||||
with $FutureModifier<double?>, $FutureProvider<double?> {
|
||||
MediaDurationProvider._({
|
||||
required MediaDurationFamily super.from,
|
||||
required AssetDocument super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'mediaDurationProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mediaDurationHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'mediaDurationProvider'
|
||||
''
|
||||
'($argument)';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<double?> $createElement($ProviderPointer pointer) =>
|
||||
$FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<double?> create(Ref ref) {
|
||||
final argument = this.argument as AssetDocument;
|
||||
return mediaDuration(ref, argument);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is MediaDurationProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$mediaDurationHash() => r'065f3604e588f088d9fe4454a77a71a4eaed57b6';
|
||||
|
||||
final class MediaDurationFamily extends $Family
|
||||
with $FunctionalFamilyOverride<FutureOr<double?>, AssetDocument> {
|
||||
MediaDurationFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'mediaDurationProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
MediaDurationProvider call(AssetDocument asset) =>
|
||||
MediaDurationProvider._(argument: asset, from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'mediaDurationProvider';
|
||||
}
|
||||
|
||||
@ProviderFor(mediaWaveform)
|
||||
final mediaWaveformProvider = MediaWaveformFamily._();
|
||||
|
||||
final class MediaWaveformProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<TimelineWaveform?>,
|
||||
TimelineWaveform?,
|
||||
FutureOr<TimelineWaveform?>
|
||||
>
|
||||
with
|
||||
$FutureModifier<TimelineWaveform?>,
|
||||
$FutureProvider<TimelineWaveform?> {
|
||||
MediaWaveformProvider._({
|
||||
required MediaWaveformFamily super.from,
|
||||
required AssetDocument super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'mediaWaveformProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mediaWaveformHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'mediaWaveformProvider'
|
||||
''
|
||||
'($argument)';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<TimelineWaveform?> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<TimelineWaveform?> create(Ref ref) {
|
||||
final argument = this.argument as AssetDocument;
|
||||
return mediaWaveform(ref, argument);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is MediaWaveformProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$mediaWaveformHash() => r'7556aade813f27763c5407b5decc65b20e5db616';
|
||||
|
||||
final class MediaWaveformFamily extends $Family
|
||||
with $FunctionalFamilyOverride<FutureOr<TimelineWaveform?>, AssetDocument> {
|
||||
MediaWaveformFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'mediaWaveformProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
MediaWaveformProvider call(AssetDocument asset) =>
|
||||
MediaWaveformProvider._(argument: asset, from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'mediaWaveformProvider';
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../workspace/media_binding.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart'
|
||||
show ProviderListenableSelect;
|
||||
part 'media_thumbnails.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
MediaThumbnails mediaThumbnails(Ref ref) {
|
||||
final projectId = ref.watch(
|
||||
projectsProvider.select((s) => s.asData?.value.activeProject?.id),
|
||||
);
|
||||
return MediaThumbnails(
|
||||
loadMedia: <T>(asset, action) => ref
|
||||
.read(projectsProvider.notifier)
|
||||
.withAssetMedia(projectId, asset, action),
|
||||
);
|
||||
}
|
||||
|
||||
/// Small runtime-generated browser covers, kept outside the project document.
|
||||
class MediaThumbnails {
|
||||
MediaThumbnails({required this.loadMedia});
|
||||
final AssetMediaLoader loadMedia;
|
||||
final _runtime = CutdexRuntime();
|
||||
final _cache = <(String, int?, int), Future<Uint8List?>>{};
|
||||
final _durations = <(String, int?), Future<double?>>{};
|
||||
Future<void> _tail = Future.value();
|
||||
|
||||
Future<double?> duration(AssetDocument asset) {
|
||||
final key = (asset.location, asset.byteLength);
|
||||
if (_durations.containsKey(key)) return _durations[key]!;
|
||||
if (_durations.length >= 64) _durations.remove(_durations.keys.first);
|
||||
return _durations[key] = () async {
|
||||
try {
|
||||
final info = await loadMedia(asset, _runtime.probe);
|
||||
final seconds = info.duration.numerator / info.duration.denominator;
|
||||
return seconds.isFinite && seconds > 0 ? seconds : null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}();
|
||||
}
|
||||
|
||||
Future<Uint8List?> load(AssetDocument asset, {int timeMilliseconds = 0}) {
|
||||
final key = (asset.location, asset.byteLength, timeMilliseconds);
|
||||
final cached = _cache.remove(key);
|
||||
if (cached != null) {
|
||||
_cache[key] = cached;
|
||||
return cached;
|
||||
}
|
||||
// Bound encoded cover retention and concurrent native generation.
|
||||
if (_cache.length >= 64) _cache.remove(_cache.keys.first);
|
||||
final future = _tail.then((_) async {
|
||||
if (asset.metadata['kind'] == 'image') {
|
||||
final image = await _imagePreview(asset);
|
||||
if (image != null) return image;
|
||||
}
|
||||
try {
|
||||
final thumbnail = await loadMedia(
|
||||
asset,
|
||||
(media) => _runtime.thumbnail(
|
||||
ThumbnailRequest(
|
||||
media: media,
|
||||
time: MediaTime(timeMilliseconds, 1000),
|
||||
),
|
||||
),
|
||||
);
|
||||
return thumbnail.data;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
_cache[key] = future;
|
||||
_tail = future.then((_) {});
|
||||
return future;
|
||||
}
|
||||
|
||||
Future<Uint8List?> _imagePreview(AssetDocument asset) async {
|
||||
if (kIsWeb) return null;
|
||||
try {
|
||||
return await loadMedia(asset, (media) async {
|
||||
if (media.uri.scheme != 'file') return null;
|
||||
final file = File.fromUri(media.uri);
|
||||
if (!file.existsSync()) return null;
|
||||
final bytes = await file.readAsBytes();
|
||||
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
|
||||
try {
|
||||
final descriptor = await ui.ImageDescriptor.encoded(buffer);
|
||||
try {
|
||||
final longestSide = descriptor.width > descriptor.height
|
||||
? descriptor.width
|
||||
: descriptor.height;
|
||||
final scale = longestSide > 320 ? 320 / longestSide : 1.0;
|
||||
final codec = await descriptor.instantiateCodec(
|
||||
targetWidth: (descriptor.width * scale).round(),
|
||||
targetHeight: (descriptor.height * scale).round(),
|
||||
);
|
||||
try {
|
||||
final frame = await codec.getNextFrame();
|
||||
try {
|
||||
return (await frame.image.toByteData(
|
||||
format: ui.ImageByteFormat.png,
|
||||
))?.buffer.asUint8List();
|
||||
} finally {
|
||||
frame.image.dispose();
|
||||
}
|
||||
} finally {
|
||||
codec.dispose();
|
||||
}
|
||||
} finally {
|
||||
descriptor.dispose();
|
||||
}
|
||||
} finally {
|
||||
buffer.dispose();
|
||||
}
|
||||
});
|
||||
} catch (_) {
|
||||
// Formats not handled by Flutter can still use the native thumbnailer.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'media_thumbnails.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(mediaThumbnails)
|
||||
final mediaThumbnailsProvider = MediaThumbnailsProvider._();
|
||||
|
||||
final class MediaThumbnailsProvider
|
||||
extends
|
||||
$FunctionalProvider<MediaThumbnails, MediaThumbnails, MediaThumbnails>
|
||||
with $Provider<MediaThumbnails> {
|
||||
MediaThumbnailsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'mediaThumbnailsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mediaThumbnailsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<MediaThumbnails> $createElement($ProviderPointer pointer) =>
|
||||
$ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
MediaThumbnails create(Ref ref) {
|
||||
return mediaThumbnails(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(MediaThumbnails value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<MediaThumbnails>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$mediaThumbnailsHash() => r'80b7a58411b734ef13efcbd01eeef5ef125d06d4';
|
||||
@@ -0,0 +1,67 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../workspace/media_binding.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart'
|
||||
show ProviderListenableSelect;
|
||||
part 'media_waveforms.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
MediaWaveforms mediaWaveforms(Ref ref) {
|
||||
final projectId = ref.watch(
|
||||
projectsProvider.select((s) => s.asData?.value.activeProject?.id),
|
||||
);
|
||||
return MediaWaveforms(
|
||||
loadMedia: <T>(asset, action) => ref
|
||||
.read(projectsProvider.notifier)
|
||||
.withAssetMedia(projectId, asset, action),
|
||||
);
|
||||
}
|
||||
|
||||
/// Browser envelopes use the same native request/cache as timeline waveforms.
|
||||
class MediaWaveforms {
|
||||
MediaWaveforms({required this.loadMedia});
|
||||
final AssetMediaLoader loadMedia;
|
||||
final _runtime = CutdexRuntime();
|
||||
final _cache = <(String, int?), Future<TimelineWaveform?>>{};
|
||||
Future<void> _tail = Future.value();
|
||||
|
||||
Future<TimelineWaveform?> load(AssetDocument asset) {
|
||||
final key = (asset.location, asset.byteLength);
|
||||
final cached = _cache.remove(key);
|
||||
if (cached != null) {
|
||||
_cache[key] = cached;
|
||||
return cached;
|
||||
}
|
||||
if (_cache.length >= 16) _cache.remove(_cache.keys.first);
|
||||
final future = _tail.then((_) async {
|
||||
try {
|
||||
final waveform = await loadMedia(
|
||||
asset,
|
||||
(media) => _runtime.waveform(WaveformRequest(media: media)),
|
||||
);
|
||||
return TimelineWaveform(
|
||||
sampleRate: waveform.sampleRate,
|
||||
sourceStartSeconds: waveform.sourceStartSeconds,
|
||||
frameCount: waveform.frameCount,
|
||||
levels: List.unmodifiable([
|
||||
for (final level in waveform.levels)
|
||||
TimelineWaveformLevel(
|
||||
samplesPerBucket: level.samplesPerBucket,
|
||||
channels: level.channels,
|
||||
),
|
||||
]),
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
_cache[key] = future;
|
||||
_tail = future.then((_) {});
|
||||
return future;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'media_waveforms.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(mediaWaveforms)
|
||||
final mediaWaveformsProvider = MediaWaveformsProvider._();
|
||||
|
||||
final class MediaWaveformsProvider
|
||||
extends $FunctionalProvider<MediaWaveforms, MediaWaveforms, MediaWaveforms>
|
||||
with $Provider<MediaWaveforms> {
|
||||
MediaWaveformsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'mediaWaveformsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mediaWaveformsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<MediaWaveforms> $createElement($ProviderPointer pointer) =>
|
||||
$ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
MediaWaveforms create(Ref ref) {
|
||||
return mediaWaveforms(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(MediaWaveforms value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<MediaWaveforms>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$mediaWaveformsHash() => r'0523a0e7fc9f29c37c23d7c17d77a167294bde54';
|
||||
@@ -0,0 +1,178 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_sdk/runtime/processing.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// App deployment configuration for non-realtime native processing.
|
||||
final class ProcessingConfiguration {
|
||||
const ProcessingConfiguration({
|
||||
required this.backend,
|
||||
this.transcriptionModel,
|
||||
this.translationModel,
|
||||
this.vocalSeparationModel,
|
||||
this.backgroundRemovalModel,
|
||||
});
|
||||
|
||||
final CutdexProcessing backend;
|
||||
final Uri? transcriptionModel;
|
||||
final Uri? translationModel;
|
||||
final Uri? vocalSeparationModel;
|
||||
final Uri? backgroundRemovalModel;
|
||||
|
||||
static String get _defaultResourcesRoot {
|
||||
if (Platform.isMacOS) {
|
||||
return p.join(
|
||||
Platform.environment['HOME'] ?? '',
|
||||
'Documents',
|
||||
'Cutdex',
|
||||
'Resources',
|
||||
);
|
||||
}
|
||||
if (Platform.isWindows) {
|
||||
return p.join(
|
||||
Platform.environment['USERPROFILE'] ?? '',
|
||||
'Documents',
|
||||
'Cutdex',
|
||||
'Resources',
|
||||
);
|
||||
}
|
||||
return p.join(
|
||||
Platform.environment['HOME'] ?? '',
|
||||
'Documents',
|
||||
'Cutdex',
|
||||
'Resources',
|
||||
);
|
||||
}
|
||||
|
||||
static String get _bundledRuntimeRoot {
|
||||
final executable = File(Platform.resolvedExecutable);
|
||||
if (Platform.isMacOS) {
|
||||
return p.normalize(
|
||||
p.join(executable.parent.path, '..', 'Resources', 'processing'),
|
||||
);
|
||||
}
|
||||
return p.join(executable.parent.path, 'processing');
|
||||
}
|
||||
|
||||
static ProcessingConfiguration? configured({
|
||||
String? resourcesRoot,
|
||||
DiagnosticSink? diagnostics,
|
||||
}) {
|
||||
const definedRoot = String.fromEnvironment('CUTDEX_PROCESSING_ROOT');
|
||||
final root = definedRoot.isNotEmpty
|
||||
? definedRoot
|
||||
: Platform.environment['CUTDEX_PROCESSING_ROOT'] ?? _bundledRuntimeRoot;
|
||||
final modelsRoot = p.join(
|
||||
resourcesRoot ?? _defaultResourcesRoot,
|
||||
'Processing',
|
||||
);
|
||||
final transcriptionPath = p.join(
|
||||
modelsRoot,
|
||||
'Transcription',
|
||||
'whisper-turbo',
|
||||
'1',
|
||||
);
|
||||
final vocalPath = p.join(
|
||||
modelsRoot,
|
||||
'VocalSeparation',
|
||||
'melband',
|
||||
'1',
|
||||
'melband.pt',
|
||||
);
|
||||
final translationPath = p.join(
|
||||
modelsRoot,
|
||||
'Translation',
|
||||
'm2m100-418m',
|
||||
'1',
|
||||
);
|
||||
final backgroundRemovalPath = p.join(
|
||||
modelsRoot,
|
||||
'BackgroundRemoval',
|
||||
'birefnet-matting',
|
||||
'1',
|
||||
'model.onnx',
|
||||
);
|
||||
return fromPaths(
|
||||
root: root,
|
||||
transcriptionPath: transcriptionPath,
|
||||
vocalPath: vocalPath,
|
||||
translationPath: translationPath,
|
||||
backgroundRemovalPath: backgroundRemovalPath,
|
||||
diagnostics: diagnostics,
|
||||
);
|
||||
}
|
||||
|
||||
/// Resolves each installed capability independently; absent files disable only that capability.
|
||||
static ProcessingConfiguration? fromPaths({
|
||||
required String root,
|
||||
required String transcriptionPath,
|
||||
required String vocalPath,
|
||||
required String translationPath,
|
||||
String? backgroundRemovalPath,
|
||||
DiagnosticSink? diagnostics,
|
||||
}) {
|
||||
if (!p.isAbsolute(root)) return null;
|
||||
final exe = Platform.isWindows ? '.exe' : '';
|
||||
final executable = p.join(root, 'bin', 'cutdex-processing-worker$exe');
|
||||
final ffmpeg = p.join(root, 'bin', 'ffmpeg$exe');
|
||||
if (!File(executable).existsSync()) {
|
||||
return null;
|
||||
}
|
||||
final asrWorker = p.join(root, 'workers', 'asr', 'cutdex-asr-worker$exe');
|
||||
final transcriptionModel =
|
||||
p.isAbsolute(transcriptionPath) &&
|
||||
File(ffmpeg).existsSync() &&
|
||||
File(asrWorker).existsSync() &&
|
||||
File(p.join(transcriptionPath, 'ggml-model.bin')).existsSync() &&
|
||||
File(p.join(transcriptionPath, 'silero_vad.onnx')).existsSync()
|
||||
? Uri.directory(transcriptionPath)
|
||||
: null;
|
||||
final audioWorker = p.join(
|
||||
root,
|
||||
'workers',
|
||||
'audio',
|
||||
'cutdex-audio-worker$exe',
|
||||
);
|
||||
final m2m100Worker = p.join(
|
||||
root,
|
||||
'workers',
|
||||
'translation',
|
||||
'cutdex-m2m100-worker$exe',
|
||||
);
|
||||
final translationModel =
|
||||
p.isAbsolute(translationPath) &&
|
||||
File(m2m100Worker).existsSync() &&
|
||||
File(p.join(translationPath, 'model.bin')).existsSync() &&
|
||||
File(p.join(translationPath, 'config.json')).existsSync() &&
|
||||
File(p.join(translationPath, 'shared_vocabulary.json'))
|
||||
.existsSync() &&
|
||||
File(p.join(translationPath, 'sentencepiece.bpe.model'))
|
||||
.existsSync()
|
||||
? Uri.directory(translationPath)
|
||||
: null;
|
||||
final vocalSeparationModel =
|
||||
p.isAbsolute(vocalPath) &&
|
||||
File(ffmpeg).existsSync() &&
|
||||
File(audioWorker).existsSync() &&
|
||||
File(vocalPath).existsSync()
|
||||
? Uri.file(vocalPath)
|
||||
: null;
|
||||
final backgroundRemovalModel =
|
||||
backgroundRemovalPath != null &&
|
||||
p.isAbsolute(backgroundRemovalPath) &&
|
||||
File(ffmpeg).existsSync() &&
|
||||
File(backgroundRemovalPath).existsSync()
|
||||
? Uri.file(backgroundRemovalPath)
|
||||
: null;
|
||||
return ProcessingConfiguration(
|
||||
backend: CutdexProcessing.fromPackage(
|
||||
Directory(root),
|
||||
diagnostics: diagnostics,
|
||||
),
|
||||
transcriptionModel: transcriptionModel,
|
||||
translationModel: translationModel,
|
||||
vocalSeparationModel: vocalSeparationModel,
|
||||
backgroundRemovalModel: backgroundRemovalModel,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,722 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../persistence/app_settings_repositories.dart';
|
||||
import '../../errors/app_failure.dart';
|
||||
import '../app_failure_adapter.dart';
|
||||
|
||||
part 'processing_resource_repository.g.dart';
|
||||
part 'processing_resource_repository.freezed.dart';
|
||||
|
||||
enum ProcessingResourceState { notInstalled, downloading, installed, failed }
|
||||
|
||||
enum ProcessingCapability {
|
||||
transcription,
|
||||
translation,
|
||||
vocalSeparation,
|
||||
backgroundRemoval,
|
||||
}
|
||||
|
||||
class ProcessingResourceCancelledException implements Exception {
|
||||
const ProcessingResourceCancelledException();
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ProcessingResourceArtifact with _$ProcessingResourceArtifact {
|
||||
const ProcessingResourceArtifact._();
|
||||
|
||||
const factory ProcessingResourceArtifact({
|
||||
required String path,
|
||||
required Uri url,
|
||||
required String sha256,
|
||||
required int bytes,
|
||||
}) = _ProcessingResourceArtifact;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ProcessingResourcePackage with _$ProcessingResourcePackage {
|
||||
const ProcessingResourcePackage._();
|
||||
|
||||
const factory ProcessingResourcePackage({
|
||||
required ProcessingCapability capability,
|
||||
required String id,
|
||||
required String version,
|
||||
required String name,
|
||||
required String description,
|
||||
required List<ProcessingResourceArtifact> artifacts,
|
||||
}) = _ProcessingResourcePackage;
|
||||
|
||||
int get bytes =>
|
||||
artifacts.fold(0, (total, artifact) => total + artifact.bytes);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ProcessingResourceInstall with _$ProcessingResourceInstall {
|
||||
const ProcessingResourceInstall._();
|
||||
|
||||
const factory ProcessingResourceInstall({
|
||||
required ProcessingResourcePackage package,
|
||||
required ProcessingResourceState state,
|
||||
@Default(0) int downloadedBytes,
|
||||
AppFailure? error,
|
||||
}) = _ProcessingResourceInstall;
|
||||
|
||||
double get progress =>
|
||||
package.bytes == 0 ? 0 : (downloadedBytes / package.bytes).clamp(0, 1);
|
||||
}
|
||||
|
||||
const _translationRevision = '18e406c615ef2991fa74d53734bf66b0a6b10cb4';
|
||||
|
||||
const _whisperRevision = '5359861c739e955e79d9a303bcbc70fb988958b1';
|
||||
|
||||
final defaultProcessingResourceCatalog = <ProcessingResourcePackage>[
|
||||
ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.transcription,
|
||||
id: 'whisper-turbo',
|
||||
version: '1',
|
||||
name: 'Whisper Large V3 Turbo',
|
||||
description: '语音识别与字幕生成',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'ggml-model.bin',
|
||||
url: Uri.parse(
|
||||
'https://huggingface.co/ggerganov/whisper.cpp/resolve/'
|
||||
'$_whisperRevision/ggml-large-v3-turbo-q5_0.bin',
|
||||
),
|
||||
sha256:
|
||||
'394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2',
|
||||
bytes: 574041195,
|
||||
),
|
||||
ProcessingResourceArtifact(
|
||||
path: 'silero_vad.onnx',
|
||||
url: Uri.parse(
|
||||
'https://github.com/k2-fsa/sherpa-onnx/releases/download/'
|
||||
'asr-models/silero_vad.onnx',
|
||||
),
|
||||
sha256:
|
||||
'9e2449e1087496d8d4caba907f23e0bd3f78d91fa552479bb9c23ac09cbb1fd6',
|
||||
bytes: 643854,
|
||||
),
|
||||
],
|
||||
),
|
||||
ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.translation,
|
||||
id: 'm2m100-418m',
|
||||
version: '1',
|
||||
name: 'M2M100 418M',
|
||||
description: '字幕翻译',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'config.json',
|
||||
url: Uri.parse(
|
||||
'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/config.json',
|
||||
),
|
||||
sha256:
|
||||
'8f6496adfc930cbfecbe8281112197705c488fab47d34b4829b06d7f478909af',
|
||||
bytes: 223,
|
||||
),
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.bin',
|
||||
url: Uri.parse(
|
||||
'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/model.bin',
|
||||
),
|
||||
sha256:
|
||||
'a1826980fc5c037e69c7ac94fcb56c03001a66f380eb71863cc0a3879e71421b',
|
||||
bytes: 490667752,
|
||||
),
|
||||
ProcessingResourceArtifact(
|
||||
path: 'sentencepiece.bpe.model',
|
||||
url: Uri.parse(
|
||||
'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/sentencepiece.bpe.model',
|
||||
),
|
||||
sha256:
|
||||
'd8f7c76ed2a5e0822be39f0a4f95a55eb19c78f4593ce609e2edbc2aea4d380a',
|
||||
bytes: 2423393,
|
||||
),
|
||||
ProcessingResourceArtifact(
|
||||
path: 'shared_vocabulary.json',
|
||||
url: Uri.parse(
|
||||
'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/shared_vocabulary.json',
|
||||
),
|
||||
sha256:
|
||||
'7eb5d0ff184c6095c7c10f9911c0aea492250abd12854f9c3d787c64b1c6397e',
|
||||
bytes: 2796509,
|
||||
),
|
||||
],
|
||||
),
|
||||
ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.backgroundRemoval,
|
||||
id: 'birefnet-matting',
|
||||
version: '1',
|
||||
name: 'BiRefNet Matting',
|
||||
description: '图片与视频背景移除',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.onnx',
|
||||
url: Uri.parse(
|
||||
'https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/'
|
||||
'BiRefNet-matting-epoch_100.onnx',
|
||||
),
|
||||
sha256:
|
||||
'6065d27c615ea27308f5b88598dd8db116eb07436c7a323ca40d13b2866c309e',
|
||||
bytes: 972667742,
|
||||
),
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
FutureOr<Raw<ProcessingResourceRepository>> processingResourceRepository(
|
||||
Ref ref,
|
||||
) async {
|
||||
final resources = await ref
|
||||
.watch(resourceLocationSettingsRepositoryProvider)
|
||||
.load();
|
||||
final resourcesRoot = resources!;
|
||||
final repository = ProcessingResourceRepository(
|
||||
root: Directory(p.join(resourcesRoot, 'Processing')),
|
||||
downloadsRoot: Directory(p.join(resourcesRoot, 'Downloads')),
|
||||
);
|
||||
await repository.load();
|
||||
ref.onDispose(repository.dispose);
|
||||
return repository;
|
||||
}
|
||||
|
||||
/// Owns optional resources required by processing capabilities.
|
||||
/// Downloads never publish a partially installed
|
||||
/// version: verified files are assembled in staging and the directory is then
|
||||
/// atomically renamed into place.
|
||||
final class ProcessingResourceRepository extends ChangeNotifier {
|
||||
ProcessingResourceRepository({
|
||||
Directory? root,
|
||||
this.downloadsRoot,
|
||||
List<ProcessingResourcePackage>? catalog,
|
||||
}) : root = root ?? Directory(_defaultRoot()),
|
||||
catalog = List.unmodifiable(catalog ?? defaultProcessingResourceCatalog);
|
||||
|
||||
final Directory root;
|
||||
final Directory? downloadsRoot;
|
||||
final List<ProcessingResourcePackage> catalog;
|
||||
final Map<String, ProcessingResourceInstall> _installs = {};
|
||||
final Set<String> _cancelled = {};
|
||||
bool _loaded = false;
|
||||
bool _disposed = false;
|
||||
bool _subtitleDownloading = false;
|
||||
bool _subtitleCancelled = false;
|
||||
bool _subtitlePaused = false;
|
||||
Set<ProcessingCapability> _subtitleAvailable = const {};
|
||||
Completer<void>? _subtitleResume;
|
||||
final Map<String, HttpClient> _downloadClients = {};
|
||||
final Map<String, _DownloadRate> _downloadRates = {};
|
||||
final Map<String, Completer<void>> _pausedDownloads = {};
|
||||
|
||||
void _changed() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_subtitleCancelled = true;
|
||||
resumeSubtitleResources();
|
||||
_cancelled.addAll(
|
||||
_installs.values
|
||||
.where(
|
||||
(install) => install.state == ProcessingResourceState.downloading,
|
||||
)
|
||||
.map((install) => install.package.id),
|
||||
);
|
||||
for (final id in _downloadClients.keys.toList()) {
|
||||
_cancelled.add(id);
|
||||
_pausedDownloads.remove(id)?.complete();
|
||||
_downloadClients[id]?.close(force: true);
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
static const subtitleCapabilities = [
|
||||
ProcessingCapability.transcription,
|
||||
ProcessingCapability.translation,
|
||||
];
|
||||
|
||||
bool get subtitlePaused => _subtitlePaused;
|
||||
bool get subtitleDownloading => _subtitleDownloading;
|
||||
int get subtitleDownloadBytesPerSecond => _subtitlePaused
|
||||
? 0
|
||||
: subtitleCapabilities.fold(
|
||||
0,
|
||||
(total, capability) => total + downloadBytesPerSecondFor(capability),
|
||||
);
|
||||
int downloadBytesPerSecondFor(ProcessingCapability capability) {
|
||||
final package = packageFor(capability);
|
||||
if (installFor(capability).state != ProcessingResourceState.downloading) {
|
||||
return 0;
|
||||
}
|
||||
return _downloadRates[package.id]?.bytesPerSecond ?? 0;
|
||||
}
|
||||
|
||||
bool downloadPausedFor(ProcessingCapability capability) =>
|
||||
_pausedDownloads.containsKey(packageFor(capability).id);
|
||||
|
||||
void pauseDownload(ProcessingCapability capability) {
|
||||
final id = packageFor(capability).id;
|
||||
if (installFor(capability).state != ProcessingResourceState.downloading ||
|
||||
_pausedDownloads.containsKey(id)) {
|
||||
return;
|
||||
}
|
||||
_pausedDownloads[id] = Completer<void>();
|
||||
_downloadRates[id]?.reset();
|
||||
_changed();
|
||||
}
|
||||
|
||||
void resumeDownload(ProcessingCapability capability) {
|
||||
final id = packageFor(capability).id;
|
||||
final gate = _pausedDownloads.remove(id);
|
||||
if (gate == null) return;
|
||||
_downloadRates[id]?.reset();
|
||||
gate.complete();
|
||||
_changed();
|
||||
}
|
||||
|
||||
Future<void> _waitForDownloadResume(String packageId) async {
|
||||
while (_pausedDownloads.containsKey(packageId)) {
|
||||
await _pausedDownloads[packageId]!.future;
|
||||
}
|
||||
if (_cancelled.contains(packageId)) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
}
|
||||
|
||||
int get subtitleTotalBytes => subtitleCapabilities.fold(
|
||||
0,
|
||||
(total, capability) => total + packageFor(capability).bytes,
|
||||
);
|
||||
int get subtitleDownloadedBytes => subtitleCapabilities.fold(0, (
|
||||
total,
|
||||
capability,
|
||||
) {
|
||||
final install = installFor(capability);
|
||||
return total +
|
||||
(_subtitleAvailable.contains(capability) ||
|
||||
install.state == ProcessingResourceState.installed
|
||||
? install.package.bytes
|
||||
: install.downloadedBytes.clamp(0, install.package.bytes).toInt());
|
||||
});
|
||||
|
||||
void pauseSubtitleResources() {
|
||||
if (!_subtitleDownloading || _subtitlePaused) return;
|
||||
_subtitlePaused = true;
|
||||
for (final capability in subtitleCapabilities) {
|
||||
_downloadRates[packageFor(capability).id]?.reset();
|
||||
}
|
||||
_subtitleResume = Completer<void>();
|
||||
_changed();
|
||||
}
|
||||
|
||||
void resumeSubtitleResources() {
|
||||
if (!_subtitlePaused) return;
|
||||
_subtitlePaused = false;
|
||||
for (final capability in subtitleCapabilities) {
|
||||
_downloadRates[packageFor(capability).id]?.reset();
|
||||
}
|
||||
_subtitleResume?.complete();
|
||||
_subtitleResume = null;
|
||||
_changed();
|
||||
}
|
||||
|
||||
Future<void> _waitForSubtitleResume(String packageId) async {
|
||||
if (!_subtitleDownloading ||
|
||||
!subtitleCapabilities.any(
|
||||
(capability) => packageFor(capability).id == packageId,
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
while (_subtitlePaused && !_subtitleCancelled) {
|
||||
await _subtitleResume!.future;
|
||||
}
|
||||
if (_subtitleCancelled) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs both subtitle resources with one byte-weighted progress value.
|
||||
/// Already configured resources participate as completed bytes.
|
||||
Future<void> ensureSubtitleResources({
|
||||
Set<ProcessingCapability> available = const {},
|
||||
required void Function(ProcessingCapability stage, double progress)
|
||||
onProgress,
|
||||
}) async {
|
||||
if (_subtitleDownloading) {
|
||||
throw StateError('Subtitle download is already in progress');
|
||||
}
|
||||
var stage = ProcessingCapability.transcription;
|
||||
final total = subtitleTotalBytes;
|
||||
_subtitleDownloading = true;
|
||||
_subtitleCancelled = false;
|
||||
_subtitlePaused = false;
|
||||
_subtitleAvailable = Set.unmodifiable(available);
|
||||
_changed();
|
||||
void report() {
|
||||
final completed = subtitleDownloadedBytes;
|
||||
var installed = true;
|
||||
for (final capability in subtitleCapabilities) {
|
||||
final install = installFor(capability);
|
||||
final ready =
|
||||
available.contains(capability) ||
|
||||
install.state == ProcessingResourceState.installed;
|
||||
installed = installed && ready;
|
||||
}
|
||||
onProgress(
|
||||
stage,
|
||||
installed
|
||||
? 1.0
|
||||
: (total == 0 ? 0.0 : completed / total)
|
||||
.clamp(0.0, 0.99)
|
||||
.toDouble(),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await load();
|
||||
addListener(report);
|
||||
for (final capability in subtitleCapabilities) {
|
||||
await _waitForSubtitleResume(packageFor(capability).id);
|
||||
if (_subtitleCancelled) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
if (available.contains(capability) ||
|
||||
installFor(capability).state == ProcessingResourceState.installed) {
|
||||
continue;
|
||||
}
|
||||
stage = capability;
|
||||
report();
|
||||
if (_subtitleCancelled) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
await ensureAvailable(capability);
|
||||
}
|
||||
if (_subtitleCancelled) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
report();
|
||||
} finally {
|
||||
removeListener(report);
|
||||
_subtitleDownloading = false;
|
||||
_subtitleAvailable = const {};
|
||||
resumeSubtitleResources();
|
||||
_changed();
|
||||
}
|
||||
}
|
||||
|
||||
void cancelSubtitleResources() {
|
||||
_subtitleCancelled = true;
|
||||
resumeSubtitleResources();
|
||||
for (final capability in subtitleCapabilities) {
|
||||
cancel(capability);
|
||||
}
|
||||
}
|
||||
|
||||
List<ProcessingResourceInstall> get installs => [
|
||||
for (final package in catalog)
|
||||
_installs[package.id] ??
|
||||
ProcessingResourceInstall(
|
||||
package: package,
|
||||
state: ProcessingResourceState.notInstalled,
|
||||
),
|
||||
];
|
||||
|
||||
static String _defaultRoot() {
|
||||
if (Platform.isMacOS) {
|
||||
return p.join(
|
||||
Platform.environment['HOME'] ?? '',
|
||||
'Library',
|
||||
'Application Support',
|
||||
'Cutdex',
|
||||
'models',
|
||||
);
|
||||
}
|
||||
if (Platform.isWindows) {
|
||||
return p.join(
|
||||
Platform.environment['LOCALAPPDATA'] ?? '',
|
||||
'Cutdex',
|
||||
'models',
|
||||
);
|
||||
}
|
||||
return p.join(
|
||||
Platform.environment['XDG_DATA_HOME'] ??
|
||||
p.join(Platform.environment['HOME'] ?? '', '.local', 'share'),
|
||||
'cutdex',
|
||||
'models',
|
||||
);
|
||||
}
|
||||
|
||||
Directory directoryFor(ProcessingResourcePackage package) => Directory(
|
||||
p.join(
|
||||
root.path,
|
||||
switch (package.capability) {
|
||||
ProcessingCapability.transcription => 'Transcription',
|
||||
ProcessingCapability.translation => 'Translation',
|
||||
ProcessingCapability.vocalSeparation => 'VocalSeparation',
|
||||
ProcessingCapability.backgroundRemoval => 'BackgroundRemoval',
|
||||
},
|
||||
package.id,
|
||||
package.version,
|
||||
),
|
||||
);
|
||||
|
||||
ProcessingResourcePackage packageFor(ProcessingCapability capability) =>
|
||||
catalog.singleWhere((item) => item.capability == capability);
|
||||
|
||||
ProcessingResourceInstall installFor(ProcessingCapability capability) {
|
||||
final package = packageFor(capability);
|
||||
return _installs[package.id] ??
|
||||
ProcessingResourceInstall(
|
||||
package: package,
|
||||
state: ProcessingResourceState.notInstalled,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> load() async {
|
||||
if (_loaded) return;
|
||||
_loaded = true;
|
||||
for (final package in catalog) {
|
||||
final installed = await _isValidInstall(package);
|
||||
_installs[package.id] = ProcessingResourceInstall(
|
||||
package: package,
|
||||
state: installed
|
||||
? ProcessingResourceState.installed
|
||||
: ProcessingResourceState.notInstalled,
|
||||
);
|
||||
}
|
||||
_changed();
|
||||
}
|
||||
|
||||
Future<Directory> ensureAvailable(ProcessingCapability capability) async {
|
||||
await load();
|
||||
final package = packageFor(capability);
|
||||
final id = package.id;
|
||||
if (_installs[id]?.state == ProcessingResourceState.installed) {
|
||||
return directoryFor(package);
|
||||
}
|
||||
if (_installs[id]?.state == ProcessingResourceState.downloading) {
|
||||
throw StateError('Resource download is already in progress');
|
||||
}
|
||||
_cancelled.remove(id);
|
||||
_set(package, ProcessingResourceState.downloading);
|
||||
final destination = directoryFor(package);
|
||||
final staging = downloadsRoot == null
|
||||
? Directory('${destination.path}.download')
|
||||
: Directory(
|
||||
p.join(downloadsRoot!.path, '${package.id}-${package.version}'),
|
||||
);
|
||||
try {
|
||||
if (await staging.exists()) await staging.delete(recursive: true);
|
||||
await staging.create(recursive: true);
|
||||
var completed = 0;
|
||||
for (final artifact in package.artifacts) {
|
||||
await _waitForSubtitleResume(id);
|
||||
if (_cancelled.contains(id)) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
final target = File(p.join(staging.path, artifact.path));
|
||||
await target.parent.create(recursive: true);
|
||||
await _download(id, artifact, target, (received) {
|
||||
_set(
|
||||
package,
|
||||
ProcessingResourceState.downloading,
|
||||
downloadedBytes: completed + received,
|
||||
);
|
||||
});
|
||||
completed += artifact.bytes;
|
||||
}
|
||||
if (_cancelled.contains(id)) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
await File(p.join(staging.path, '.installed.json')).writeAsString(
|
||||
jsonEncode({'id': package.id, 'version': package.version}),
|
||||
flush: true,
|
||||
);
|
||||
await destination.parent.create(recursive: true);
|
||||
if (await destination.exists()) await destination.delete(recursive: true);
|
||||
await staging.rename(destination.path);
|
||||
_set(
|
||||
package,
|
||||
ProcessingResourceState.installed,
|
||||
downloadedBytes: package.bytes,
|
||||
);
|
||||
return destination;
|
||||
} on ProcessingResourceCancelledException {
|
||||
if (await staging.exists()) await staging.delete(recursive: true);
|
||||
_set(package, ProcessingResourceState.notInstalled);
|
||||
throw const ProcessingResourceCancelledException();
|
||||
} catch (error) {
|
||||
if (await staging.exists()) await staging.delete(recursive: true);
|
||||
if (_cancelled.contains(id)) {
|
||||
_set(package, ProcessingResourceState.notInstalled);
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
_set(
|
||||
package,
|
||||
ProcessingResourceState.failed,
|
||||
error: appFailureFromError(error),
|
||||
);
|
||||
rethrow;
|
||||
} finally {
|
||||
_pausedDownloads.remove(id)?.complete();
|
||||
_cancelled.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
void cancel(ProcessingCapability capability) {
|
||||
final id = packageFor(capability).id;
|
||||
if (_subtitleDownloading && subtitleCapabilities.contains(capability)) {
|
||||
_subtitleCancelled = true;
|
||||
resumeSubtitleResources();
|
||||
}
|
||||
_cancelled.add(id);
|
||||
resumeDownload(capability);
|
||||
_downloadClients[id]?.close(force: true);
|
||||
}
|
||||
|
||||
Future<void> remove(ProcessingCapability capability) async {
|
||||
await load();
|
||||
final package = packageFor(capability);
|
||||
cancel(capability);
|
||||
final directory = directoryFor(package);
|
||||
if (await directory.exists()) await directory.delete(recursive: true);
|
||||
_set(package, ProcessingResourceState.notInstalled);
|
||||
}
|
||||
|
||||
Future<bool> _isValidInstall(ProcessingResourcePackage package) async {
|
||||
final directory = directoryFor(package);
|
||||
final marker = File(p.join(directory.path, '.installed.json'));
|
||||
if (!await marker.exists()) return false;
|
||||
try {
|
||||
final value = jsonDecode(await marker.readAsString());
|
||||
if (value is! Map ||
|
||||
value['id'] != package.id ||
|
||||
value['version'] != package.version) {
|
||||
return false;
|
||||
}
|
||||
return package.artifacts.every(
|
||||
(artifact) => File(p.join(directory.path, artifact.path)).existsSync(),
|
||||
);
|
||||
} on FormatException {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _download(
|
||||
String packageId,
|
||||
ProcessingResourceArtifact artifact,
|
||||
File target,
|
||||
ValueChanged<int> onProgress,
|
||||
) async {
|
||||
if (_disposed) throw const ProcessingResourceCancelledException();
|
||||
final client = HttpClient();
|
||||
_downloadClients[packageId] = client;
|
||||
final rate = _DownloadRate();
|
||||
_downloadRates[packageId] = rate;
|
||||
try {
|
||||
await _waitForSubtitleResume(packageId);
|
||||
await _waitForDownloadResume(packageId);
|
||||
final request = await client.getUrl(artifact.url);
|
||||
request.headers.set(HttpHeaders.userAgentHeader, 'Cutdex/1');
|
||||
final response = await request.close();
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw AppException(
|
||||
AppErrorCode.resourceDownloadHttpFailed,
|
||||
httpStatusCode: response.statusCode,
|
||||
diagnostic: artifact.url.toString(),
|
||||
);
|
||||
}
|
||||
final output = target.openWrite();
|
||||
final digestOutput = _DigestSink();
|
||||
final digestInput = sha256.startChunkedConversion(digestOutput);
|
||||
var received = 0;
|
||||
try {
|
||||
await for (final chunk in response) {
|
||||
await _waitForSubtitleResume(packageId);
|
||||
await _waitForDownloadResume(packageId);
|
||||
if (_cancelled.contains(packageId)) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
digestInput.add(chunk);
|
||||
output.add(chunk);
|
||||
received += chunk.length;
|
||||
rate.record(received);
|
||||
onProgress(received);
|
||||
}
|
||||
} finally {
|
||||
digestInput.close();
|
||||
await output.close();
|
||||
}
|
||||
final actual = digestOutput.value.toString();
|
||||
if (received != artifact.bytes || actual != artifact.sha256) {
|
||||
throw AppException(AppErrorCode.resourceChecksumFailed);
|
||||
}
|
||||
} finally {
|
||||
_downloadRates.remove(packageId);
|
||||
_downloadClients.remove(packageId);
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
|
||||
void _set(
|
||||
ProcessingResourcePackage package,
|
||||
ProcessingResourceState state, {
|
||||
int downloadedBytes = 0,
|
||||
AppFailure? error,
|
||||
}) {
|
||||
_installs[package.id] = ProcessingResourceInstall(
|
||||
package: package,
|
||||
state: state,
|
||||
downloadedBytes: downloadedBytes,
|
||||
error: error,
|
||||
);
|
||||
_changed();
|
||||
}
|
||||
}
|
||||
|
||||
final class _DownloadRate {
|
||||
final Stopwatch _clock = Stopwatch()..start();
|
||||
int _sampleBytes = 0;
|
||||
int _sampleMilliseconds = 0;
|
||||
int _lastBytes = 0;
|
||||
int bytesPerSecond = 0;
|
||||
|
||||
void record(int receivedBytes) {
|
||||
_lastBytes = receivedBytes;
|
||||
final now = _clock.elapsedMilliseconds;
|
||||
final elapsed = now - _sampleMilliseconds;
|
||||
if (elapsed < 500) return;
|
||||
bytesPerSecond = ((receivedBytes - _sampleBytes) * 1000 / elapsed).round();
|
||||
_sampleBytes = receivedBytes;
|
||||
_sampleMilliseconds = now;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
_sampleBytes = _lastBytes;
|
||||
_sampleMilliseconds = _clock.elapsedMilliseconds;
|
||||
bytesPerSecond = 0;
|
||||
}
|
||||
}
|
||||
|
||||
final class _DigestSink implements Sink<Digest> {
|
||||
Digest? _digest;
|
||||
Digest get value => _digest ?? (throw StateError('Missing digest'));
|
||||
|
||||
@override
|
||||
void add(Digest data) => _digest = data;
|
||||
|
||||
@override
|
||||
void close() {}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'processing_resource_repository.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(processingResourceRepository)
|
||||
final processingResourceRepositoryProvider =
|
||||
ProcessingResourceRepositoryProvider._();
|
||||
|
||||
final class ProcessingResourceRepositoryProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<Raw<ProcessingResourceRepository>>,
|
||||
Raw<ProcessingResourceRepository>,
|
||||
FutureOr<Raw<ProcessingResourceRepository>>
|
||||
>
|
||||
with
|
||||
$FutureModifier<Raw<ProcessingResourceRepository>>,
|
||||
$FutureProvider<Raw<ProcessingResourceRepository>> {
|
||||
ProcessingResourceRepositoryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'processingResourceRepositoryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$processingResourceRepositoryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<Raw<ProcessingResourceRepository>> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<Raw<ProcessingResourceRepository>> create(Ref ref) {
|
||||
return processingResourceRepository(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$processingResourceRepositoryHash() =>
|
||||
r'e96db5dd36cde4d619d1bc1236be27591d3794e1';
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import 'processing_resource_repository.dart';
|
||||
|
||||
part 'processing_resource_state.g.dart';
|
||||
part 'processing_resource_state.freezed.dart';
|
||||
|
||||
@freezed
|
||||
abstract class ProcessingResourcesSnapshot with _$ProcessingResourcesSnapshot {
|
||||
const factory ProcessingResourcesSnapshot({
|
||||
@Default([]) List<ProcessingResourceInstall> installs,
|
||||
@Default({}) Set<ProcessingCapability> paused,
|
||||
@Default({}) Map<ProcessingCapability, int> rates,
|
||||
@Default(false) bool subtitleDownloading,
|
||||
@Default(false) bool subtitlePaused,
|
||||
@Default(0) int subtitleDownloadedBytes,
|
||||
@Default(0) int subtitleTotalBytes,
|
||||
@Default(0) int subtitleBytesPerSecond,
|
||||
}) = _ProcessingResourcesSnapshot;
|
||||
}
|
||||
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
@riverpod
|
||||
class ProcessingResources extends _$ProcessingResources {
|
||||
@override
|
||||
ProcessingResourcesSnapshot build(ProcessingResourceRepository repository) {
|
||||
void changed() {
|
||||
if (ref.mounted) state = _snapshot();
|
||||
}
|
||||
|
||||
repository.addListener(changed);
|
||||
ref.onDispose(() => repository.removeListener(changed));
|
||||
return _snapshot();
|
||||
}
|
||||
|
||||
ProcessingResourcesSnapshot _snapshot() => ProcessingResourcesSnapshot(
|
||||
installs: List.of(repository.installs),
|
||||
paused: {
|
||||
for (final package in repository.catalog)
|
||||
if (repository.downloadPausedFor(package.capability))
|
||||
package.capability,
|
||||
},
|
||||
rates: {
|
||||
for (final package in repository.catalog)
|
||||
package.capability: repository.downloadBytesPerSecondFor(
|
||||
package.capability,
|
||||
),
|
||||
},
|
||||
subtitleDownloading: repository.subtitleDownloading,
|
||||
subtitlePaused: repository.subtitlePaused,
|
||||
subtitleDownloadedBytes:
|
||||
repository.catalog.any(
|
||||
(p) => p.capability == ProcessingCapability.transcription,
|
||||
) &&
|
||||
repository.catalog.any(
|
||||
(p) => p.capability == ProcessingCapability.translation,
|
||||
)
|
||||
? repository.subtitleDownloadedBytes
|
||||
: 0,
|
||||
subtitleTotalBytes: repository.catalog
|
||||
.where(
|
||||
(p) => ProcessingResourceRepository.subtitleCapabilities.contains(
|
||||
p.capability,
|
||||
),
|
||||
)
|
||||
.fold(0, (bytes, p) => bytes + p.bytes),
|
||||
subtitleBytesPerSecond:
|
||||
repository.catalog.any(
|
||||
(p) => p.capability == ProcessingCapability.transcription,
|
||||
) &&
|
||||
repository.catalog.any(
|
||||
(p) => p.capability == ProcessingCapability.translation,
|
||||
)
|
||||
? repository.subtitleDownloadBytesPerSecond
|
||||
: 0,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'processing_resource_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$ProcessingResourcesSnapshot {
|
||||
List<ProcessingResourceInstall> get installs;
|
||||
Set<ProcessingCapability> get paused;
|
||||
Map<ProcessingCapability, int> get rates;
|
||||
bool get subtitleDownloading;
|
||||
bool get subtitlePaused;
|
||||
int get subtitleDownloadedBytes;
|
||||
int get subtitleTotalBytes;
|
||||
int get subtitleBytesPerSecond;
|
||||
|
||||
/// Create a copy of ProcessingResourcesSnapshot
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$ProcessingResourcesSnapshotCopyWith<ProcessingResourcesSnapshot>
|
||||
get copyWith =>
|
||||
_$ProcessingResourcesSnapshotCopyWithImpl<ProcessingResourcesSnapshot>(
|
||||
this as ProcessingResourcesSnapshot,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as ProcessingResourcesSnapshot;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is ProcessingResourcesSnapshot &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.installs,
|
||||
_this.installs,
|
||||
) &&
|
||||
const DeepCollectionEquality().equals(other.paused, _this.paused) &&
|
||||
const DeepCollectionEquality().equals(other.rates, _this.rates) &&
|
||||
(identical(other.subtitleDownloading, _this.subtitleDownloading) ||
|
||||
other.subtitleDownloading == _this.subtitleDownloading) &&
|
||||
(identical(other.subtitlePaused, _this.subtitlePaused) ||
|
||||
other.subtitlePaused == _this.subtitlePaused) &&
|
||||
(identical(
|
||||
other.subtitleDownloadedBytes,
|
||||
_this.subtitleDownloadedBytes,
|
||||
) ||
|
||||
other.subtitleDownloadedBytes ==
|
||||
_this.subtitleDownloadedBytes) &&
|
||||
(identical(other.subtitleTotalBytes, _this.subtitleTotalBytes) ||
|
||||
other.subtitleTotalBytes == _this.subtitleTotalBytes) &&
|
||||
(identical(
|
||||
other.subtitleBytesPerSecond,
|
||||
_this.subtitleBytesPerSecond,
|
||||
) ||
|
||||
other.subtitleBytesPerSecond == _this.subtitleBytesPerSecond));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as ProcessingResourcesSnapshot;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
const DeepCollectionEquality().hash(_this.installs),
|
||||
const DeepCollectionEquality().hash(_this.paused),
|
||||
const DeepCollectionEquality().hash(_this.rates),
|
||||
_this.subtitleDownloading,
|
||||
_this.subtitlePaused,
|
||||
_this.subtitleDownloadedBytes,
|
||||
_this.subtitleTotalBytes,
|
||||
_this.subtitleBytesPerSecond,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as ProcessingResourcesSnapshot;
|
||||
return 'ProcessingResourcesSnapshot(installs: ${_this.installs}, paused: ${_this.paused}, rates: ${_this.rates}, subtitleDownloading: ${_this.subtitleDownloading}, subtitlePaused: ${_this.subtitlePaused}, subtitleDownloadedBytes: ${_this.subtitleDownloadedBytes}, subtitleTotalBytes: ${_this.subtitleTotalBytes}, subtitleBytesPerSecond: ${_this.subtitleBytesPerSecond})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $ProcessingResourcesSnapshotCopyWith<$Res> {
|
||||
factory $ProcessingResourcesSnapshotCopyWith(
|
||||
ProcessingResourcesSnapshot value,
|
||||
$Res Function(ProcessingResourcesSnapshot) _then,
|
||||
) = _$ProcessingResourcesSnapshotCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
List<ProcessingResourceInstall> installs,
|
||||
Set<ProcessingCapability> paused,
|
||||
Map<ProcessingCapability, int> rates,
|
||||
bool subtitleDownloading,
|
||||
bool subtitlePaused,
|
||||
int subtitleDownloadedBytes,
|
||||
int subtitleTotalBytes,
|
||||
int subtitleBytesPerSecond,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$ProcessingResourcesSnapshotCopyWithImpl<$Res>
|
||||
implements $ProcessingResourcesSnapshotCopyWith<$Res> {
|
||||
_$ProcessingResourcesSnapshotCopyWithImpl(this._self, this._then);
|
||||
|
||||
final ProcessingResourcesSnapshot _self;
|
||||
final $Res Function(ProcessingResourcesSnapshot) _then;
|
||||
|
||||
/// Create a copy of ProcessingResourcesSnapshot
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? installs = null,
|
||||
Object? paused = null,
|
||||
Object? rates = null,
|
||||
Object? subtitleDownloading = null,
|
||||
Object? subtitlePaused = null,
|
||||
Object? subtitleDownloadedBytes = null,
|
||||
Object? subtitleTotalBytes = null,
|
||||
Object? subtitleBytesPerSecond = null,
|
||||
}) {
|
||||
return _then(
|
||||
ProcessingResourcesSnapshot(
|
||||
installs: null == installs
|
||||
? _self.installs
|
||||
: installs // ignore: cast_nullable_to_non_nullable
|
||||
as List<ProcessingResourceInstall>,
|
||||
paused: null == paused
|
||||
? _self.paused
|
||||
: paused // ignore: cast_nullable_to_non_nullable
|
||||
as Set<ProcessingCapability>,
|
||||
rates: null == rates
|
||||
? _self.rates
|
||||
: rates // ignore: cast_nullable_to_non_nullable
|
||||
as Map<ProcessingCapability, int>,
|
||||
subtitleDownloading: null == subtitleDownloading
|
||||
? _self.subtitleDownloading
|
||||
: subtitleDownloading // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
subtitlePaused: null == subtitlePaused
|
||||
? _self.subtitlePaused
|
||||
: subtitlePaused // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
subtitleDownloadedBytes: null == subtitleDownloadedBytes
|
||||
? _self.subtitleDownloadedBytes
|
||||
: subtitleDownloadedBytes // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
subtitleTotalBytes: null == subtitleTotalBytes
|
||||
? _self.subtitleTotalBytes
|
||||
: subtitleTotalBytes // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
subtitleBytesPerSecond: null == subtitleBytesPerSecond
|
||||
? _self.subtitleBytesPerSecond
|
||||
: subtitleBytesPerSecond // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [ProcessingResourcesSnapshot].
|
||||
extension ProcessingResourcesSnapshotPatterns on ProcessingResourcesSnapshot {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_ProcessingResourcesSnapshot value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_ProcessingResourcesSnapshot value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_ProcessingResourcesSnapshot value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(
|
||||
List<ProcessingResourceInstall> installs,
|
||||
Set<ProcessingCapability> paused,
|
||||
Map<ProcessingCapability, int> rates,
|
||||
bool subtitleDownloading,
|
||||
bool subtitlePaused,
|
||||
int subtitleDownloadedBytes,
|
||||
int subtitleTotalBytes,
|
||||
int subtitleBytesPerSecond,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot() when $default != null:
|
||||
return $default(
|
||||
_that.installs,
|
||||
_that.paused,
|
||||
_that.rates,
|
||||
_that.subtitleDownloading,
|
||||
_that.subtitlePaused,
|
||||
_that.subtitleDownloadedBytes,
|
||||
_that.subtitleTotalBytes,
|
||||
_that.subtitleBytesPerSecond,
|
||||
);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(
|
||||
List<ProcessingResourceInstall> installs,
|
||||
Set<ProcessingCapability> paused,
|
||||
Map<ProcessingCapability, int> rates,
|
||||
bool subtitleDownloading,
|
||||
bool subtitlePaused,
|
||||
int subtitleDownloadedBytes,
|
||||
int subtitleTotalBytes,
|
||||
int subtitleBytesPerSecond,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot():
|
||||
return $default(
|
||||
_that.installs,
|
||||
_that.paused,
|
||||
_that.rates,
|
||||
_that.subtitleDownloading,
|
||||
_that.subtitlePaused,
|
||||
_that.subtitleDownloadedBytes,
|
||||
_that.subtitleTotalBytes,
|
||||
_that.subtitleBytesPerSecond,
|
||||
);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(
|
||||
List<ProcessingResourceInstall> installs,
|
||||
Set<ProcessingCapability> paused,
|
||||
Map<ProcessingCapability, int> rates,
|
||||
bool subtitleDownloading,
|
||||
bool subtitlePaused,
|
||||
int subtitleDownloadedBytes,
|
||||
int subtitleTotalBytes,
|
||||
int subtitleBytesPerSecond,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot() when $default != null:
|
||||
return $default(
|
||||
_that.installs,
|
||||
_that.paused,
|
||||
_that.rates,
|
||||
_that.subtitleDownloading,
|
||||
_that.subtitlePaused,
|
||||
_that.subtitleDownloadedBytes,
|
||||
_that.subtitleTotalBytes,
|
||||
_that.subtitleBytesPerSecond,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _ProcessingResourcesSnapshot implements ProcessingResourcesSnapshot {
|
||||
const _ProcessingResourcesSnapshot({
|
||||
List<ProcessingResourceInstall> installs = const [],
|
||||
Set<ProcessingCapability> paused = const {},
|
||||
Map<ProcessingCapability, int> rates = const {},
|
||||
this.subtitleDownloading = false,
|
||||
this.subtitlePaused = false,
|
||||
this.subtitleDownloadedBytes = 0,
|
||||
this.subtitleTotalBytes = 0,
|
||||
this.subtitleBytesPerSecond = 0,
|
||||
}) : _installs = installs,
|
||||
_paused = paused,
|
||||
_rates = rates;
|
||||
|
||||
final List<ProcessingResourceInstall> _installs;
|
||||
@override
|
||||
@JsonKey()
|
||||
List<ProcessingResourceInstall> get installs {
|
||||
if (_installs is EqualUnmodifiableListView) return _installs;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_installs);
|
||||
}
|
||||
|
||||
final Set<ProcessingCapability> _paused;
|
||||
@override
|
||||
@JsonKey()
|
||||
Set<ProcessingCapability> get paused {
|
||||
if (_paused is EqualUnmodifiableSetView) return _paused;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableSetView(_paused);
|
||||
}
|
||||
|
||||
final Map<ProcessingCapability, int> _rates;
|
||||
@override
|
||||
@JsonKey()
|
||||
Map<ProcessingCapability, int> get rates {
|
||||
if (_rates is EqualUnmodifiableMapView) return _rates;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableMapView(_rates);
|
||||
}
|
||||
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool subtitleDownloading;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool subtitlePaused;
|
||||
@override
|
||||
@JsonKey()
|
||||
final int subtitleDownloadedBytes;
|
||||
@override
|
||||
@JsonKey()
|
||||
final int subtitleTotalBytes;
|
||||
@override
|
||||
@JsonKey()
|
||||
final int subtitleBytesPerSecond;
|
||||
|
||||
/// Create a copy of ProcessingResourcesSnapshot
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$ProcessingResourcesSnapshotCopyWith<_ProcessingResourcesSnapshot>
|
||||
get copyWith =>
|
||||
__$ProcessingResourcesSnapshotCopyWithImpl<_ProcessingResourcesSnapshot>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _ProcessingResourcesSnapshot &&
|
||||
const DeepCollectionEquality().equals(other.installs, _installs) &&
|
||||
const DeepCollectionEquality().equals(other.paused, _paused) &&
|
||||
const DeepCollectionEquality().equals(other.rates, _rates) &&
|
||||
(identical(other.subtitleDownloading, subtitleDownloading) ||
|
||||
other.subtitleDownloading == subtitleDownloading) &&
|
||||
(identical(other.subtitlePaused, subtitlePaused) ||
|
||||
other.subtitlePaused == subtitlePaused) &&
|
||||
(identical(
|
||||
other.subtitleDownloadedBytes,
|
||||
subtitleDownloadedBytes,
|
||||
) ||
|
||||
other.subtitleDownloadedBytes == subtitleDownloadedBytes) &&
|
||||
(identical(other.subtitleTotalBytes, subtitleTotalBytes) ||
|
||||
other.subtitleTotalBytes == subtitleTotalBytes) &&
|
||||
(identical(other.subtitleBytesPerSecond, subtitleBytesPerSecond) ||
|
||||
other.subtitleBytesPerSecond == subtitleBytesPerSecond));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
const DeepCollectionEquality().hash(_installs),
|
||||
const DeepCollectionEquality().hash(_paused),
|
||||
const DeepCollectionEquality().hash(_rates),
|
||||
subtitleDownloading,
|
||||
subtitlePaused,
|
||||
subtitleDownloadedBytes,
|
||||
subtitleTotalBytes,
|
||||
subtitleBytesPerSecond,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'ProcessingResourcesSnapshot(installs: $installs, paused: $paused, rates: $rates, subtitleDownloading: $subtitleDownloading, subtitlePaused: $subtitlePaused, subtitleDownloadedBytes: $subtitleDownloadedBytes, subtitleTotalBytes: $subtitleTotalBytes, subtitleBytesPerSecond: $subtitleBytesPerSecond)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$ProcessingResourcesSnapshotCopyWith<$Res>
|
||||
implements $ProcessingResourcesSnapshotCopyWith<$Res> {
|
||||
factory _$ProcessingResourcesSnapshotCopyWith(
|
||||
_ProcessingResourcesSnapshot value,
|
||||
$Res Function(_ProcessingResourcesSnapshot) _then,
|
||||
) = __$ProcessingResourcesSnapshotCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
List<ProcessingResourceInstall> installs,
|
||||
Set<ProcessingCapability> paused,
|
||||
Map<ProcessingCapability, int> rates,
|
||||
bool subtitleDownloading,
|
||||
bool subtitlePaused,
|
||||
int subtitleDownloadedBytes,
|
||||
int subtitleTotalBytes,
|
||||
int subtitleBytesPerSecond,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$ProcessingResourcesSnapshotCopyWithImpl<$Res>
|
||||
implements _$ProcessingResourcesSnapshotCopyWith<$Res> {
|
||||
__$ProcessingResourcesSnapshotCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _ProcessingResourcesSnapshot _self;
|
||||
final $Res Function(_ProcessingResourcesSnapshot) _then;
|
||||
|
||||
/// Create a copy of ProcessingResourcesSnapshot
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? installs = null,
|
||||
Object? paused = null,
|
||||
Object? rates = null,
|
||||
Object? subtitleDownloading = null,
|
||||
Object? subtitlePaused = null,
|
||||
Object? subtitleDownloadedBytes = null,
|
||||
Object? subtitleTotalBytes = null,
|
||||
Object? subtitleBytesPerSecond = null,
|
||||
}) {
|
||||
return _then(
|
||||
_ProcessingResourcesSnapshot(
|
||||
installs: null == installs
|
||||
? _self._installs
|
||||
: installs // ignore: cast_nullable_to_non_nullable
|
||||
as List<ProcessingResourceInstall>,
|
||||
paused: null == paused
|
||||
? _self._paused
|
||||
: paused // ignore: cast_nullable_to_non_nullable
|
||||
as Set<ProcessingCapability>,
|
||||
rates: null == rates
|
||||
? _self._rates
|
||||
: rates // ignore: cast_nullable_to_non_nullable
|
||||
as Map<ProcessingCapability, int>,
|
||||
subtitleDownloading: null == subtitleDownloading
|
||||
? _self.subtitleDownloading
|
||||
: subtitleDownloading // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
subtitlePaused: null == subtitlePaused
|
||||
? _self.subtitlePaused
|
||||
: subtitlePaused // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
subtitleDownloadedBytes: null == subtitleDownloadedBytes
|
||||
? _self.subtitleDownloadedBytes
|
||||
: subtitleDownloadedBytes // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
subtitleTotalBytes: null == subtitleTotalBytes
|
||||
? _self.subtitleTotalBytes
|
||||
: subtitleTotalBytes // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
subtitleBytesPerSecond: null == subtitleBytesPerSecond
|
||||
? _self.subtitleBytesPerSecond
|
||||
: subtitleBytesPerSecond // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'processing_resource_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
|
||||
@ProviderFor(ProcessingResources)
|
||||
final processingResourcesProvider = ProcessingResourcesFamily._();
|
||||
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
final class ProcessingResourcesProvider
|
||||
extends
|
||||
$NotifierProvider<ProcessingResources, ProcessingResourcesSnapshot> {
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
ProcessingResourcesProvider._({
|
||||
required ProcessingResourcesFamily super.from,
|
||||
required ProcessingResourceRepository super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'processingResourcesProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$processingResourcesHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'processingResourcesProvider'
|
||||
''
|
||||
'($argument)';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
ProcessingResources create() => ProcessingResources();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(ProcessingResourcesSnapshot value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<ProcessingResourcesSnapshot>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is ProcessingResourcesProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$processingResourcesHash() =>
|
||||
r'd39d92ad2c74b9be524152b3e946e6f1b43de7b0';
|
||||
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
|
||||
final class ProcessingResourcesFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
ProcessingResources,
|
||||
ProcessingResourcesSnapshot,
|
||||
ProcessingResourcesSnapshot,
|
||||
ProcessingResourcesSnapshot,
|
||||
ProcessingResourceRepository
|
||||
> {
|
||||
ProcessingResourcesFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'processingResourcesProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
|
||||
ProcessingResourcesProvider call(ProcessingResourceRepository repository) =>
|
||||
ProcessingResourcesProvider._(argument: repository, from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'processingResourcesProvider';
|
||||
}
|
||||
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
|
||||
abstract class _$ProcessingResources
|
||||
extends $Notifier<ProcessingResourcesSnapshot> {
|
||||
late final _$args = ref.$arg as ProcessingResourceRepository;
|
||||
ProcessingResourceRepository get repository => _$args;
|
||||
|
||||
ProcessingResourcesSnapshot build(ProcessingResourceRepository repository);
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref =
|
||||
this.ref
|
||||
as $Ref<ProcessingResourcesSnapshot, ProcessingResourcesSnapshot>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<
|
||||
ProcessingResourcesSnapshot,
|
||||
ProcessingResourcesSnapshot
|
||||
>,
|
||||
ProcessingResourcesSnapshot,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, () => build(_$args));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart' show ClipAudioGain;
|
||||
|
||||
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 _WaveformKey = ({String id, Uri uri, TrackSelection? trackSelection});
|
||||
|
||||
/// Source-level cache shared by clips on one timeline, independent of zoom.
|
||||
class RuntimeTimelineWaveforms extends ChangeNotifier
|
||||
implements TimelineWaveforms {
|
||||
RuntimeTimelineWaveforms({
|
||||
required this.resolveMedia,
|
||||
this.resolveTrackSelection,
|
||||
this.resolveGain,
|
||||
this.gainChanges,
|
||||
CutdexRuntime? runtime,
|
||||
this.maximumEntries = 16,
|
||||
this.maximumConcurrent = 2,
|
||||
}) : _runtime = runtime ?? CutdexRuntime() {
|
||||
if (maximumEntries < 1 || maximumConcurrent < 1) {
|
||||
throw ArgumentError('Waveform limits must be positive');
|
||||
}
|
||||
gainChanges?.addListener(_gainChanged);
|
||||
}
|
||||
|
||||
final double Function(ElementRecord)? resolveGain;
|
||||
final Listenable? gainChanges;
|
||||
void _gainChanged() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
final MediaReference? Function(PayloadRef) resolveMedia;
|
||||
final TrackSelection? Function(PayloadRef)? resolveTrackSelection;
|
||||
final CutdexRuntime _runtime;
|
||||
|
||||
/// Warm-cache target. Visible sources remain pinned until they leave the view.
|
||||
final int maximumEntries;
|
||||
final int maximumConcurrent;
|
||||
final _cache = <_WaveformKey, TimelineWaveform?>{};
|
||||
final _wanted = <_WaveformKey>{};
|
||||
final _inFlight = <_WaveformKey>{};
|
||||
final _attempts = <_WaveformKey, int>{};
|
||||
final _retries = <_WaveformKey, Timer>{};
|
||||
Future<bool>? _supported;
|
||||
var _scheduled = false;
|
||||
var _disposed = false;
|
||||
|
||||
@override
|
||||
void beginFrame() => _wanted.clear();
|
||||
|
||||
@override
|
||||
bool hasAudioFor(ElementRecord element) =>
|
||||
!_disposed &&
|
||||
element.payloadRef != null &&
|
||||
resolveMedia(element.payloadRef!) != null;
|
||||
|
||||
@override
|
||||
TimelineWaveform? waveformFor(ElementRecord element) {
|
||||
if (_disposed ||
|
||||
element.payloadRef == null ||
|
||||
ClipAudioGain.isDetached(element)) {
|
||||
return null;
|
||||
}
|
||||
final media = resolveMedia(element.payloadRef!);
|
||||
if (media == null) return null;
|
||||
final key = (
|
||||
id: media.id,
|
||||
uri: media.uri,
|
||||
trackSelection: resolveTrackSelection?.call(element.payloadRef!),
|
||||
);
|
||||
_wanted.add(key);
|
||||
if (!_cache.containsKey(key)) return null;
|
||||
final value = _cache.remove(key);
|
||||
_cache[key] = value;
|
||||
if (value == null || resolveGain == null) return value;
|
||||
return TimelineWaveform(
|
||||
sampleRate: value.sampleRate,
|
||||
sourceStartSeconds: value.sourceStartSeconds,
|
||||
frameCount: value.frameCount,
|
||||
levels: value.levels,
|
||||
amplitudeScale: resolveGain!(element),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void endFrame() {
|
||||
if (_disposed || _scheduled) return;
|
||||
_scheduled = true;
|
||||
scheduleMicrotask(() {
|
||||
_scheduled = false;
|
||||
for (final key in _retries.keys.toList()) {
|
||||
if (!_wanted.contains(key)) {
|
||||
_retries.remove(key)!.cancel();
|
||||
_attempts.remove(key);
|
||||
}
|
||||
}
|
||||
_trimCache();
|
||||
_drain();
|
||||
});
|
||||
}
|
||||
|
||||
void _drain() {
|
||||
if (_disposed) return;
|
||||
for (final key in _wanted) {
|
||||
if (_inFlight.length >= maximumConcurrent) break;
|
||||
if (_cache.containsKey(key) ||
|
||||
_inFlight.contains(key) ||
|
||||
_retries.containsKey(key)) {
|
||||
continue;
|
||||
}
|
||||
_inFlight.add(key);
|
||||
unawaited(_load(key));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _load(_WaveformKey key) async {
|
||||
TimelineWaveform? value;
|
||||
final attempt = (_attempts[key] ?? 0) + 1;
|
||||
_attempts[key] = attempt;
|
||||
var retry = false;
|
||||
try {
|
||||
final supported = await (_supported ??= _checkSupport());
|
||||
if (supported && !_disposed) {
|
||||
final result = await _runtime.waveform(
|
||||
WaveformRequest(
|
||||
media: MediaReference(id: key.id, uri: key.uri),
|
||||
trackSelection:
|
||||
key.trackSelection ?? const TrackSelection.defaultTrack(),
|
||||
),
|
||||
);
|
||||
value = TimelineWaveform(
|
||||
sampleRate: result.sampleRate,
|
||||
sourceStartSeconds: result.sourceStartSeconds,
|
||||
frameCount: result.frameCount,
|
||||
levels: List.unmodifiable([
|
||||
for (final level in result.levels)
|
||||
TimelineWaveformLevel(
|
||||
samplesPerBucket: level.samplesPerBucket,
|
||||
channels: level.channels,
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
} on RuntimeException catch (error) {
|
||||
retry = error.retryable && attempt < 3;
|
||||
} catch (_) {
|
||||
// Permanent failures stay cached; malformed sources must not loop.
|
||||
} finally {
|
||||
_inFlight.remove(key);
|
||||
if (!_disposed) {
|
||||
if (retry && _wanted.contains(key)) {
|
||||
_retries[key] = Timer(Duration(seconds: 1 << (attempt - 1)), () {
|
||||
_retries.remove(key);
|
||||
_drain();
|
||||
});
|
||||
} else {
|
||||
_attempts.remove(key);
|
||||
if (!retry) _cache[key] = value;
|
||||
}
|
||||
_trimCache();
|
||||
if (value != null && _wanted.contains(key)) notifyListeners();
|
||||
_drain();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _checkSupport() async {
|
||||
try {
|
||||
final capabilities = await _runtime.capabilities();
|
||||
return capabilities.query('media.waveform') ==
|
||||
CapabilityAvailability.available;
|
||||
} catch (_) {
|
||||
_supported = null;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
void _trimCache() {
|
||||
for (final key in _cache.keys.toList()) {
|
||||
if (_cache.length <= maximumEntries) break;
|
||||
if (!_wanted.contains(key)) _cache.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
gainChanges?.removeListener(_gainChanged);
|
||||
_wanted.clear();
|
||||
_cache.clear();
|
||||
for (final timer in _retries.values) {
|
||||
timer.cancel();
|
||||
}
|
||||
_retries.clear();
|
||||
_attempts.clear();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user