Files
cutdex/lib/features/media/subtitle_download.dart
T
lingjhf 06f1c26681
Gitea CI / Assemble and validate CI artifacts (push) Successful in 1m47s
Gitea CI / Check code and tests (push) Successful in 7m15s
Gitea CI / Build Android APK (push) Successful in 4m6s
Gitea CI / Build Windows x64 app (push) Successful in 3m34s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m29s
Gitea CI / Gitea CI passed (push) Successful in 1s
Gitea Release / Prepare draft Release (push) Failing after 8s
Gitea Release / Upload Android to draft Release (push) Skipped
Gitea Release / Upload Windows to draft Release (push) Skipped
Gitea Release / Verify and publish Release (push) Skipped
Move editor UI into the app and release verified Core dependencies (#14)
2026-10-11 19:59:40 +00:00

268 lines
8.7 KiB
Dart

import 'package:cutdex/diagnostics/app_diagnostics.dart';
import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex_core/editor.dart';
import 'package:cutdex_core/project.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../integrations/runtime/processing_configuration.dart';
import '../../integrations/runtime/processing_resource_repository.dart';
import '../../workspace/timeline_session.dart';
import 'processing_targets.dart';
part 'subtitle_download.g.dart';
part 'subtitle_download.freezed.dart';
enum SubtitleStartFailure { start, download, engine }
@freezed
abstract class SubtitleRequest with _$SubtitleRequest {
const factory SubtitleRequest({
required EditorTimelineSession session,
required SequenceId? sequence,
AssetDocument? asset,
TranscriptionClipTarget? target,
@Default('auto') String language,
@Default('none') String targetLanguage,
}) = _SubtitleRequest;
}
@freezed
sealed class SubtitleDownloadState with _$SubtitleDownloadState {
const SubtitleDownloadState._();
const factory SubtitleDownloadState.idle() = SubtitleIdle;
const factory SubtitleDownloadState.starting(SubtitleRequest request) =
SubtitleStarting;
const factory SubtitleDownloadState.downloading(
SubtitleRequest request, {
required ProcessingCapability stage,
ProcessingResourceRepository? repository,
@Default(0) double progress,
@Default(false) bool paused,
}) = SubtitleDownloading;
const factory SubtitleDownloadState.started(SubtitleRequest request) =
SubtitleStarted;
const factory SubtitleDownloadState.cancelled(SubtitleRequest request) =
SubtitleCancelled;
const factory SubtitleDownloadState.failed(
SubtitleRequest request,
SubtitleStartFailure failure,
) = SubtitleFailed;
SubtitleRequest? get request => switch (this) {
SubtitleIdle() => null,
SubtitleStarting(:final request) ||
SubtitleDownloading(:final request) ||
SubtitleStarted(:final request) ||
SubtitleCancelled(:final request) ||
SubtitleFailed(:final request) => request,
};
bool get running => this is SubtitleStarting || this is SubtitleDownloading;
}
/// Owns the download and task handoff even when its dialog is closed.
@Riverpod(keepAlive: true)
class SubtitleDownload extends _$SubtitleDownload {
ProcessingResourceRepository? _repository;
bool _cancelled = false;
@override
SubtitleDownloadState build() {
ref.onDispose(() {
_cancelled = true;
_repository?.cancelSubtitleResources();
});
return const SubtitleDownloadState.idle();
}
Future<void> start(SubtitleRequest request, {bool download = false}) async {
if (state.running) return;
_cancelled = false;
var resourceInstalled = false;
final session = request.session;
final release = session.retainViews();
state = download
? SubtitleDownloadState.downloading(
request,
stage: session.transcriptions?.recognitionAvailable == true
? ProcessingCapability.translation
: ProcessingCapability.transcription,
)
: SubtitleDownloadState.starting(request);
ProcessingResourceRepository? repository;
void changed() {
if (!ref.mounted || state is! SubtitleDownloading) return;
final current = state as SubtitleDownloading;
state = current.copyWith(
paused: repository?.subtitlePaused ?? current.paused,
);
}
try {
final service = session.transcriptions;
if (download) {
final loaded = await ref.read(
processingResourceRepositoryProvider.future,
);
repository = loaded;
if (_cancelled || !ref.mounted) {
return;
}
_repository = loaded;
final pausedBeforeLoad = (state as SubtitleDownloading).paused;
state = (state as SubtitleDownloading).copyWith(repository: loaded);
loaded.addListener(changed);
final install = loaded.ensureSubtitleResources(
available: {
if (service?.recognitionAvailable == true)
ProcessingCapability.transcription,
if (service?.translationAvailable == true)
ProcessingCapability.translation,
},
onProgress: (stage, progress) {
if (!ref.mounted) return;
if (state case SubtitleDownloading(:final paused)) {
state = SubtitleDownloadState.downloading(
request,
stage: stage,
repository: loaded,
progress: progress,
paused: paused,
);
}
},
);
if (pausedBeforeLoad) loaded.pauseSubtitleResources();
await install;
resourceInstalled = true;
if (_cancelled || !ref.mounted) {
return;
}
final processing = ProcessingConfiguration.configured(
diagnostics: AppDiagnostics.report,
resourcesRoot: loaded.root.parent.path,
);
final speechBackend = service?.backend ?? processing?.backend;
final speechModel =
service?.modelDirectory ?? processing?.transcriptionModel;
final translationBackend =
service?.translationBackend ?? processing?.backend;
final translationModel =
service?.translationModel ?? processing?.translationModel;
if (speechBackend == null ||
speechModel == null ||
translationBackend == null ||
translationModel == null) {
throw AppException(AppErrorCode.subtitleEngineUnavailable);
}
session.configureProcessing(
transcriptionBackend: speechBackend,
transcriptionModel: speechModel,
translationBackend: translationBackend,
translationModel: translationModel,
);
}
if (_cancelled || !ref.mounted) {
return;
}
await _startSubtitles(request);
if (ref.mounted) state = SubtitleDownloadState.started(request);
} on ProcessingResourceCancelledException {
if (ref.mounted) state = SubtitleDownloadState.cancelled(request);
} catch (_) {
if (ref.mounted) {
state = SubtitleDownloadState.failed(
request,
!download
? SubtitleStartFailure.start
: resourceInstalled
? SubtitleStartFailure.engine
: SubtitleStartFailure.download,
);
}
} finally {
repository?.removeListener(changed);
_repository = null;
if (ref.mounted && _cancelled && state.running) {
state = SubtitleDownloadState.cancelled(request);
}
release();
}
}
void togglePause() {
if (state case SubtitleDownloading(:final paused)) {
state = (state as SubtitleDownloading).copyWith(paused: !paused);
if (paused) {
_repository?.resumeSubtitleResources();
} else {
_repository?.pauseSubtitleResources();
}
}
}
void cancel() {
if (!state.running) return;
_cancelled = true;
_repository?.cancelSubtitleResources();
}
}
Future<void> _startSubtitles(SubtitleRequest request) async {
final mediaId = request.target?.mediaId ?? request.asset?.id;
final name = request.target?.name ?? request.asset?.name ?? mediaId;
final sequence = request.sequence;
if (sequence == null || mediaId == null || name == null) {
throw const CommandRejected(
'missingSequence',
'Sequence or media does not exist',
);
}
await request.session.subtitleWorkflows.start(
sequence: sequence,
command: StartTranscription(
mediaId: mediaId,
clipId: request.target?.clipId,
audioStream: request.target?.audioStream ?? 0,
language: request.language,
),
name: name,
targetLanguage: request.targetLanguage,
);
}
/// Configured sessions can start independently of another project's download.
@riverpod
class SubtitleStart extends _$SubtitleStart {
@override
SubtitleDownloadState build(EditorTimelineSession session) =>
const SubtitleDownloadState.idle();
void reset() {
if (!state.running) state = const SubtitleDownloadState.idle();
}
Future<void> start(SubtitleRequest request) async {
if (state.running) return;
final lease = ref.keepAlive();
final release = session.retainViews();
state = SubtitleDownloadState.starting(request);
try {
await _startSubtitles(request);
if (ref.mounted) state = SubtitleDownloadState.started(request);
} catch (_) {
if (ref.mounted) {
state = SubtitleDownloadState.failed(
request,
SubtitleStartFailure.start,
);
}
} finally {
release();
lease.close();
}
}
}