Files
cutdex/lib/workspace/persistence/project_workspace.dart
T
lingjhf 38ca180cf7
Gitea CI / Check code and tests (pull_request) Failing after 8s
Gitea CI / Build Android APK (pull_request) Skipped
Gitea CI / Build Windows x64 app (pull_request) Skipped
Gitea CI / Audit and package Windows x64 (pull_request) Skipped
Gitea CI / Assemble and validate CI artifacts (pull_request) Skipped
Gitea CI / Gitea CI passed (pull_request) Failing after 1s
refactor(core): own editor UI and pin verified native releases
2026-10-12 03:20:29 +08:00

1075 lines
35 KiB
Dart

import 'package:cutdex/errors/app_failure.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import '../../diagnostics/app_diagnostics.dart';
import 'timeline_creation_names.dart';
import 'package:cutdex_core/project.dart';
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:path/path.dart' as p;
import 'package:uuid/uuid.dart';
import 'package:cutdex_core/editor.dart';
import '../project_assets_changed.dart';
import '../project_state.dart';
import '../media_file_extensions.dart';
import '../media_import.dart';
import '../prepared_media_metadata.dart';
import '../timeline_session.dart';
import '../background_task_registry.dart';
import '../../integrations/runtime/editor_export.dart';
import '../../integrations/runtime/processing_configuration.dart';
import '../../integrations/platform/media_source_reader.dart';
class ProjectOpenSuperseded implements Exception {}
class WorkspaceTimelineLease {
const WorkspaceTimelineLease(this.session, this.release, this.validate);
final EditorTimelineSession session;
final Future<void> Function() release;
final Future<void> Function() validate;
}
typedef CreatedTimeline = ({
List<TimelineSummary> timelines,
TimelineDocument document,
EditorTimelineSession session,
});
/// Owns the active file and serializes operations, including close.
class ProjectWorkspace {
ProjectWorkspace({
required this._creationNames,
CutdexRuntime? runtime,
ProcessingConfiguration? processing,
BackgroundTaskRegistry? backgroundTasks,
this.mediaSourceReader = const MediaSourceReader(),
}) : _runtime = runtime ?? CutdexRuntime(diagnostics: AppDiagnostics.report),
_processingOverride = processing,
backgroundTasks = backgroundTasks ?? BackgroundTaskRegistry(),
_ownsBackgroundTasks = backgroundTasks == null;
final _assetChanges = StreamController<ProjectAssetsChanged>.broadcast();
Stream<ProjectAssetsChanged> get assetChanges => _assetChanges.stream;
final TimelineCreationNames _creationNames;
final CutdexRuntime _runtime;
final MediaSourceReader mediaSourceReader;
final ProcessingConfiguration? _processingOverride;
final BackgroundTaskRegistry backgroundTasks;
final bool _ownsBackgroundTasks;
ProcessingConfiguration? get _processing =>
_processingOverride ??
ProcessingConfiguration.configured(diagnostics: AppDiagnostics.report);
ProjectFile? _project;
final _documents = <String, TimelineDocument>{};
final _documentVersions = <String, String>{};
final _sessions = <String, EditorTimelineSession>{};
final _retainedProjects = <ProjectFile>{};
final _warmProjects = <ProjectFile>[];
Set<String> get cachedProjectIds => {
if (_project != null) _project!.info.id,
for (final file in _warmProjects) file.info.id,
};
final _retainedTimelines = <EditorTimelineSession, ProjectFile>{};
final _timelineLeases = <EditorTimelineSession, int>{};
Future<void> _tail = Future.value();
bool _closed = false;
Future<void>? _closing;
static const _uuid = Uuid();
ProjectFile? get project => _project;
EditorTimelineSession? cachedTimelineSession(
String projectId,
String timelineId,
) {
if (_project?.info.id != projectId) return null;
final session = _sessions[timelineId];
return session?.acceptsEdits == true ? session : null;
}
TimelineDocument? cachedTimelineDocument(
String projectId,
String timelineId,
) => _project?.info.id == projectId ? _documents[timelineId] : null;
ProjectFile? _fileFor(String projectId) {
final active = _project;
if (active?.info.id == projectId) return active;
for (final file in _retainedProjects) {
if (file.info.id == projectId) return file;
}
return null;
}
Future<void> _retireProject() async {
final file = _project;
if (file == null) return;
for (final timeline in _sessions.values) {
await timeline.flush();
}
for (final timeline in _sessions.values) {
_retainedTimelines[timeline] = file;
}
_retainedProjects.add(file);
_warmProjects.remove(file);
_warmProjects.add(file);
_sessions.clear();
_documents.clear();
_documentVersions.clear();
_project = null;
}
Future<void> deactivateProject() => _run(() async {
await _retireProject();
await _trimWarmProjects();
});
Future<void> _trimWarmProjects() async {
while (_warmProjects.length > 2) {
final file = _warmProjects.removeAt(0);
final sessions = _retainedTimelines.entries
.where((entry) => entry.value == file)
.map((entry) => entry.key)
.toList();
for (final session in sessions) {
final hasTasks =
session.subtitleWorkflows.tasks.isNotEmpty ||
(session.transcriptions?.tasks.isNotEmpty ?? false) ||
session.backgroundRemovals.tasks.isNotEmpty;
if ((_timelineLeases[session] ?? 0) > 0 || hasTasks) continue;
await session.flush();
backgroundTasks.unregister(session);
await session.close();
_retainedTimelines.remove(session);
}
if (!_retainedTimelines.containsValue(file)) {
_retainedProjects.remove(file);
await file.close();
}
}
}
Future<WorkspaceTimelineLease> leaseTimeline(
String projectId,
String timelineId,
) => _run(() async {
final session = _sessions[timelineId];
if (_project?.info.id != projectId || session == null) {
throw AppException(AppErrorCode.openTimelineFailed);
}
_timelineLeases[session] = (_timelineLeases[session] ?? 0) + 1;
final file = _project!;
var released = false;
Future<void> validate() async {
if (!session.acceptsEdits) {
throw AppException(AppErrorCode.timelineSessionClosed);
}
final manifest = File(p.join(file.directory.path, 'manifest.json'));
final value = jsonDecode(await manifest.readAsString());
if (value is! Map || value['projectId'] != projectId) {
throw AppException(AppErrorCode.projectMismatch);
}
}
return WorkspaceTimelineLease(
session,
() => _run(() async {
if (released) return;
released = true;
final remaining = (_timelineLeases[session] ?? 1) - 1;
if (remaining > 0) {
_timelineLeases[session] = remaining;
return;
}
_timelineLeases.remove(session);
final retainedFile = _retainedTimelines[session];
if (retainedFile == null || _warmProjects.contains(retainedFile)) {
return;
}
final file = _retainedTimelines.remove(session)!;
backgroundTasks.unregister(session);
await session.close();
if (file != _project && !_retainedTimelines.containsValue(file)) {
_retainedProjects.remove(file);
await file.close();
}
}),
validate,
);
});
bool get hasBackgroundTasks =>
{..._sessions.values, ..._retainedTimelines.keys}.any(
(timeline) =>
timeline.subtitleWorkflows.runningCount > 0 ||
(timeline.transcriptions?.translationTasks.any(
(task) => !task.terminal,
) ??
false) ||
(timeline.vocalSeparations?.tasks.any((task) => !task.terminal) ??
false),
);
Future<T> _run<T>(Future<T> Function() action) {
if (_closed) {
return Future.error(AppException(AppErrorCode.projectSessionClosed));
}
final result = _tail.then((_) => action());
_tail = result.then<void>((_) {}, onError: (Object _, StackTrace _) {});
return result;
}
Future<List<TimelineSummary>> open(
String path, {
String? name,
String? expectedId,
TimelineCreationNames? creationNames,
bool Function()? isCurrent,
}) => _run(() async {
void checkCurrent() {
if (isCurrent?.call() == false) throw ProjectOpenSuperseded();
}
checkCurrent();
final directory = Directory(path);
ProjectFile? candidate;
var installed = false;
try {
if (_project != null &&
name == null &&
await directory.resolveSymbolicLinks() == _project!.directory.path) {
if (expectedId != null && expectedId != _project!.info.id) {
throw AppException(AppErrorCode.projectMismatch);
}
return await _project!.listTimelines();
}
final canonicalPath = name == null
? await directory.resolveSymbolicLinks()
: null;
final retained = name == null
? _retainedProjects
.where((file) => file.directory.path == canonicalPath)
.firstOrNull
: null;
candidate =
retained ??
(name == null
? await ProjectFile.open(directory)
: await _createProjectFile(
directory,
name: name,
initialTimeline: _newTimelineDocument(
(creationNames ?? _creationNames).timeline,
creationNames ?? _creationNames,
),
));
if (expectedId != null && candidate.info.id != expectedId) {
throw AppException(AppErrorCode.projectMismatch);
}
var timelines = await candidate.listTimelines();
if (timelines.isEmpty) {
final initial = _newTimelineDocument(
(creationNames ?? _creationNames).timeline,
creationNames ?? _creationNames,
);
await candidate.saveTimeline(initial);
await candidate.setTimelinePinned(initial.id, true);
timelines = await candidate.listTimelines();
}
checkCurrent();
final documents = <String, TimelineDocument>{};
for (final timeline in timelines) {
checkCurrent();
documents[timeline.id] = await candidate.loadTimeline(timeline.id);
}
checkCurrent();
// Saving the previous project is deliberately not cancellable.
await _retireProject();
_retainedProjects.remove(candidate);
_warmProjects.remove(candidate);
_project = candidate;
_documents.addAll(documents);
installed = true;
await _trimWarmProjects();
return timelines;
} finally {
if (!installed) {
if (candidate != null && !_retainedProjects.contains(candidate)) {
await candidate.close();
}
}
}
});
Future<ProjectFile> _createProjectFile(
Directory directory, {
required String name,
required TimelineDocument initialTimeline,
}) async {
try {
return await ProjectFile.create(
directory,
name: name,
initialTimeline: initialTimeline,
);
} on ProjectFileException catch (error) {
if (error.code != ProjectFileError.conflict) rethrow;
throw AppException(
AppErrorCode.projectAlreadyExists,
diagnostic: error.toString(),
);
}
}
/// Reads timelines from any project without installing it as the active one.
///
/// This intentionally shares the workspace queue with [open] and all active
/// project operations. A restored expansion and a restored active project
/// can otherwise try to open the same SQLite files at the same time.
Future<List<TimelineSummary>> listProjectTimelines(
String path, {
required String expectedId,
}) => _run(() async {
final available = _fileFor(expectedId);
if (available != null) {
return available.listTimelines();
}
final candidate = await ProjectFile.open(Directory(path));
try {
if (candidate.info.id != expectedId) {
throw AppException(AppErrorCode.projectMismatch);
}
return await candidate.listTimelines();
} finally {
await candidate.close();
}
});
Future<void> renameProject(RecentProject project, String name) =>
_withProject(project, (file) => file.rename(name));
Future<void> renameTimeline(
RecentProject project,
String timelineId,
String name,
) => _withProject(project, (file) async {
await file.renameTimeline(timelineId, name);
if (file != _project) return;
final document = _documents[timelineId];
if (document == null) return;
_documents[timelineId] = TimelineDocument(
id: document.id,
name: name,
sequences: document.sequences,
defaultSequenceId: document.defaultSequenceId,
payloads: document.payloads,
settings: document.settings,
revision: document.revision,
);
});
Future<List<TimelineSummary>> setTimelinePinned(
RecentProject project,
String timelineId,
bool pinned,
) => _withProject(project, (file) async {
await file.setTimelinePinned(timelineId, pinned);
return file.listTimelines();
});
Future<List<TimelineSummary>> deleteTimeline(
RecentProject project,
String timelineId,
) => _withProject(project, (file) async {
final session = file == _project ? _sessions[timelineId] : null;
if (session != null) {
if ((_timelineLeases[session] ?? 0) > 0) {
throw AppException(AppErrorCode.timelineInUse);
}
if (session.subtitleWorkflows.runningCount > 0 ||
session.backgroundRemovals.runningCount > 0 ||
(session.vocalSeparations?.tasks.any((task) => !task.terminal) ??
false)) {
throw AppException(AppErrorCode.timelineHasBackgroundTasks);
}
await session.flush();
}
final summaries = await file.listTimelines();
final target = summaries.where((item) => item.id == timelineId).firstOrNull;
if (target == null) throw AppException(AppErrorCode.timelineMissing);
await file.deleteTimeline(timelineId, expectedRevision: target.revision);
if (session != null) {
backgroundTasks.unregister(session);
await session.close();
}
if (file == _project) {
_sessions.remove(timelineId);
_documents.remove(timelineId);
_documentVersions.remove(timelineId);
}
return file.listTimelines();
});
Future<T> _withProject<T>(
RecentProject project,
Future<T> Function(ProjectFile file) action,
) => _run(() async {
final available = _fileFor(project.id);
if (available != null) return action(available);
final candidate = await ProjectFile.open(Directory(project.path));
try {
if (candidate.info.id != project.id) {
throw AppException(AppErrorCode.projectMismatch);
}
return await action(candidate);
} finally {
await candidate.close();
}
});
Future<List<TimelineSummary>> createTimeline(
String name, {
TimelineCreationNames? creationNames,
}) => _run(() async {
await _createTimelineDocument(name, creationNames ?? _creationNames);
return _project!.listTimelines();
});
Future<CreatedTimeline> createPreparedTimeline(
String name, {
TimelineCreationNames? creationNames,
}) => _run(() async {
final saved = await _createTimelineDocument(
name,
creationNames ?? _creationNames,
);
final project = _project!;
final session = await _openTimelineSession(project.info.id, saved);
return (
timelines: await project.listTimelines(),
document: saved,
session: session,
);
});
Future<TimelineDocument> _createTimelineDocument(
String name,
TimelineCreationNames creationNames,
) async {
final project = _project;
if (project == null) throw AppException(AppErrorCode.openProjectFirst);
final document = _newTimelineDocument(name, creationNames);
await project.saveTimeline(document);
final saved = await project.loadTimeline(document.id);
_documents[document.id] = saved;
return saved;
}
TimelineDocument _newTimelineDocument(
String name,
TimelineCreationNames creationNames,
) {
final sequence = TimelineDto(
id: SequenceId(_uuid.v4()),
name: creationNames.sequence,
format: TimelineFormat(frameDuration: RationalTime(1, 30)),
primaryStorylineId: StorylineId('primary'),
storylines: [
StorylineDto(
id: StorylineId('primary'),
elementIds: [],
name: creationNames.storyline,
),
],
elements: [],
);
return TimelineDocument(
id: _uuid.v4(),
name: name,
sequences: [sequence],
defaultSequenceId: sequence.id,
);
}
Future<TimelineDocument> loadTimeline(String projectId, String timelineId) =>
_run(() async {
if (_project?.info.id != projectId) {
throw AppException(AppErrorCode.openMatchingProject);
}
for (final session in _retainedTimelines.keys) {
if (session.document.id == timelineId &&
_retainedTimelines[session] == _project) {
return _documents[timelineId] ?? session.document;
}
}
final session = _sessions[timelineId];
if (session != null &&
_documentVersions[timelineId] != session.version) {
await session.flush();
_documents[timelineId] = await _project!.loadTimeline(timelineId);
_documentVersions[timelineId] = session.version;
}
final document =
_documents[timelineId] ?? await _project!.loadTimeline(timelineId);
_documents[timelineId] = document;
return document;
});
Future<List<AssetDocument>> listAssets(String projectId) => _run(() async {
final project = _fileFor(projectId);
if (project == null) throw AppException(AppErrorCode.openMatchingProject);
return _visibleAssets(await project.listAssets());
});
static const _hiddenAssetKey = 'cutdex.catalogHidden';
static List<AssetDocument> _visibleAssets(List<AssetDocument> assets) => [
for (final asset in assets)
if (asset.metadata[_hiddenAssetKey] != true) asset,
];
static AssetDocument _catalogAsset(
AssetDocument asset, {
String? name,
bool? hidden,
}) => AssetDocument(
id: asset.id,
name: name ?? asset.name,
storage: asset.storage,
location: asset.location,
byteLength: asset.byteLength,
contentHash: asset.contentHash,
metadata: {
for (final entry in asset.metadata.entries)
if (entry.key != _hiddenAssetKey || hidden == null)
entry.key: entry.value,
if (hidden == true) _hiddenAssetKey: true,
},
accessData: asset.accessData,
);
Future<List<AssetDocument>> editAsset(
String projectId,
String assetId, {
String? name,
}) => _run(
() async => (await _editCatalog(projectId, assetId, name: name)).assets,
);
Future<bool> editCatalog(String projectId, String assetId, {String? name}) =>
_run(
() async =>
(await _editCatalog(projectId, assetId, name: name)).changed,
);
Future<({List<AssetDocument> assets, bool changed})> _editCatalog(
String projectId,
String assetId, {
String? name,
}) async {
final project = _fileFor(projectId);
if (project == null) {
throw const CommandRejected('closed', 'Media project has changed');
}
final all = await project.listAssets();
final asset = all.where((a) => a.id == assetId).firstOrNull;
if (asset == null) {
throw const CommandRejected('missingMedia', 'Media does not exist');
}
if (name != null && name.trim().isEmpty) {
throw const CommandRejected('invalidArguments', 'Name is empty');
}
final changed = name == null
? asset.metadata[_hiddenAssetKey] != true
: asset.name != name.trim();
if (changed) {
await project.saveAsset(
name == null
? _catalogAsset(asset, hidden: true)
: _catalogAsset(asset, name: name.trim()),
);
}
final visible = _visibleAssets(await project.listAssets());
if (changed) _assetChanges.add(ProjectAssetsChanged(projectId, visible));
return (assets: visible, changed: changed);
}
Future<T> withAssetMedia<T>(
String projectId,
AssetDocument asset,
Future<T> Function(MediaReference media) action,
) async {
final media = await _run(() async {
final project = _fileFor(projectId);
if (project == null) {
throw AppException(AppErrorCode.projectSwitched);
}
final uri = await project.resolveAsset(asset);
return MediaReference(
id: asset.id,
uri: uri,
isImage: asset.metadata['kind'] == 'image',
);
});
return action(media);
}
/// Registers local references and imports provider documents into the project.
Future<MediaImportResult> importExternalMedia(
String projectId,
Iterable<ExternalMediaFile> files, {
bool Function()? isCancelled,
}) {
final batch = files.toList(growable: false);
return _run(() async {
final project = _fileFor(projectId);
if (project == null) {
throw AppException(AppErrorCode.openMatchingProject);
}
final assets = await project.listAssets();
final locations = {
for (final asset in assets)
if (asset.metadata[_hiddenAssetKey] != true)
?mediaSourceLocation(asset),
};
final hiddenByLocation = {
for (final asset in assets)
if (asset.metadata[_hiddenAssetKey] == true)
?mediaSourceLocation(asset): asset,
};
final failures = <MediaImportFailure>[];
var added = 0;
var duplicates = 0;
for (final source in batch) {
try {
if (source case ContentMediaFile()) {
final location = source.sourceUri.toString();
if (locations.contains(location)) {
duplicates++;
continue;
}
final hidden = hiddenByLocation[location];
if (hidden != null) {
if (isCancelled?.call() == true) {
throw AppException(AppErrorCode.mediaImportCancelled);
}
await project.saveAsset(_catalogAsset(hidden, hidden: false));
} else {
await _importProviderMedia(project, source, isCancelled);
}
locations.add(location);
added++;
continue;
}
final sourcePath = source.localPath!;
if (!p.isAbsolute(sourcePath)) {
throw AppException(AppErrorCode.localFilesOnly);
}
// The native runtime verifies the selected file's actual media tracks.
final kind = mediaKindForPath(sourcePath);
if (kind == null) {
throw AppException(AppErrorCode.unsupportedMediaType);
}
final file = File(await File(sourcePath).resolveSymbolicLinks());
final stat = await file.stat();
if (stat.type != FileSystemEntityType.file) {
throw AppException(AppErrorCode.foldersUnsupported);
}
// Check read access without reading the file into memory.
final handle = await file.open();
await handle.close();
final location = file.uri.toString();
if (locations.contains(location)) {
duplicates++;
continue;
}
if (p.extension(file.path).toLowerCase() == '.iso') {
final metadata = PreparedMediaMetadata.fromInfo(
await _runtime.probe(MediaReference(id: location, uri: file.uri)),
);
if (metadata.kind != EditorMediaKind.video) {
throw AppException(AppErrorCode.mediaNoVideoTracks);
}
}
final hidden = hiddenByLocation[location];
if (hidden != null) {
if (isCancelled?.call() == true) {
throw AppException(AppErrorCode.mediaImportCancelled);
}
await project.saveAsset(_catalogAsset(hidden, hidden: false));
locations.add(location);
added++;
continue;
}
final asset = AssetDocument(
id: _uuid.v4(),
name: source.displayName,
storage: AssetStorage.external,
location: location,
byteLength: stat.size,
metadata: {'kind': kind},
);
if (isCancelled?.call() == true) {
throw AppException(AppErrorCode.mediaImportCancelled);
}
await project.saveAsset(asset);
locations.add(location);
added++;
} catch (error) {
failures.add(
MediaImportFailure(
name: source.displayName,
failure: switch (error) {
AppException(:final failure) => failure,
FileSystemException() => AppFailure(
AppErrorCode.fileAccessFailed,
diagnostic: error.toString(),
),
_ => AppFailure(
AppErrorCode.registerMediaFailed,
diagnostic: error.toString(),
),
},
),
);
}
}
final visible = _visibleAssets(await project.listAssets());
_assetChanges.add(ProjectAssetsChanged(projectId, visible));
return MediaImportResult(
assets: visible,
added: added,
duplicates: duplicates,
failures: failures,
);
});
}
Future<void> _importProviderMedia(
ProjectFile project,
ContentMediaFile source,
bool Function()? isCancelled,
) async {
final kind = mediaKindForPath(source.name);
if (source.uri.scheme != 'content' || source.uri.host.isEmpty) {
throw AppException(
AppErrorCode.fileAccessFailed,
diagnostic: 'Invalid provider URI',
);
}
if (kind == null) throw AppException(AppErrorCode.unsupportedMediaType);
if (isCancelled?.call() == true) {
throw AppException(AppErrorCode.mediaImportCancelled);
}
final staging = await Directory.systemTemp.createTemp(
'cutdex-media-import-',
);
try {
final file = File(
p.join(staging.path, 'source${p.extension(source.name)}'),
);
final handle = await file.open(mode: FileMode.write);
var bytes = 0;
try {
await for (final chunk in mediaSourceReader.openRead(source.uri)) {
if (isCancelled?.call() == true) {
throw AppException(AppErrorCode.mediaImportCancelled);
}
await handle.writeFrom(chunk);
bytes += chunk.length;
}
await handle.flush();
} finally {
await handle.close();
}
if (source.byteLength != null && source.byteLength != bytes) {
throw AppException(
AppErrorCode.mediaReadFailed,
diagnostic: 'Expected ${source.byteLength} bytes, received $bytes',
);
}
if (isCancelled?.call() == true) {
throw AppException(AppErrorCode.mediaImportCancelled);
}
await project.importFile(
file,
name: source.name,
metadata: {'kind': kind, mediaSourceUriKey: source.uri.toString()},
);
} finally {
await staging.delete(recursive: true);
}
}
Future<EditorTimelineSession> openTimelineSession(
String projectId,
TimelineDocument document,
) => _run(() => _openTimelineSession(projectId, document));
Future<EditorTimelineSession> _openTimelineSession(
String projectId,
TimelineDocument document,
) async {
if (_project?.info.id != projectId) {
throw AppException(AppErrorCode.openMatchingProject);
}
final existing = _sessions[document.id];
if (existing != null) return existing;
for (final session in _retainedTimelines.keys.toList()) {
if (session.document.id == document.id &&
_retainedTimelines[session] == _project) {
_retainedTimelines.remove(session);
_sessions[document.id] = session;
_documentVersions[document.id] = session.version;
return session;
}
}
final persistence = await _project!.openTimelineSaveSession(document.id);
EditorSession.validateCheckpoint(document, persistence);
final referencedAssets = document.payloads
.expand((payload) => payload.assetIds)
.toSet();
final assetUris = <String, Uri>{};
for (final asset in await _project!.listAssets()) {
if (referencedAssets.contains(asset.id)) {
assetUris[asset.id] = await _project!.resolveAsset(asset);
}
}
final processing = _processing;
final session = EditorTimelineSession(
diagnostics: (event) => withDiagnosticContext({
'projectId': projectId,
}, () => reportDiagnostic(AppDiagnostics.report, event)),
document: document,
persistence: persistence,
assetUris: Map.unmodifiable(assetUris),
media: _WorkspaceEditorMedia(this, projectId),
exportService: RuntimeEditorExport(_runtime),
captionFiles: Platform.isMacOS || Platform.isIOS || Platform.isWindows
? _runtime
: null,
transcriptionBackend: processing?.transcriptionModel == null
? null
: processing!.backend,
transcriptionModel: processing?.transcriptionModel,
translationBackend: processing?.translationModel == null
? null
: processing!.backend,
translationModel: processing?.translationModel,
vocalSeparationBackend: processing?.vocalSeparationModel == null
? null
: processing!.backend,
vocalSeparationModel: processing?.vocalSeparationModel,
);
if (processing?.backgroundRemovalModel case final model?) {
session.backgroundRemovals.configure(
backend: processing!.backend.execute,
model: model,
);
}
await session.restoreProcessingTasks();
_sessions[document.id] = session;
backgroundTasks.register(
projectId: projectId,
projectName: _project!.info.name,
session: session,
);
_documents[document.id] = document;
_documentVersions[document.id] = session.version;
return session;
}
Future<PreparedEditorMedia> prepareMedia(
String projectId,
String assetId,
) => _run(() async {
final project = _fileFor(projectId);
if (project == null) throw AppException(AppErrorCode.openMatchingProject);
final asset = (await project.listAssets())
.where((asset) => asset.id == assetId)
.firstOrNull;
if (asset == null) throw AppException(AppErrorCode.mediaNoLongerExists);
final uri = await project.resolveAsset(asset);
final PreparedMediaMetadata metadata;
if (asset.metadata['kind'] == 'image') {
metadata = PreparedMediaMetadata.image();
} else {
try {
final source = MediaReference(id: asset.id, uri: uri);
metadata = PreparedMediaMetadata.fromInfo(await _runtime.probe(source));
} on RuntimeException catch (e) {
throw AppException(
e.code == 'unsupported'
? AppErrorCode.mediaInfoUnsupported
: AppErrorCode.mediaInfoFailed,
diagnostic: e.toString(),
);
}
}
return PreparedEditorMedia(
asset: _editorAsset(asset),
uri: uri,
duration: metadata.duration,
kind: metadata.kind,
hasAudio: metadata.hasAudio,
audioTracks: metadata.audioTracks,
);
});
Future<PreparedEditorMedia> importGeneratedMedia(
String projectId,
String path, {
required String name,
}) async {
final asset = await _run(() async {
final project = _fileFor(projectId);
if (project == null) {
throw const CommandRejected('closed', 'Media project has changed');
}
final imported = await project.importFile(
File(path),
name: name,
recoveryKey: 'generated:${File(path).absolute.path}',
);
final visible = _visibleAssets(await project.listAssets());
_assetChanges.add(ProjectAssetsChanged(projectId, visible));
return imported;
});
return prepareMedia(projectId, asset.id);
}
Future<void> close() {
if (_closing case final pending?) return pending;
_closed = true;
final operation = _tail.then((_) async {
try {
for (final session in _sessions.values) {
await session.flush();
}
for (final session in _retainedTimelines.keys) {
await session.flush();
}
for (final session in _sessions.values) {
backgroundTasks.unregister(session);
await session.close();
}
for (final session in _retainedTimelines.keys) {
backgroundTasks.unregister(session);
await session.close();
}
} catch (_) {
// Nothing has been released yet. Keep the workspace usable so the
// caller can recover an unsuccessful save without losing the edits.
_closed = false;
rethrow;
}
_sessions.clear();
_documents.clear();
_documentVersions.clear();
_retainedTimelines.clear();
_timelineLeases.clear();
await _project?.close();
for (final file in _retainedProjects) {
await file.close();
}
_project = null;
_retainedProjects.clear();
_warmProjects.clear();
await _assetChanges.close();
if (_ownsBackgroundTasks) backgroundTasks.dispose();
});
final closing = operation.onError((Object error, StackTrace stack) {
_closing = null;
Error.throwWithStackTrace(error, stack);
});
_closing = closing;
// A failed close must not poison the queue or prevent cleanup retries.
_tail = closing.then<void>((_) {}, onError: (Object _, StackTrace _) {});
return closing;
}
}
final class _WorkspaceEditorMedia
implements
EditorMediaService,
EditorAudioSource,
EditorMediaCatalog,
EditorGeneratedMediaCatalog {
const _WorkspaceEditorMedia(this.workspace, this.projectId);
final ProjectWorkspace workspace;
final String projectId;
@override
Future<List<EditorMediaAsset>> query() async => [
for (final asset in await workspace.listAssets(projectId))
_editorAsset(asset),
];
@override
Future<EditorMediaImportResult> importFile(
String path, {
bool Function()? isCancelled,
}) async {
final result = await workspace.importExternalMedia(projectId, [
ExternalMediaFile(path: path),
], isCancelled: isCancelled);
if (result.failures.isNotEmpty) {
throw AppException.fromFailure(result.failures.first.failure);
}
return EditorMediaImportResult(
assets: [for (final asset in result.assets) _editorAsset(asset)],
added: result.added,
duplicates: result.duplicates,
);
}
@override
Future<bool> rename(String assetId, String name) =>
workspace.editCatalog(projectId, assetId, name: name);
@override
Future<bool> remove(String assetId) =>
workspace.editCatalog(projectId, assetId);
@override
Future<MediaWaveform> waveform(String assetId, int audioTrackIndex) async {
final asset = (await workspace.listAssets(projectId))
.where((a) => a.id == assetId)
.firstOrNull;
if (asset == null) {
throw const CommandRejected('missingMedia', 'Audio asset is unavailable');
}
return workspace.withAssetMedia(
projectId,
asset,
(media) => CutdexRuntime(diagnostics: AppDiagnostics.report).waveform(
WaveformRequest(
media: media,
trackSelection: TrackSelection.index(audioTrackIndex),
baseBucketCount: 32768,
levelCount: 1,
),
),
);
}
@override
Future<PreparedEditorMedia> prepare(String assetId) =>
workspace.prepareMedia(projectId, assetId);
@override
Future<PreparedEditorMedia> importGenerated(
String path, {
required String name,
}) => workspace.importGeneratedMedia(projectId, path, name: name);
}
EditorMediaAsset _editorAsset(AssetDocument asset) =>
EditorMediaAsset(id: asset.id, name: asset.name, metadata: asset.metadata);