Files
cutdex/lib/features/media/subtitle_download.dart
T
lingjhf 27e77fff39 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.
2026-10-05 23:36:23 +08:00

268 lines
8.7 KiB
Dart

import 'package:cutdex/diagnostics/app_diagnostics.dart';
import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/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();
}
}
}