diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index d2a685de4..1f8e69605 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -20,6 +20,8 @@ from opendirector.application.creation_canvas import CreationCanvas from opendirector.application.creation_history import CreationHistory from opendirector.application.creation_timeline_packages import CreationTimelinePackages +from opendirector.application.linked_draft import LinkedVideoDrafts +from opendirector.domain.creation.linked_draft import LinkedClipSaveInput, LinkedDraftView from opendirector.domain.creation.timeline_packages import TimelinePackageImportRequest, TimelinePackageImportReceipt from opendirector.domain.creation.assets import Asset, UploadInfo from opendirector.domain.creation.base import MediaKind @@ -31,7 +33,7 @@ from opendirector.infrastructure.creation_projects import CreationProjects from opendirector.media.fonts import MAX_FONT_BYTES, inspect_font from opendirector_api.models import AssetSource, Session -from opendirector_api.localization import localized_receipt +from opendirector_api.localization import localized_error, localized_receipt from opendirector_api.localization import localized_error_for_language @@ -79,12 +81,79 @@ async def disconnected(): await asyncio.gather(work, disconnect, return_exceptions=True) +def _stream_byte_range( + stream, + *, + size: int, + etag: str, + mime_type: str, + filename: str, + attachment: bool, + range_header: str | None, + if_none_match: str | None, +): + headers = { + 'Accept-Ranges': 'bytes', + 'ETag': etag, + 'Cache-Control': 'private, no-cache', + 'X-Content-Type-Options': 'nosniff', + 'Content-Disposition': ('attachment' if attachment else 'inline') + + "; filename*=utf-8''" + quote(filename, safe=''), + } + if range_header is None and if_none_match == etag: + stream.close() + return Response(status_code=304, headers=headers) + start, end = 0, size - 1 + if range_header is not None: + try: + match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header) if len(range_header) <= 128 else None + if match is None or not any(match.groups()) or not size: + raise ValueError() + first, last = match.groups() + if first: + start, end = int(first), min(int(last), size - 1) if last else size - 1 + else: + suffix = int(last) + if suffix <= 0: + raise ValueError() + start = max(0, size - suffix) + if start > end or start >= size: + raise ValueError() + except ValueError: + stream.close() + return Response(status_code=416, headers={**headers, 'Content-Range': f'bytes */{size}'}) + headers['Content-Range'] = f'bytes {start}-{end}/{size}' + headers['Content-Length'] = str(end - start + 1) + + async def chunks(): + try: + await run_in_threadpool(stream.seek, start) + remaining = end - start + 1 + while remaining > 0: + data = await run_in_threadpool(stream.read, min(1024 * 1024, remaining)) + if not data: + break + remaining -= len(data) + yield data + finally: + stream.close() + + return StreamingResponse( + chunks(), + status_code=206 if range_header else 200, + media_type=mime_type, + headers=headers, + background=BackgroundTask(stream.close), + ) + + def creation_routes(projects: CreationProjects, generation=None, prompt_optimization=None): router = APIRouter(prefix='/api/creation', tags=['Unified creation projects']) assets = CreationAssets(projects) canvas = CreationCanvas(projects) history = CreationHistory(projects, assets=assets) timeline_packages = CreationTimelinePackages(projects) + linked_drafts = LinkedVideoDrafts(projects) @router.post('/fonts/inspect', response_model=FontCoverageResponse) async def inspect_preview_font(request: Request, response: Response, @@ -375,48 +444,57 @@ def browser_image(project_id: UUID, asset_id: UUID, def content(project_id: UUID, asset_id: UUID, range_header: str | None = Header(default=None, alias='Range'), if_none_match: str | None = Header(default=None, alias='If-None-Match')): stream, asset = assets.open_media(project_id, asset_id) - size, etag = asset.metadata.size, '"' + asset.fingerprint + '"' - headers = {'Accept-Ranges': 'bytes', 'ETag': etag, 'Cache-Control': 'private, no-cache', - 'X-Content-Type-Options': 'nosniff', - 'Content-Disposition': ('attachment' if asset.kind == 'file' else 'inline') - + "; filename*=utf-8''" + quote(asset.name, safe='')} - if range_header is None and if_none_match == etag: - stream.close() - return Response(status_code=304, headers=headers) - start, end = 0, size - 1 - if range_header is not None: - try: - match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header) if len(range_header) <= 128 else None - if match is None or not any(match.groups()) or not size: - raise ValueError() - first, last = match.groups() - if first: - start, end = int(first), min(int(last), size - 1) if last else size - 1 - else: - suffix = int(last) - if suffix <= 0: - raise ValueError() - start = max(0, size - suffix) - if start > end or start >= size: - raise ValueError() - except ValueError: - stream.close() - return Response(status_code=416, headers={**headers, 'Content-Range': f'bytes */{size}'}) - headers['Content-Range'] = f'bytes {start}-{end}/{size}' - headers['Content-Length'] = str(end - start + 1) - async def chunks(): - try: - stream.seek(start) - remaining = end - start + 1 - while remaining > 0: - data = await run_in_threadpool(stream.read, min(1024 * 1024, remaining)) - if not data: - break - remaining -= len(data) - yield data - finally: - stream.close() - return StreamingResponse(chunks(), status_code=206 if range_header else 200, - media_type=asset.metadata.mimeType, headers=headers, background=BackgroundTask(stream.close)) + return _stream_byte_range( + stream, + size=asset.metadata.size, + etag='"' + asset.fingerprint + '"', + mime_type=asset.metadata.mimeType, + filename=asset.name, + attachment=asset.kind == 'file', + range_header=range_header, + if_none_match=if_none_match, + ) + + @router.get('/projects/{project_id}/linked-draft', response_model=LinkedDraftView) + def get_linked_draft( + project_id: UUID, + request: Request, + source_id: UUID | None = Query(default=None, alias='sourceId'), + ): + view = linked_drafts.get_draft(project_id, source_id=source_id) + if view.reason and view.reasonCode: + view = view.model_copy(update={ + 'reason': localized_error(request, chinese=view.reason, status=409, code=view.reasonCode), + }) + return view + + @router.put('/projects/{project_id}/linked-draft', response_model=LinkedDraftView) + def put_linked_draft( + project_id: UUID, + value: LinkedClipSaveInput, + x_opendirector_session: UUID | None = Header(default=None), + ): + session = str(x_opendirector_session) if x_opendirector_session else None + return linked_drafts.save_clip(project_id, value, session=session) + + @router.get('/projects/{project_id}/linked-sources/{source_id}/content') + def linked_source_content( + project_id: UUID, + source_id: UUID, + range_header: str | None = Header(default=None, alias='Range'), + if_none_match: str | None = Header(default=None, alias='If-None-Match'), + ): + stream, info = linked_drafts.open_media(project_id, source_id) + etag = f'"linked-{info.sourceId}-{info.size}-{info.modifiedAt}"' + return _stream_byte_range( + stream, + size=info.size, + etag=etag, + mime_type=info.mimeType, + filename=info.title, + attachment=False, + range_header=range_header, + if_none_match=if_none_match, + ) return router diff --git a/apps/api/src/opendirector_api/desktop.py b/apps/api/src/opendirector_api/desktop.py index 41ca054a1..ab3c9ce10 100644 --- a/apps/api/src/opendirector_api/desktop.py +++ b/apps/api/src/opendirector_api/desktop.py @@ -19,8 +19,9 @@ from starlette.types import ASGIApp, Scope, Receive, Send from starlette.requests import Request -from opendirector_api.localization import localized_error +from opendirector_api.localization import localized_error, localized_error_for_language +from opendirector.domain.projects import ProjectError from opendirector.infrastructure.local_projects import LocalProjects from opendirector.installation import data_root from opendirector_api.main import create_app @@ -67,7 +68,16 @@ class SessionRegistration(BaseModel): sessionId: UUID -CONTROL = TypeAdapter(Annotated[Control | SessionRegistration, Field(discriminator='type')]) +class BindLinkedVideo(BaseModel): + model_config = ConfigDict(extra='forbid') + type: Literal['bind-linked-video'] + requestId: int = Field(ge=1) + projectId: UUID + filePath: str = Field(min_length=1, max_length=4096) + locale: str = Field(default='zh-CN', max_length=32) + + +CONTROL = TypeAdapter(Annotated[Control | SessionRegistration | BindLinkedVideo, Field(discriminator='type')]) def runtime_check() -> dict[str, str]: @@ -87,6 +97,10 @@ def runtime_check() -> dict[str, str]: async def serve(token: str) -> None: + if hasattr(sys.stdout, 'reconfigure'): + sys.stdout.reconfigure(encoding='utf-8') + if hasattr(sys.stderr, 'reconfigure'): + sys.stderr.reconfigure(encoding='utf-8') output = sys.stdout def emit(event: dict[str, object]) -> None: @@ -105,16 +119,16 @@ def emit(event: dict[str, object]) -> None: port = listener.getsockname()[1] os.environ['OPENDIRECTOR_API_URL'] = f'http://127.0.0.1:{port}' sessions: set[str] = set() - commands: asyncio.Queue[str] = asyncio.Queue() + commands: asyncio.Queue[bytes] = asyncio.Queue() loop = asyncio.get_running_loop() def read_controls() -> None: - while line := sys.stdin.readline(65537): - if len(line) > 65536: - loop.call_soon_threadsafe(commands.put_nowait, 'invalid\n') + while raw := sys.stdin.buffer.readline(65537): + if len(raw) > 65536: + loop.call_soon_threadsafe(commands.put_nowait, b'invalid\n') return - loop.call_soon_threadsafe(commands.put_nowait, line) - loop.call_soon_threadsafe(commands.put_nowait, '') + loop.call_soon_threadsafe(commands.put_nowait, raw) + loop.call_soon_threadsafe(commands.put_nowait, b'') class DesktopServer(uvicorn.Server): async def startup(self, sockets: list[socket.socket] | None = None) -> None: @@ -138,6 +152,42 @@ async def control() -> None: if message.type == 'shutdown': server.should_exit = True return + if message.type == 'bind-linked-video': + try: + info = await asyncio.to_thread( + app.state.bind_linked_video, message.projectId, message.filePath, + ) + emit({ + 'type': 'linked-video-bound', + 'requestId': message.requestId, + 'ok': True, + 'source': info.model_dump(mode='json'), + }) + except ProjectError as error: + emit({ + 'type': 'linked-video-bound', + 'requestId': message.requestId, + 'ok': False, + 'code': error.code, + 'message': localized_error_for_language( + message.locale, chinese=str(error), status=error.status, code=error.code, + ), + }) + except Exception: + logging.getLogger(__name__).exception('Unexpected error binding linked video') + emit({ + 'type': 'linked-video-bound', + 'requestId': message.requestId, + 'ok': False, + 'code': 'linked_source_offline', + 'message': localized_error_for_language( + message.locale, + chinese='无法读取所选视频文件,请检查文件格式与挂载盘状态。', + status=409, + code='linked_source_offline', + ), + }) + continue emit({'type': 'inspection', 'requestId': message.requestId, **app.state.desktop_activity()}) threading.Thread(target=read_controls, name='desktop-parent', daemon=True).start() @@ -161,7 +211,7 @@ async def control() -> None: def main() -> None: try: - message = Initialize.model_validate_json(sys.stdin.readline(65537)) + message = Initialize.model_validate_json(sys.stdin.buffer.readline(65537)) asyncio.run(serve(message.token)) except ValueError: print(json.dumps({'type': 'fatal', 'version': 1, 'message': 'Invalid desktop control message.'}), flush=True) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 183412a69..265d17e7a 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -128,6 +128,9 @@ "canvas_run_layout_conflict": "Locked Run areas overlap. Unlock one of the groups and try again.", "canvas_run_layout_shared_object": "Two Runs use the same editable object. Copy the configuration or editor document and try again.", "storage_unavailable": "A stored file is missing or has changed. Restore the file and try again.", + "linked_source_offline": "The linked source video is currently unavailable (drive disconnected, file moved, or access denied). Your clip and trim points were kept.", + "linked_source_modified": "The linked source video size or modification time changed. Playback is paused while keeping your saved trim points.", + "linked_source_unbound": "This computer does not have a local binding for the linked video source. Your clip and trim points were kept.", "capability_unsupported": "This capability is not supported yet.", "model_list_http_error": "Could not load the model list from the service.", "operation_rejected": "The operation was rejected. Reload the item and try again.", diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index 3b4bf88a3..75f28a926 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -22,6 +22,7 @@ from opendirector.application.prompt_optimization import PromptOptimization from opendirector.application.tool_tasks import ToolTasks from opendirector.application.creation_tool_assets import CreationToolAssets +from opendirector.application.linked_draft import LinkedVideoDrafts from opendirector.infrastructure.local_projects import LocalProjects from opendirector.infrastructure.creation_projects import CreationProjects from opendirector.infrastructure.model_configs import ModelConfigs @@ -94,6 +95,7 @@ async def lifespan(app): app.state.desktop_activity = lambda: dict( agents=len(active_agents), generations=sum(not job.future.done() for job in creation_generation.jobs.values()), tools=sum(not job.done() for job in creation_tools.jobs.values())) + app.state.bind_linked_video = LinkedVideoDrafts(creation_projects).bind_video @app.exception_handler(RequestValidationError) diff --git a/apps/desktop/src/host.mjs b/apps/desktop/src/host.mjs index 068ffc871..4a7818137 100644 --- a/apps/desktop/src/host.mjs +++ b/apps/desktop/src/host.mjs @@ -13,6 +13,14 @@ export const eventSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('fatal'), version: z.literal(1), message: z.string() }), z.object({ type: z.literal('inspection'), requestId: z.number().int().positive(), agents: z.number().int().nonnegative(), generations: z.number().int().nonnegative(), tools: z.number().int().nonnegative() }), + z.object({ + type: z.literal('linked-video-bound'), + requestId: z.number().int().positive(), + ok: z.boolean(), + source: z.record(z.string(), z.unknown()).optional(), + code: z.string().optional(), + message: z.string().optional(), + }), z.object({ type: z.literal('shutdown-complete') }), ]); @@ -25,7 +33,7 @@ export class Host { shutdownComplete = false; constructor({ python, env, directory, log, onExit }) { - this.child = spawn(python, ['-I', '-B', '-m', 'opendirector_api.desktop'], { + this.child = spawn(python, ['-I', '-B', '-X', 'utf8', '-m', 'opendirector_api.desktop'], { cwd: directory, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, }); this.child.stderr.pipe(log, { end: false }); @@ -46,7 +54,7 @@ export class Host { reject(new Error(event.message)); } else if (event.type === 'shutdown-complete') { this.shutdownComplete = true; - } else if (event.type === 'inspection') { + } else if (event.type === 'inspection' || event.type === 'linked-video-bound') { this.pending.get(event.requestId)?.(event); this.pending.delete(event.requestId); } @@ -83,6 +91,18 @@ export class Host { }); } + async bindLinkedVideo(projectId, filePath, locale) { + if (!this.url || this.child.exitCode !== null) return null; + const requestId = ++this.nextId; + return new Promise(resolve => { + const timeout = setTimeout(() => { this.pending.delete(requestId); resolve(null); }, 15_000); + this.pending.set(requestId, event => { clearTimeout(timeout); resolve(event); }); + this.child.stdin.write(JSON.stringify({ + type: 'bind-linked-video', requestId, projectId, filePath, locale, + }) + '\n'); + }); + } + async stop() { this.stopping = true; if (this.child.exitCode !== null) return; @@ -108,6 +128,9 @@ export async function proxyRequest(request, host, fetcher) { const headers = new Headers(request.headers); for (const name of ['host', 'origin', 'cookie', 'authorization', 'connection', 'content-length', 'x-opendirector-desktop']) headers.delete(name); headers.set('X-OpenDirector-Desktop', host.token); + if (request.method === 'GET' && /^\/api\/creation\/projects\/[^/]+\/linked-sources\/[^/]+\/content$/.test(incoming.pathname)) { + headers.set('X-OpenDirector-Request', '1'); + } const upload = request.method === 'PUT' && /^\/api\/creation\/projects\/[^/]+\/uploads\/[^/]+$/.test(incoming.pathname); const options = { method: request.method, headers, redirect: 'manual', credentials: 'omit', cache: 'no-store', signal: request.signal, @@ -123,7 +146,9 @@ export async function proxyRequest(request, host, fetcher) { const response = await fetcher(target.href, options); if (response.status >= 300 && response.status < 400 && response.status !== 304) return new Response(null, { status: 502 }); const outgoing = new Headers(response.headers); - for (const name of ['connection', 'transfer-encoding', 'keep-alive', 'set-cookie', 'content-encoding', 'content-length']) outgoing.delete(name); + const encoded = response.headers.has('content-encoding'); + for (const name of ['connection', 'transfer-encoding', 'keep-alive', 'set-cookie', 'content-encoding']) outgoing.delete(name); + if (encoded) outgoing.delete('content-length'); outgoing.set('Cache-Control', 'no-store'); outgoing.set('Content-Security-Policy', "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob: data:; font-src 'self' data:; connect-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-src 'none'"); return new Response(response.body, { status: response.status, statusText: response.statusText, headers: outgoing }); diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs index c1ba6060c..32feb94c6 100644 --- a/apps/desktop/src/main.mjs +++ b/apps/desktop/src/main.mjs @@ -62,6 +62,20 @@ ipcMain.on('desktop:session', (event, value) => { ipcMain.on('desktop:exporting', (event, value) => { if (trusted(event) && typeof value === 'boolean') exporting = value; }); +ipcMain.handle('desktop:pick-linked-video', async (event, projectId) => { + const parsed = z.uuid().safeParse(projectId); + if (!trusted(event) || !parsed.success || !host) return null; + const { canceled, filePaths } = await dialog.showOpenDialog(window, { + properties: ['openFile'], + filters: [{ name: 'Video', extensions: ['mp4', 'mov', 'webm', 'm4v'] }], + }); + if (canceled || !filePaths[0]) return null; + const result = await host.bindLinkedVideo(parsed.data, filePaths[0], locale); + if (!result) return { ok: false, code: 'linked_source_offline', message: text().failed }; + return result.ok + ? { ok: true, source: result.source } + : { ok: false, code: result.code ?? 'operation_rejected', message: result.message ?? text().failed }; +}); function desktopActions() { return [ @@ -147,7 +161,7 @@ async function start() { // upload uses Node fetch to send the body incrementally over loopback. // Asset reads use it too so large response bodies reach the renderer. const assetMedia = options.method === 'GET' && - /^\/api\/creation\/projects\/[^/]+\/assets\/[^/]+\/content$/.test(pathname); + /^\/api\/creation\/projects\/[^/]+\/(?:assets|linked-sources)\/[^/]+\/content$/.test(pathname); return options.duplex || assetMedia ? fetch(url, options) : net.fetch(url, options); })); ownedSession.on('will-download', (_event, item) => item.setSaveDialogOptions({ title: text().save })); diff --git a/apps/desktop/src/preload.cjs b/apps/desktop/src/preload.cjs index 5bc5597e7..92e413303 100644 --- a/apps/desktop/src/preload.cjs +++ b/apps/desktop/src/preload.cjs @@ -4,6 +4,7 @@ contextBridge.exposeInMainWorld('opendirectorDesktop', { setLocale: locale => ipcRenderer.send('desktop:locale', locale), ...(['darwin', 'win32'].includes(process.platform) ? { showMore: () => ipcRenderer.send('desktop:more') } : {}), setExporting: active => ipcRenderer.send('desktop:exporting', active), + pickLinkedVideo: projectId => ipcRenderer.invoke('desktop:pick-linked-video', projectId), }); function markDesktop() { diff --git a/packages/core/src/opendirector/application/linked_draft.py b/packages/core/src/opendirector/application/linked_draft.py new file mode 100644 index 000000000..a5698c162 --- /dev/null +++ b/packages/core/src/opendirector/application/linked_draft.py @@ -0,0 +1,99 @@ +"""Application service for the single-video in-place editing slice (§19). + +Coordinates Host-local source bindings (stored under workspace/state) with the +project-scoped experimental clip record, ensuring all external file stat/open +calls happen outside project SQLite transaction locks. +""" +from uuid import UUID + +from opendirector.domain.creation.linked_draft import ( + LinkedClipSaveInput, LinkedDraftView, LinkedVideoSourceInfo, +) +from opendirector.domain.projects import ProjectError +from opendirector.ports.gateway import gateway + + +class LinkedVideoDrafts: + def __init__(self, projects): + self.projects = projects + + def _sources(self): + return gateway().linked_sources(self.projects.state_dir) + + def bind_video(self, project_id: UUID, file_path: str) -> LinkedVideoSourceInfo: + """Bind a user-selected host file to a project via the trusted control pipe.""" + project_uuid = UUID(str(project_id)) + self.projects.snapshot(project_uuid) + return self._sources().bind_video(project_uuid, file_path) + + def get_draft(self, project_id: UUID, *, source_id: UUID | None = None) -> LinkedDraftView: + """Return the saved experimental clip (if any) and live source availability.""" + project_uuid = UUID(str(project_id)) + self.projects.snapshot(project_uuid) + clip = self.projects.linked_clip_draft(project_uuid) + sources = self._sources() + if source_id is not None: + info, availability, code, reason = sources.inspect_availability( + project_uuid, UUID(str(source_id)), + ) + return LinkedDraftView( + projectId=project_uuid, + source=info, + availability=availability, + reasonCode=code, + reason=reason, + clip=clip, + ) + if clip is not None: + info, availability, code, reason = sources.inspect_availability(project_uuid, clip.sourceId) + return LinkedDraftView( + projectId=project_uuid, + source=info, + availability=availability, + reasonCode=code, + reason=reason, + clip=clip, + ) + latest = sources.latest_for_project(project_uuid) + if latest is None: + return LinkedDraftView(projectId=project_uuid, source=None, availability='unbound') + info, availability, code, reason = sources.inspect_availability(project_uuid, latest.sourceId) + return LinkedDraftView( + projectId=project_uuid, + source=info, + availability=availability, + reasonCode=code, + reason=reason, + clip=None, + ) + + def save_clip( + self, project_id: UUID, value: LinkedClipSaveInput, *, session: str | None, + ) -> LinkedDraftView: + """Verify source availability outside locks, then atomically persist trim points under lease.""" + project_uuid = UUID(str(project_id)) + payload = LinkedClipSaveInput.model_validate(value) + info, availability, code, reason = self._sources().inspect_availability(project_uuid, payload.sourceId) + if availability != 'online' or info is None: + raise ProjectError( + reason or '源视频当前不可用,无法保存实验剪辑。', + 409, + code=code or 'linked_source_offline', + ) + if payload.outPoint > info.durationSeconds: + raise ProjectError('裁剪出点超出源视频真实时长。', 422, code='invalid_input') + payload = payload.model_copy(update={'durationSeconds': info.durationSeconds}) + saved = self.projects.linked_clip_draft(project_uuid, payload, session=session) + return LinkedDraftView( + projectId=project_uuid, + source=info, + availability='online', + clip=saved, + ) + + def open_media(self, project_id: UUID, source_id: UUID): + """Open a read-only stream for Range playback after verifying project & source state.""" + project_uuid = UUID(str(project_id)) + source_uuid = UUID(str(source_id)) + self.projects.snapshot(project_uuid) + return self._sources().open_stream(project_uuid, source_uuid) diff --git a/packages/core/src/opendirector/domain/creation/linked_draft.py b/packages/core/src/opendirector/domain/creation/linked_draft.py new file mode 100644 index 000000000..2d93092b1 --- /dev/null +++ b/packages/core/src/opendirector/domain/creation/linked_draft.py @@ -0,0 +1,84 @@ +"""Contracts for the single-video in-place editing slice (Issue #473 §19). + +Separates the Host-local single-file binding (never persisted in project files) +from the project-scoped experimental clip record (which stores only stable IDs +and trim points in seconds, without faking an AssetRef fingerprint). +""" +from math import isfinite +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import Field, model_validator + +from .base import Contract, Identifier, NonNegative, Positive, PositiveInt + +NonNegativeInt = Annotated[int, Field(strict=True, ge=0)] +LinkedSourceAvailability = Literal['online', 'offline', 'modified', 'unbound'] + + +class LinkedVideoSourceInfo(Contract): + sourceId: UUID = Field(description='Random host-local binding ID.') + projectId: UUID = Field(description='Owning project ID.') + title: str = Field(min_length=1, max_length=255, description='Display file name (no host path).') + mimeType: str = Field(min_length=1, max_length=128, description='Detected video MIME type.') + size: PositiveInt = Field(description='Observed source size in bytes at bind time.') + modifiedAt: str = Field(min_length=1, description='Observed UTC ISO-8601 modification timestamp.') + durationSeconds: Positive = Field(description='Probed video duration in seconds.') + width: PositiveInt | None = Field(default=None, description='Video width in pixels, when known.') + height: PositiveInt | None = Field(default=None, description='Video height in pixels, when known.') + + +class LinkedClipDraft(Contract): + schemaVersion: Literal[1] = Field(default=1, description='Experimental record format version.') + timelineId: Identifier = Field(description='Stable experimental timeline ID.') + clipId: Identifier = Field(description='Stable experimental clip ID.') + sourceId: UUID = Field(description='Host-local bound video source ID.') + title: str = Field(min_length=1, max_length=255, description='Display name of the bound clip.') + durationSeconds: Positive = Field(description='Known source duration in seconds.') + start: NonNegative = Field(default=0.0, description='Clip start position on the timeline in seconds.') + inPoint: NonNegative = Field(description='Source trim in-point in seconds.') + outPoint: Positive = Field(description='Source trim out-point in seconds.') + revision: PositiveInt = Field(default=1, description='Monotonic edit revision for CAS saves.') + + @model_validator(mode='after') + def check_interval(self): + for val in (self.durationSeconds, self.start, self.inPoint, self.outPoint): + if not isfinite(val): + raise ValueError('Clip timing values must be finite numbers') + if self.inPoint < 0 or self.outPoint <= self.inPoint: + raise ValueError('Clip trim points must satisfy 0 <= inPoint < outPoint') + if self.outPoint > self.durationSeconds + 1e-6: + raise ValueError('Clip outPoint cannot exceed source duration') + return self + + +class LinkedClipSaveInput(Contract): + timelineId: Identifier = Field(description='Stable experimental timeline ID.') + clipId: Identifier = Field(description='Stable experimental clip ID.') + sourceId: UUID = Field(description='Host-local bound video source ID.') + title: str = Field(min_length=1, max_length=255, description='Display name of the bound clip.') + durationSeconds: Positive = Field(description='Known source duration in seconds.') + start: NonNegative = Field(default=0.0, description='Clip start position on the timeline in seconds.') + inPoint: NonNegative = Field(description='Source trim in-point in seconds.') + outPoint: Positive = Field(description='Source trim out-point in seconds.') + expectedRevision: NonNegativeInt = Field(default=0, description='Expected current revision (0 when creating).') + + @model_validator(mode='after') + def check_interval(self): + for val in (self.durationSeconds, self.start, self.inPoint, self.outPoint): + if not isfinite(val): + raise ValueError('Clip timing values must be finite numbers') + if self.inPoint < 0 or self.outPoint <= self.inPoint: + raise ValueError('Clip trim points must satisfy 0 <= inPoint < outPoint') + if self.outPoint > self.durationSeconds + 1e-6: + raise ValueError('Clip outPoint cannot exceed source duration') + return self + + +class LinkedDraftView(Contract): + projectId: UUID = Field(description='Owning project ID.') + source: LinkedVideoSourceInfo | None = Field(default=None, description='Current bound source metadata, when bound on this host.') + availability: LinkedSourceAvailability = Field(description='Derived availability of the referenced source.') + reasonCode: str | None = Field(default=None, description='Localizable status reason code when unavailable.') + reason: str | None = Field(default=None, description='Localized human-readable status message when unavailable.') + clip: LinkedClipDraft | None = Field(default=None, description='Saved experimental timeline clip record, if any.') diff --git a/packages/core/src/opendirector/infrastructure/creation_projects.py b/packages/core/src/opendirector/infrastructure/creation_projects.py index 4c5a45ff8..fa4ab81a4 100644 --- a/packages/core/src/opendirector/infrastructure/creation_projects.py +++ b/packages/core/src/opendirector/infrastructure/creation_projects.py @@ -18,6 +18,7 @@ from opendirector.domain.creation.base import digest from opendirector.domain.creation.commands import Command from opendirector.domain.creation.index import object_index +from opendirector.domain.creation.linked_draft import LinkedClipDraft, LinkedClipSaveInput from opendirector.domain.creation.project import Project, ProjectSnapshot, ViewState from opendirector.domain.creation.validation import ContractError, validate_command from opendirector.domain.projects import ProjectError, identifier, project_name @@ -121,6 +122,54 @@ def view(self, project_id, client_id, value=None, *, session=None, missing_ok=Fa return ViewState.model_validate(read_json(file)) return None if missing_ok else ViewState(projectId=project_id, clientId=client_id) + def linked_clip_draft( + self, project_id, value: LinkedClipSaveInput | None = None, *, session: str | None = None, + ) -> LinkedClipDraft | None: + """Read or atomically save the project's experimental in-place clip record (§19).""" + with self.local.transaction() as db: + self._recover() + path, _ = self._find(db, project_id) + file = child(path, 'linked-clip-draft.json') + existing = LinkedClipDraft.model_validate(read_json(file)) if file.exists() else None + if value is None: + return existing + self._lease(db, project_id, path, session) + payload = LinkedClipSaveInput.model_validate(value) + if existing is None: + if payload.expectedRevision != 0: + raise ProjectError('实验剪辑记录版本不匹配,请重新打开后再保存。', 409, code='revision_conflict') + next_revision = 1 + else: + if payload.expectedRevision != existing.revision: + raise ProjectError('实验剪辑记录已在其他操作中更新,请刷新后重试。', 409, code='revision_conflict') + unchanged = ( + existing.timelineId == payload.timelineId + and existing.clipId == payload.clipId + and existing.sourceId == payload.sourceId + and existing.title == payload.title + and abs(existing.durationSeconds - payload.durationSeconds) <= 1e-9 + and abs(existing.start - payload.start) <= 1e-9 + and abs(existing.inPoint - payload.inPoint) <= 1e-9 + and abs(existing.outPoint - payload.outPoint) <= 1e-9 + ) + if unchanged: + return existing + next_revision = existing.revision + 1 + saved = LinkedClipDraft( + schemaVersion=1, + timelineId=payload.timelineId, + clipId=payload.clipId, + sourceId=payload.sourceId, + title=payload.title, + durationSeconds=payload.durationSeconds, + start=payload.start, + inPoint=payload.inPoint, + outPoint=payload.outPoint, + revision=next_revision, + ) + durable_json(file, saved.model_dump(mode='json')) + return saved + def open_canvas( self, project_id: UUID | str, session: str, *, allow_preview: bool, persistent: bool = False, ) -> tuple[ProjectSnapshot, dict[str, str | None]]: diff --git a/packages/core/src/opendirector/infrastructure/linked_sources.py b/packages/core/src/opendirector/infrastructure/linked_sources.py new file mode 100644 index 000000000..04d28c16f --- /dev/null +++ b/packages/core/src/opendirector/infrastructure/linked_sources.py @@ -0,0 +1,344 @@ +"""SQLite-backed host-local binding store and read-only stream opener (§19). + +Persists bindings strictly in workspace/state/linked-media.sqlite (outside all +project directories). Every external stat, probe, and open executes outside +SQLite locks with a bounded timeout so a hung mount never blocks the host. +""" +from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError +from contextlib import contextmanager +from datetime import datetime, timezone +import os +from pathlib import Path +import shutil +import sqlite3 +import struct +from threading import Lock +from typing import BinaryIO +from uuid import UUID, uuid4 + +from opendirector.domain.creation.linked_draft import ( + LinkedSourceAvailability, LinkedVideoSourceInfo, +) +from opendirector.domain.projects import ProjectError +from opendirector.media.probe import probe_file + +DEFAULT_EXTERNAL_IO_TIMEOUT = 10.0 +_WIN_FILE_ATTRIBUTE_REPARSE_POINT = 0x0400 + +_MIME_BY_SUFFIX = { + '.mp4': 'video/mp4', + '.m4v': 'video/mp4', + '.mov': 'video/quicktime', + '.webm': 'video/webm', +} + +_SCHEMA = """ +CREATE TABLE IF NOT EXISTS linked_video_sources ( + project_id TEXT NOT NULL, + source_id TEXT NOT NULL, + file_path TEXT NOT NULL, + title TEXT NOT NULL, + mime_type TEXT NOT NULL, + size INTEGER NOT NULL, + mtime_ns INTEGER NOT NULL, + modified_at TEXT NOT NULL, + duration_seconds REAL NOT NULL, + width INTEGER, + height INTEGER, + created_at TEXT NOT NULL, + PRIMARY KEY (project_id, source_id) +); + +CREATE INDEX IF NOT EXISTS idx_linked_video_sources_project + ON linked_video_sources (project_id, created_at DESC); +""" + + +def _iso_utc(timestamp: float) -> str: + return datetime.fromtimestamp(timestamp, tz=timezone.utc).isoformat(timespec='seconds').replace('+00:00', 'Z') + + +def _utc_now() -> str: + return datetime.now(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z') + + +def _is_file_symlink_or_reparse(path: Path) -> bool: + st = os.lstat(path) + if path.is_symlink(): + return True + attrs = getattr(st, 'st_file_attributes', 0) + return bool(attrs & _WIN_FILE_ATTRIBUTE_REPARSE_POINT) + + +def _parse_mvhd_duration(data: bytes) -> float | None: + """Fallback header-only ISO BMFF (MP4/MOV) mvhd duration parser when ffprobe is absent.""" + idx = 0 + while True: + pos = data.find(b'mvhd', idx) + if pos < 4 or pos + 24 > len(data): + return None + version = data[pos + 4] + if version == 0 and pos + 24 <= len(data): + timescale, duration = struct.unpack('>II', data[pos + 16:pos + 24]) + if timescale > 0 and duration > 0: + return duration / timescale + elif version == 1 and pos + 36 <= len(data): + timescale, duration = struct.unpack('>IQ', data[pos + 24:pos + 36]) + if timescale > 0 and duration > 0: + return duration / timescale + idx = pos + 4 + + +def _probe_video_header(path: Path, size: int) -> tuple[str, float, int | None, int | None]: + suffix = path.suffix.lower() + if suffix not in _MIME_BY_SUFFIX: + raise ProjectError('请选择受支持的视频格式(MP4、MOV、WebM)。', 422, code='invalid_input') + if shutil.which('ffprobe'): + facts = probe_file(path, 'video', include_container=True) + container = facts.get('container', '') + brand = facts.get('majorBrand', '') + mime = ( + 'video/webm' if container == 'matroska,webm' + else 'video/quicktime' if brand == 'qt' + else 'video/mp4' if 'mp4' in container + else _MIME_BY_SUFFIX[suffix] + ) + duration = facts.get('durationSeconds') + if not duration or duration <= 0: + raise ProjectError('无法读取视频有效时长,请更换视频文件。', 422, code='invalid_input') + return mime, float(duration), facts.get('width'), facts.get('height') + + # Lightweight fallback for environments without ffprobe: inspect head/tail boxes only (<= 512 KiB). + fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)) + try: + with os.fdopen(fd, 'rb') as stream: + head = stream.read(min(262144, size)) + duration = _parse_mvhd_duration(head) + if duration is None and size > 262144: + stream.seek(max(0, size - 262144)) + duration = _parse_mvhd_duration(stream.read(262144)) + except OSError as exc: + raise ProjectError('无法读取源视频文件头。', 409, code='linked_source_offline') from exc + if duration is None or duration <= 0: + raise ProjectError('视频探测需要安装 ffprobe,或使用包含标准 mvhd 头部的 MP4/MOV 文件。', 409, code='storage_unavailable') + return _MIME_BY_SUFFIX[suffix], float(duration), None, None + + +class SqliteLinkedSourceStore: + """Host-local SQLite store for bound single-file video sources.""" + + def __init__(self, state_dir: Path, *, io_timeout: float = DEFAULT_EXTERNAL_IO_TIMEOUT): + self.state_dir = Path(state_dir) + self.state_dir.mkdir(parents=True, exist_ok=True) + self.db_path = self.state_dir / 'linked-media.sqlite' + self.io_timeout = io_timeout + self._db_lock = Lock() + self._executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix='opendirector-linked-video') + with self._connect() as db: + db.executescript(_SCHEMA) + + @contextmanager + def _connect(self): + with self._db_lock: + conn = sqlite3.connect(self.db_path, timeout=10.0) + conn.row_factory = sqlite3.Row + try: + conn.execute('PRAGMA journal_mode=WAL') + conn.execute('PRAGMA busy_timeout=10000') + yield conn + conn.commit() + except BaseException: + conn.rollback() + raise + finally: + conn.close() + + def _run_io(self, fn, *, cleanup_late=None): + future = self._executor.submit(fn) + try: + return future.result(timeout=self.io_timeout) + except FutureTimeoutError: + if cleanup_late is not None: + def _close_late(done): + if not done.cancelled() and done.exception() is None: + try: + cleanup_late(done.result()) + except Exception: + pass + future.add_done_callback(_close_late) + raise ProjectError( + '读取外部视频超时,请检查挂载盘或网络连接。', + 409, + code='linked_source_offline', + ) from None + + @staticmethod + def _row_to_info(row: sqlite3.Row) -> LinkedVideoSourceInfo: + return LinkedVideoSourceInfo( + sourceId=UUID(row['source_id']), + projectId=UUID(row['project_id']), + title=row['title'], + mimeType=row['mime_type'], + size=row['size'], + modifiedAt=row['modified_at'], + durationSeconds=row['duration_seconds'], + width=row['width'], + height=row['height'], + ) + + def _get_row(self, project_id: UUID, source_id: UUID) -> sqlite3.Row | None: + with self._connect() as db: + return db.execute( + 'SELECT * FROM linked_video_sources WHERE project_id = ? AND source_id = ?', + (str(project_id), str(source_id)), + ).fetchone() + + def bind_video(self, project_id: UUID, file_path: str) -> LinkedVideoSourceInfo: + if not isinstance(file_path, str) or not file_path.strip() or '\x00' in file_path: + raise ProjectError('无效的视频文件路径。', 400, code='invalid_input') + path = Path(file_path) + if not path.is_absolute(): + raise ProjectError('绑定视频必须使用本机绝对路径。', 400, code='invalid_input') + + def _inspect(): + try: + if _is_file_symlink_or_reparse(path): + raise ProjectError('不支持直接绑定符号链接文件,请选择原始视频文件。', 400, code='invalid_input') + fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)) + try: + st = os.fstat(fd) + finally: + os.close(fd) + except FileNotFoundError: + raise ProjectError('所选视频文件不存在或挂载盘已断开。', 409, code='linked_source_offline') from None + except PermissionError: + raise ProjectError('没有读取所选视频文件的权限。', 403, code='linked_source_offline') from None + except OSError as exc: + raise ProjectError('无法访问所选视频文件,请检查挂载盘状态。', 409, code='linked_source_offline') from exc + if st.st_size <= 0: + raise ProjectError('所选视频文件为空。', 422, code='invalid_input') + mime, duration, width, height = _probe_video_header(path, st.st_size) + return st.st_size, st.st_mtime_ns, _iso_utc(st.st_mtime), mime, duration, width, height + + size, mtime_ns, modified_at, mime, duration, width, height = self._run_io(_inspect) + source_id = uuid4() + title = (path.name or 'video.mp4')[:255] + created_at = _utc_now() + + with self._connect() as db: + db.execute( + """ + INSERT INTO linked_video_sources ( + project_id, source_id, file_path, title, mime_type, + size, mtime_ns, modified_at, duration_seconds, width, height, created_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + str(project_id), str(source_id), str(path), title, mime, + size, mtime_ns, modified_at, duration, width, height, created_at, + ), + ) + + return LinkedVideoSourceInfo( + sourceId=source_id, + projectId=UUID(str(project_id)), + title=title, + mimeType=mime, + size=size, + modifiedAt=modified_at, + durationSeconds=duration, + width=width, + height=height, + ) + + def latest_for_project(self, project_id: UUID) -> LinkedVideoSourceInfo | None: + with self._connect() as db: + row = db.execute( + 'SELECT * FROM linked_video_sources WHERE project_id = ? ORDER BY created_at DESC LIMIT 1', + (str(project_id),), + ).fetchone() + return self._row_to_info(row) if row is not None else None + + def get_source(self, project_id: UUID, source_id: UUID) -> LinkedVideoSourceInfo | None: + row = self._get_row(project_id, source_id) + return self._row_to_info(row) if row is not None else None + + def inspect_availability( + self, project_id: UUID, source_id: UUID, + ) -> tuple[LinkedVideoSourceInfo | None, LinkedSourceAvailability, str | None, str | None]: + row = self._get_row(project_id, source_id) + if row is None: + return ( + None, + 'unbound', + 'linked_source_unbound', + '当前机器没有该外部视频的绑定授权,已保留片段与剪点记录。', + ) + info = self._row_to_info(row) + target = Path(row['file_path']) + expected_size = int(row['size']) + expected_mtime_ns = int(row['mtime_ns']) + + def _stat(): + if _is_file_symlink_or_reparse(target): + return 'offline', 'linked_source_offline', '源视频路径已变为符号链接,已暂停读取并保留剪点。' + fd = os.open(target, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)) + try: + st = os.fstat(fd) + finally: + os.close(fd) + if st.st_size != expected_size or st.st_mtime_ns != expected_mtime_ns: + return 'modified', 'linked_source_modified', '检测到源视频文件大小或修改时间发生变化,已暂停读取并保留剪点。' + return 'online', None, None + + try: + status, code, reason = self._run_io(_stat) + return info, status, code, reason + except ProjectError as exc: + return info, 'offline', exc.code, str(exc) + except (FileNotFoundError, PermissionError, OSError): + return ( + info, + 'offline', + 'linked_source_offline', + '源视频当前不可用(挂载盘已断开、文件已移走或无读取权限),已保留片段与剪点。', + ) + + def open_stream(self, project_id: UUID, source_id: UUID) -> tuple[BinaryIO, LinkedVideoSourceInfo]: + row = self._get_row(project_id, source_id) + if row is None: + raise ProjectError('当前机器未绑定该外部视频源。', 409, code='linked_source_unbound') + info = self._row_to_info(row) + target = Path(row['file_path']) + expected_size = int(row['size']) + expected_mtime_ns = int(row['mtime_ns']) + + def _open(): + try: + if _is_file_symlink_or_reparse(target): + raise ProjectError('源视频路径异常,已拒绝打开。', 409, code='linked_source_offline') + fd = os.open(target, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)) + stream = os.fdopen(fd, 'rb') + try: + st = os.fstat(stream.fileno()) + if st.st_size != expected_size or st.st_mtime_ns != expected_mtime_ns: + raise ProjectError( + '检测到源视频文件大小或修改时间发生变化,已阻止返回不一致的媒体字节。', + 409, + code='linked_source_modified', + ) + return stream + except BaseException: + stream.close() + raise + except ProjectError: + raise + except (FileNotFoundError, PermissionError, OSError) as exc: + raise ProjectError( + '源视频当前不可用(挂载盘已断开、文件已移走或无读取权限),已保留片段与剪点。', + 409, + code='linked_source_offline', + ) from exc + + stream = self._run_io(_open, cleanup_late=lambda handle: handle.close()) + return stream, info diff --git a/packages/core/src/opendirector/ports/gateway.py b/packages/core/src/opendirector/ports/gateway.py index 9b4a44a8d..d110296a3 100644 --- a/packages/core/src/opendirector/ports/gateway.py +++ b/packages/core/src/opendirector/ports/gateway.py @@ -62,6 +62,9 @@ def media_kind(self, mime: str, name: str = ''): def library_now(self) -> str: """UTC timestamp used by library mutations.""" + def linked_sources(self, state_dir: Path): + """Host-local store and read-only opener for bound external videos.""" + _ports: InfrastructurePorts | None = None diff --git a/packages/core/src/opendirector/ports/linked_draft.py b/packages/core/src/opendirector/ports/linked_draft.py new file mode 100644 index 000000000..9d09d32f0 --- /dev/null +++ b/packages/core/src/opendirector/ports/linked_draft.py @@ -0,0 +1,28 @@ +"""Host-local read-only port for single-file linked video bindings (§19).""" +from typing import BinaryIO, Protocol +from uuid import UUID + +from opendirector.domain.creation.linked_draft import ( + LinkedSourceAvailability, LinkedVideoSourceInfo, +) + + +class LinkedSourceStore(Protocol): + """Host-local persistence and read-only access for bound external videos.""" + + def bind_video(self, project_id: UUID, file_path: str) -> LinkedVideoSourceInfo: + """Probe a user-selected video file outside DB locks and record a host-local binding.""" + + def latest_for_project(self, project_id: UUID) -> LinkedVideoSourceInfo | None: + """Return the most recently bound source for a project on this host, if any.""" + + def get_source(self, project_id: UUID, source_id: UUID) -> LinkedVideoSourceInfo | None: + """Look up a specific bound source record on this host.""" + + def inspect_availability( + self, project_id: UUID, source_id: UUID, + ) -> tuple[LinkedVideoSourceInfo | None, LinkedSourceAvailability, str | None, str | None]: + """Check readability and (size, mtime) consistency outside DB locks with a timeout.""" + + def open_stream(self, project_id: UUID, source_id: UUID) -> tuple[BinaryIO, LinkedVideoSourceInfo]: + """Open a read-only binary stream after verifying availability and observed attributes.""" diff --git a/packages/core/src/opendirector/wiring.py b/packages/core/src/opendirector/wiring.py index 2a6037463..a036a3146 100644 --- a/packages/core/src/opendirector/wiring.py +++ b/packages/core/src/opendirector/wiring.py @@ -20,6 +20,7 @@ from opendirector.infrastructure.library_store import LibraryStore from opendirector.infrastructure.library_store import media_kind as library_media_kind from opendirector.infrastructure.library_store import now as library_timestamp +from opendirector.infrastructure.linked_sources import SqliteLinkedSourceStore from opendirector.infrastructure.local_projects import child as child_path from opendirector.infrastructure.local_projects import read_json as read_json_file from opendirector.infrastructure.local_projects import write_json as write_json_file @@ -30,6 +31,9 @@ class InfrastructureGateway: """Concrete adapters behind ``opendirector.ports.gateway``.""" + def __init__(self): + self._linked_stores: dict[Path, SqliteLinkedSourceStore] = {} + def child(self, directory: Path, name: str) -> Path: return child_path(directory, name) @@ -84,6 +88,14 @@ def media_kind(self, mime: str, name: str = ''): def library_now(self) -> str: return library_timestamp() + def linked_sources(self, state_dir: Path): + resolved = Path(state_dir).resolve() + store = self._linked_stores.get(resolved) + if store is None: + store = SqliteLinkedSourceStore(resolved) + self._linked_stores[resolved] = store + return store + def configure_runtime() -> InfrastructureGateway: """Bind ports and command dispatch. Safe to call more than once.""" diff --git a/scripts/build-desktop-local.ps1 b/scripts/build-desktop-local.ps1 new file mode 100644 index 000000000..3e363ae69 --- /dev/null +++ b/scripts/build-desktop-local.ps1 @@ -0,0 +1,177 @@ +[CmdletBinding()] +param( + [switch]$FrontendOnly, + [switch]$BackendOnly +) + +$ErrorActionPreference = 'Stop' + +if ($env:OS -ne 'Windows_NT') { + throw 'Run this script on Windows.' +} + +$repoRoot = Split-Path -Parent $PSScriptRoot +$desktop = Join-Path $repoRoot 'apps\desktop' +$mediaDir = Join-Path $repoRoot 'build\desktop-media' +$app = Join-Path $desktop 'build\win-unpacked\OpenDirector.exe' +$npm = (Get-Command npm.cmd -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source + +function Assert-UnpackedAppNotRunning { + param([string]$AppPath) + if (-not (Test-Path -LiteralPath $AppPath -PathType Leaf)) { + return + } + $resolvedApp = (Resolve-Path -LiteralPath $AppPath).Path + if (Get-Process -Name OpenDirector -ErrorAction SilentlyContinue | Where-Object Path -eq $resolvedApp) { + throw "Close the running unpacked OpenDirector application before updating or rebuilding: $resolvedApp" + } +} + +function Resolve-UnpackedSitePackages { + param([string]$AppPath) + $runtime = Join-Path (Split-Path -Parent $AppPath) 'resources\runtime' + $manifestPath = Join-Path $runtime 'manifest.json' + if (-not (Test-Path -LiteralPath $AppPath -PathType Leaf) -or + -not (Test-Path -LiteralPath $manifestPath -PathType Leaf)) { + throw 'The unpacked application is missing or incomplete. Run a full build first.' + } + + $manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json + $python = Join-Path $runtime $manifest.python + $sitePackages = Join-Path (Split-Path -Parent $python) 'Lib\site-packages' + if (-not (Test-Path -LiteralPath $sitePackages -PathType Container)) { + throw 'The unpacked runtime site-packages directory is missing. Run a full build first.' + } + + $resolvedApp = (Resolve-Path -LiteralPath $AppPath).Path + $unpacked = Split-Path -Parent $resolvedApp + $resolvedSitePackages = (Resolve-Path -LiteralPath $sitePackages).Path + if (-not $resolvedSitePackages.StartsWith($unpacked + '\', [StringComparison]::OrdinalIgnoreCase)) { + throw 'The unpacked site-packages directory is outside the unpacked application.' + } + + return @{ + App = $resolvedApp + SitePackages = $resolvedSitePackages + } +} + +function Sync-PackageTree { + param( + [string]$Source, + [string]$Destination, + [string[]]$ExcludeDirs = @('__pycache__') + ) + if (-not (Test-Path -LiteralPath $Source -PathType Container)) { + throw "Missing package source directory: $Source" + } + if (-not (Test-Path -LiteralPath $Destination -PathType Container)) { + throw "Missing target package directory in unpacked runtime: $Destination" + } + $args = @($Source, $Destination, '/MIR', '/FFT', '/R:2', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS', '/NP', '/XF', '*.pyc', '*.pyo') + if ($ExcludeDirs.Count -gt 0) { + $args += '/XD' + $args += $ExcludeDirs + } + & robocopy @args | Out-Null + if ($LASTEXITCODE -ge 8) { + throw "Failed to sync $Source -> $Destination (robocopy exit code $LASTEXITCODE)." + } +} + +function Update-UnpackedFrontend { + param([string]$SitePackages) + $webParent = Join-Path $SitePackages 'opendirector\_bundled' + $web = Join-Path $webParent 'web' + if (-not (Test-Path -LiteralPath (Join-Path $web 'index.html') -PathType Leaf)) { + throw 'The unpacked runtime has no bundled web application. Run a full build first.' + } + + & $npm run build --prefix $repoRoot + if ($LASTEXITCODE -ne 0) { throw 'Frontend build failed. The unpacked application was not updated.' } + + $dist = Join-Path $repoRoot 'dist' + if (-not (Test-Path -LiteralPath (Join-Path $dist 'index.html') -PathType Leaf)) { + throw 'The frontend build did not produce dist\index.html.' + } + + $suffix = [guid]::NewGuid().ToString('N') + $staged = Join-Path $webParent "web-next-$suffix" + $backup = Join-Path $webParent "web-old-$suffix" + try { + Copy-Item -LiteralPath $dist -Destination $staged -Recurse + Rename-Item -LiteralPath $web -NewName (Split-Path -Leaf $backup) + try { + Rename-Item -LiteralPath $staged -NewName 'web' + } catch { + Rename-Item -LiteralPath $backup -NewName 'web' + throw + } + Remove-Item -LiteralPath $backup -Recurse -Force + } finally { + if (Test-Path -LiteralPath $staged) { + Remove-Item -LiteralPath $staged -Recurse -Force + } + } +} + +function Update-UnpackedBackend { + param([string]$SitePackages) + # Preserve opendirector\_bundled (web, opencode binary, skills) while syncing Python sources. + Sync-PackageTree ` + -Source (Join-Path $repoRoot 'packages\core\src\opendirector') ` + -Destination (Join-Path $SitePackages 'opendirector') ` + -ExcludeDirs @('_bundled', '__pycache__') + Sync-PackageTree ` + -Source (Join-Path $repoRoot 'apps\api\src\opendirector_api') ` + -Destination (Join-Path $SitePackages 'opendirector_api') ` + -ExcludeDirs @('__pycache__') +} + +Assert-UnpackedAppNotRunning -AppPath $app + +if ($FrontendOnly -or $BackendOnly) { + $resolved = Resolve-UnpackedSitePackages -AppPath $app + $updated = @() + if ($FrontendOnly) { + Update-UnpackedFrontend -SitePackages $resolved.SitePackages + $updated += 'frontend' + } + if ($BackendOnly) { + Update-UnpackedBackend -SitePackages $resolved.SitePackages + $updated += 'backend' + } + Write-Output ("Updated ({0}). Restart: {1}" -f ($updated -join ' + '), $resolved.App) + return +} + +foreach ($tool in 'ffmpeg.exe', 'ffprobe.exe') { + $toolPath = Join-Path $mediaDir $tool + if (-not (Test-Path -LiteralPath $toolPath -PathType Leaf)) { + throw "Missing $toolPath. Put the standalone Windows binaries in build\desktop-media." + } +} + +$previousMediaDir = $env:OPENDIRECTOR_FFMPEG_DIR +$previousSigningDiscovery = $env:CSC_IDENTITY_AUTO_DISCOVERY +try { + $env:OPENDIRECTOR_FFMPEG_DIR = $mediaDir + $env:CSC_IDENTITY_AUTO_DISCOVERY = 'false' + + if (-not (Test-Path -LiteralPath (Join-Path $desktop 'node_modules\.bin\electron-builder.cmd') -PathType Leaf)) { + & $npm ci --prefix $desktop + if ($LASTEXITCODE -ne 0) { throw 'Desktop dependency installation failed.' } + } + + & $npm run prepare:runtime --prefix $desktop + if ($LASTEXITCODE -ne 0) { throw 'Runtime build failed. Packaging was skipped.' } + + & $npm run pack --prefix $desktop + if ($LASTEXITCODE -ne 0) { throw 'Windows unpacked build failed.' } + if (-not (Test-Path -LiteralPath $app -PathType Leaf)) { throw "Expected desktop application at $app." } + + Write-Output "Windows application: $app" +} finally { + $env:OPENDIRECTOR_FFMPEG_DIR = $previousMediaDir + $env:CSC_IDENTITY_AUTO_DISCOVERY = $previousSigningDiscovery +} diff --git a/src/backend/linkedDraftClient.ts b/src/backend/linkedDraftClient.ts new file mode 100644 index 000000000..19a8bafe0 --- /dev/null +++ b/src/backend/linkedDraftClient.ts @@ -0,0 +1,74 @@ +import { request } from "./api.ts"; +import type { DesktopLinkedVideoSource } from "../desktop.ts"; + +export type LinkedSourceAvailability = + | "online" + | "offline" + | "modified" + | "unbound"; + +export interface LinkedClipDraft { + schemaVersion: 1; + timelineId: string; + clipId: string; + sourceId: string; + title: string; + durationSeconds: number; + start: number; + inPoint: number; + outPoint: number; + revision: number; +} + +export interface LinkedClipSaveInput { + timelineId: string; + clipId: string; + sourceId: string; + title: string; + durationSeconds: number; + start: number; + inPoint: number; + outPoint: number; + expectedRevision: number; +} + +export interface LinkedDraftView { + projectId: string; + source: DesktopLinkedVideoSource | null; + availability: LinkedSourceAvailability; + reasonCode?: string | null; + reason?: string | null; + clip?: LinkedClipDraft | null; +} + +export function linkedSourceContentUrl(projectId: string, sourceId: string, reload = 0): string { + const url = `/api/creation/projects/${encodeURIComponent(projectId)}/linked-sources/${encodeURIComponent(sourceId)}/content`; + return reload > 0 ? `${url}?reload=${reload}` : url; +} + +export function getLinkedDraft( + projectId: string, + options?: AbortSignal | { sourceId?: string; signal?: AbortSignal }, +): Promise { + const signal = options instanceof AbortSignal ? options : options?.signal; + const sourceId = options instanceof AbortSignal ? undefined : options?.sourceId; + const query = sourceId ? `?sourceId=${encodeURIComponent(sourceId)}` : ""; + return request( + `/creation/projects/${encodeURIComponent(projectId)}/linked-draft${query}`, + { method: "GET", signal }, + ); +} + +export function saveLinkedDraft( + projectId: string, + payload: LinkedClipSaveInput, +): Promise { + return request( + `/creation/projects/${encodeURIComponent(projectId)}/linked-draft`, + { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload), + }, + ); +} diff --git a/src/canvas/LinkedVideoDraftPanel.tsx b/src/canvas/LinkedVideoDraftPanel.tsx new file mode 100644 index 000000000..0ac03a52b --- /dev/null +++ b/src/canvas/LinkedVideoDraftPanel.tsx @@ -0,0 +1,607 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { ApiError } from "../backend/api.ts"; +import { useI18n } from "../i18n/I18nProvider.tsx"; +import type { DesktopLinkedVideoSource } from "../desktop.ts"; +import { + getLinkedDraft, + linkedSourceContentUrl, + saveLinkedDraft, + type LinkedClipDraft, + type LinkedDraftView, + type LinkedSourceAvailability, +} from "../backend/linkedDraftClient.ts"; +import { CanvasIcon } from "./CanvasIcon.tsx"; +import { EditorModal } from "./EditorModal.tsx"; +import { + createLinkedPreviewController, + formatPreviewClock, + validateDraftTimelineScope, + type ClipRangeBounds, + type LinkedPreviewController, + type LinkedPreviewSnapshot, +} from "./linkedDraftController.ts"; +import { TimelineEditor } from "./TimelineEditor.tsx"; +import type { CanvasNode, CanvasResource, TimelineData } from "./model.ts"; + +export interface LinkedVideoDraftPanelProps { + projectId: string; + readOnly: boolean; + onRequestEdit?: () => void; + initialDraft: LinkedDraftView | null; + onDraftChange: (next: LinkedDraftView) => void; + onClose: () => void; +} + +function buildAdapterNode( + source: DesktopLinkedVideoSource, + savedClip: LinkedClipDraft | null, + fallbackIds: { timelineId: string; clipId: string }, + streamUrl: string, +): CanvasNode { + const matchingClip = + savedClip && savedClip.sourceId === source.sourceId ? savedClip : null; + const timelineId = matchingClip?.timelineId ?? fallbackIds.timelineId; + const clipId = matchingClip?.clipId ?? fallbackIds.clipId; + const duration = matchingClip?.durationSeconds ?? source.durationSeconds; + const inPoint = matchingClip?.inPoint ?? 0; + const outPoint = matchingClip?.outPoint ?? duration; + + const resource: CanvasResource = { + id: source.sourceId, + kind: "video", + title: source.title, + src: streamUrl, + mimeType: source.mimeType, + byteSize: source.size, + durationSeconds: duration, + }; + + const timeline: TimelineData = { + fps: 30, + width: source.width ?? 1920, + height: source.height ?? 1080, + importedAssets: [resource], + tracks: [ + { + id: "visual", + kind: "visual", + title: "", + muted: false, + clips: [ + { + id: clipId, + resource, + inPoint, + outPoint, + speed: 1, + volume: 1, + muted: false, + }, + ], + }, + ], + }; + + return { + id: timelineId, + type: "timeline", + position: { x: 0, y: 0 }, + width: 360, + height: 240, + data: { + kind: "timeline", + title: source.title, + prompt: "", + timeline, + }, + }; +} + +export function LinkedVideoDraftPanel({ + projectId, + readOnly, + onRequestEdit, + initialDraft, + onDraftChange, + onClose, +}: LinkedVideoDraftPanelProps) { + const { t } = useI18n(); + const [draft, setDraft] = useState(initialDraft); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [editingSession, setEditingSession] = useState<{ + node: CanvasNode; + source: DesktopLinkedVideoSource; + } | null>(null); + const [reloadSeq, setReloadSeq] = useState(0); + const [videoElement, setVideoElement] = useState(null); + const [timelineSnapshot, setTimelineSnapshot] = + useState(null); + + const mountedRef = useRef(true); + const checkAbortRef = useRef(null); + const controllerRef = useRef(null); + const appliedRestoreKeyRef = useRef(null); + + const fallbackIdsRef = useRef<{ + sourceId: string; + timelineId: string; + clipId: string; + } | null>(null); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + checkAbortRef.current?.abort(); + controllerRef.current?.dispose(); + controllerRef.current = null; + appliedRestoreKeyRef.current = null; + }; + }, []); + + const savedClip = draft?.clip ?? null; + const activeSource = draft?.source ?? null; + const activeClip = + savedClip && + activeSource && + savedClip.sourceId === activeSource.sourceId && + savedClip.outPoint > savedClip.inPoint + ? savedClip + : null; + const availability: LinkedSourceAvailability = draft?.availability ?? "unbound"; + const statusReason = draft?.reason; + + const activeClipBounds = useMemo(() => { + if (!activeClip) return null; + return { + inPoint: activeClip.inPoint, + outPoint: activeClip.outPoint, + sourceDuration: activeSource?.durationSeconds ?? activeClip.durationSeconds, + }; + }, [ + activeClip?.inPoint, + activeClip?.outPoint, + activeClip?.durationSeconds, + activeSource?.durationSeconds, + ]); + + const activeClipBoundsRef = useRef(activeClipBounds); + activeClipBoundsRef.current = activeClipBounds; + + useEffect(() => { + if (!videoElement) { + controllerRef.current?.dispose(); + controllerRef.current = null; + appliedRestoreKeyRef.current = null; + setTimelineSnapshot(null); + return; + } + + const controller = createLinkedPreviewController( + videoElement, + activeClipBoundsRef.current, + (nextSnapshot) => { + if (mountedRef.current) { + setTimelineSnapshot(nextSnapshot); + } + }, + ); + controllerRef.current = controller; + setTimelineSnapshot(controller.getSnapshot()); + + return () => { + controller.dispose(); + if (controllerRef.current === controller) { + controllerRef.current = null; + } + appliedRestoreKeyRef.current = null; + }; + }, [videoElement]); + + const restoreKey = activeClip + ? `${activeClip.sourceId}:${activeClip.revision}:${activeClip.inPoint}:${activeClip.outPoint}` + : null; + + useEffect(() => { + const controller = controllerRef.current; + if (!controller || !videoElement) return; + controller.syncClip(activeClipBounds); + + if (activeClip && restoreKey) { + if (appliedRestoreKeyRef.current !== restoreKey) { + appliedRestoreKeyRef.current = restoreKey; + controller.restoreToInPoint(activeClip.inPoint); + } + } else { + appliedRestoreKeyRef.current = null; + controller.cancelPendingRestore(); + } + }, [videoElement, activeClip, activeClipBounds, restoreKey]); + + const getStableIds = (sourceId: string) => { + if (!fallbackIdsRef.current || fallbackIdsRef.current.sourceId !== sourceId) { + fallbackIdsRef.current = { + sourceId, + timelineId: `tl-${sourceId.slice(0, 8)}`, + clipId: `clip-${crypto.randomUUID().slice(0, 8)}`, + }; + } + return fallbackIdsRef.current; + }; + + const recheckSource = useCallback( + async (forceReload = false, targetSourceId?: string) => { + checkAbortRef.current?.abort(); + const controller = new AbortController(); + checkAbortRef.current = controller; + setBusy(true); + setError(""); + try { + const latest = await getLinkedDraft(projectId, { + sourceId: targetSourceId, + signal: controller.signal, + }); + if (!mountedRef.current || controller.signal.aborted) return; + setDraft(latest); + if (forceReload) { + setReloadSeq((seq) => seq + 1); + } + onDraftChange(latest); + } catch (reason) { + if (!mountedRef.current || controller.signal.aborted) return; + setError(reason instanceof Error ? reason.message : String(reason)); + } finally { + if (mountedRef.current && checkAbortRef.current === controller) { + setBusy(false); + } + } + }, + [projectId, onDraftChange], + ); + + useEffect(() => { + void recheckSource(false); + }, [recheckSource]); + + const pickVideo = async () => { + if (!window.opendirectorDesktop?.pickLinkedVideo || savedClip || busy || readOnly) return; + setBusy(true); + setError(""); + try { + const picked = await window.opendirectorDesktop.pickLinkedVideo(projectId); + if (!mountedRef.current || !picked) return; + if (!picked.ok) { + setError(picked.message); + return; + } + controllerRef.current?.cancelPendingRestore(); + const nextView: LinkedDraftView = { + projectId, + source: picked.source, + availability: "online", + clip: null, + }; + setDraft(nextView); + setReloadSeq((seq) => seq + 1); + onDraftChange(nextView); + } catch (reason) { + if (!mountedRef.current) return; + setError(reason instanceof Error ? reason.message : String(reason)); + } finally { + if (mountedRef.current) { + setBusy(false); + } + }; + }; + + const openTimelineEditor = async () => { + if (!activeSource || busy || readOnly) return; + const targetSourceId = activeSource.sourceId; + checkAbortRef.current?.abort(); + const controller = new AbortController(); + checkAbortRef.current = controller; + setBusy(true); + setError(""); + try { + const checked = await getLinkedDraft(projectId, { + sourceId: targetSourceId, + signal: controller.signal, + }); + if (!mountedRef.current || controller.signal.aborted) return; + + setDraft(checked); + onDraftChange(checked); + if (checked.availability === "online" && checked.source?.sourceId === targetSourceId) { + controllerRef.current?.cancelPendingRestore(); + const node = buildAdapterNode( + checked.source, + checked.clip ?? null, + getStableIds(checked.source.sourceId), + linkedSourceContentUrl(projectId, targetSourceId, reloadSeq), + ); + setEditingSession({ node, source: checked.source }); + } + } catch (reason) { + if (!mountedRef.current || controller.signal.aborted) return; + setError(reason instanceof Error ? reason.message : String(reason)); + } finally { + if (mountedRef.current && checkAbortRef.current === controller) { + setBusy(false); + } + } + }; + + if (editingSession) { + const sessionSource = editingSession.source; + return ( + { + setEditingSession(null); + }} + onRender={() => false} + onApply={async (nextTimeline) => { + if (readOnly) { + throw new Error(t("linkedDraft.error.readOnly")); + } + const scope = validateDraftTimelineScope( + nextTimeline, + sessionSource.sourceId, + ); + if (!scope.ok) { + throw new Error( + t( + scope.code === "singleClipRequired" + ? "linkedDraft.error.singleClipRequired" + : "linkedDraft.error.unsupportedDraftEdits", + ), + ); + } + const { clip } = scope; + const expectedRevision = draft?.clip?.revision ?? 0; + try { + const saved = await saveLinkedDraft(projectId, { + timelineId: editingSession.node.id, + clipId: clip.id, + sourceId: sessionSource.sourceId, + title: sessionSource.title, + durationSeconds: sessionSource.durationSeconds, + start: 0, + inPoint: clip.inPoint, + outPoint: Math.min(clip.outPoint, sessionSource.durationSeconds), + expectedRevision, + }); + setDraft(saved); + onDraftChange(saved); + return true; + } catch (reason) { + if ( + reason instanceof ApiError && + reason.code.startsWith("linked_source_") + ) { + throw new Error( + t("linkedDraft.error.saveRestoreSource", { + detail: reason.message, + }), + ); + } + throw reason; + } + }} + /> + ); + } + + const statusLabel = + availability === "online" + ? t("linkedDraft.status.online") + : availability === "offline" + ? t("linkedDraft.status.offline") + : availability === "modified" + ? t("linkedDraft.status.modified") + : t("linkedDraft.status.unbound"); + + const streamUrl = + activeSource && availability === "online" + ? linkedSourceContentUrl(projectId, activeSource.sourceId, reloadSeq) + : undefined; + + const savedClipOffline = Boolean(savedClip && availability !== "online"); + const hasAnySourceOrClip = Boolean(activeSource || savedClip); + const canEdit = Boolean(streamUrl); + + const clipDuration = activeClip ? activeClip.outPoint - activeClip.inPoint : 0; + const clipTime = Math.min(clipDuration, timelineSnapshot?.clipTime ?? 0); + const clockOptions = { forceHours: clipDuration >= 3600, subSecond: clipDuration < 1 }; + const clipTimeReadout = t("linkedDraft.clipTimeline.timeReadout", { + current: formatPreviewClock(clipTime, clockOptions), + total: formatPreviewClock(clipDuration, clockOptions), + }); + const clipPlaying = timelineSnapshot?.isClipPlaying ?? false; + + return ( + + {!savedClip && ( + + )} + {hasAnySourceOrClip && ( + + )} + + } + onApply={canEdit ? () => void openTimelineEditor() : undefined} + applyLabel={t(savedClip ? "linkedDraft.action.editInTimeline" : "linkedDraft.action.addToTimeline")} + disabled={busy || readOnly} + > +
+
+ + {statusLabel} + + +
+ + {readOnly && ( +
+ {t("linkedDraft.error.readOnly")} + {onRequestEdit && ( + + )} +
+ )} + + {statusReason && availability !== "online" && ( +
+ {statusReason} + {savedClipOffline && savedClip && ( + + {t("linkedDraft.hint.recheckOriginal", { + inPoint: savedClip.inPoint.toFixed(2), + })} + + )} +
+ )} + + {hasAnySourceOrClip ? ( +
+ {activeSource?.title ?? savedClip?.title} + {savedClip && !streamUrl && ( +

{t("linkedDraft.meta.trimValue", { + inPoint: savedClip.inPoint.toFixed(2), + outPoint: savedClip.outPoint.toFixed(2), + clipDuration: (savedClip.outPoint - savedClip.inPoint).toFixed(2), + })}

+ )} + {!savedClip &&

{t("linkedDraft.meta.unsavedHint")}

} +
+ ) : ( +

{t("linkedDraft.empty.hint")}

+ )} + + {streamUrl && activeSource && ( +
+
+ )} +
+
+ ); +} diff --git a/src/canvas/linkedDraftController.ts b/src/canvas/linkedDraftController.ts new file mode 100644 index 000000000..1e969b7a4 --- /dev/null +++ b/src/canvas/linkedDraftController.ts @@ -0,0 +1,578 @@ +import type { TimelineClip, TimelineData } from "./model.ts"; + +export interface MediaRestoreTarget { + readyState: number; + currentTime: number; + seeking: boolean; + paused?: boolean; + pause(): void; + addEventListener( + type: string, + listener: () => void, + options?: { once?: boolean }, + ): void; + removeEventListener(type: string, listener: () => void): void; +} + +export interface MediaPreviewPlayer extends MediaRestoreTarget { + duration: number; + paused: boolean; + ended: boolean; + play(): Promise | void; +} + + +export interface ClipRangeBounds { + inPoint: number; + outPoint: number; + sourceDuration?: number; +} + +export interface LinkedPreviewSnapshot { + clipTime: number; + isClipPlaying: boolean; +} + +export interface LinkedPreviewController { + getSnapshot(): LinkedPreviewSnapshot | null; + syncClip(nextClip: ClipRangeBounds | null): void; + restoreToInPoint(inPoint: number): void; + cancelPendingRestore(): void; + toggleClipPlayback(): void; + beginClipScrub(): void; + scrubClipTo(clipOffsetSeconds: number): void; + endClipScrub(): void; + dispose(): void; +} + +const RANGE_EPSILON = 1e-3; +const SEEK_MATCH_TOLERANCE = 0.5; + +export type DraftTimelineScopeCheck = + | { ok: true; clip: TimelineClip } + | { ok: false; code: "singleClipRequired" | "unsupportedDraftEdits" }; + +/** + * Validate that the edited timeline stays within Section 19's single-clip Draft + * persistence scope, rejecting unsupported edits rather than silently dropping them. + */ +export function validateDraftTimelineScope( + timeline: TimelineData, + expectedSourceId: string, +): DraftTimelineScopeCheck { + const visualTracks = timeline.tracks.filter((track) => track.kind === "visual"); + const visualClips = visualTracks.flatMap((track) => track.clips); + if ( + visualClips.length !== 1 || + visualClips[0]!.resource.id !== expectedSourceId + ) { + return { ok: false, code: "singleClipRequired" }; + } + const clip = visualClips[0]!; + const hasOverlaysOrFonts = Boolean( + timeline.overlays?.length || timeline.fonts?.length, + ); + const hasTrackMute = visualTracks.some((track) => track.muted); + const hasClipAdjustments = + Math.abs(clip.speed - 1) > 1e-6 || + Math.abs(clip.volume - 1) > 1e-6 || + clip.muted; + + if ( + timeline.fps !== 30 || + timeline.tracks.length !== 1 || + timeline.importedAssets?.some((asset) => asset.id !== expectedSourceId) || + hasOverlaysOrFonts || + hasTrackMute || + hasClipAdjustments + ) { + return { ok: false, code: "unsupportedDraftEdits" }; + } + return { ok: true, clip }; +} + +/** + * Format media clock in MM:SS (or HH:MM:SS when >= 1 hour). + * Adds 1ms tolerance before flooring so demuxed timestamps like 3.99999s render as 00:04. + */ +export function formatPreviewClock( + seconds: number, + options?: { forceHours?: boolean; subSecond?: boolean }, +): string { + const safe = Number.isFinite(seconds) ? Math.max(0, seconds) : 0; + if (options?.subSecond) { + const tenths = Math.round(safe * 10) / 10; + const mins = Math.floor(tenths / 60); + const rem = (tenths - mins * 60).toFixed(1).padStart(4, "0"); + return `${String(mins).padStart(2, "0")}:${rem}`; + } + const whole = Math.floor(safe + RANGE_EPSILON); + const hours = Math.floor(whole / 3600); + const minutes = Math.floor((whole % 3600) / 60); + const secs = whole % 60; + if (hours > 0 || options?.forceHours) { + return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`; + } + return `${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`; +} + +function deriveLinkedPreviewSnapshot(input: { + clip: ClipRangeBounds; + sourceTime: number; + paused: boolean; + ended: boolean; + mediaDuration?: number; +}): LinkedPreviewSnapshot { + const inPoint = Math.max(0, input.clip.inPoint); + const outPoint = Math.max(inPoint, input.clip.outPoint); + const clipDuration = Math.max(0, outPoint - inPoint); + const rawTime = Number.isFinite(input.sourceTime) + ? Math.max(0, input.sourceTime) + : 0; + const effectiveMediaDuration = + Number.isFinite(input.mediaDuration) && (input.mediaDuration ?? 0) > 0 + ? input.mediaDuration! + : input.clip.sourceDuration; + + const endedAtClipTail = + input.ended && + effectiveMediaDuration !== undefined && + outPoint >= effectiveMediaDuration - 0.25 && + rawTime >= inPoint - RANGE_EPSILON; + + const effectiveSourceTime = endedAtClipTail ? Math.max(rawTime, outPoint) : rawTime; + return { + clipTime: Math.min(clipDuration, Math.max(0, effectiveSourceTime - inPoint)), + isClipPlaying: !input.paused && !input.ended, + }; +} + +/** + * Pause player once ready, seek to saved `inPoint`, confirm arrival on `seeked`, + * keep playback paused, and detach all listeners after this single restoration. + */ +export function bindOneShotInPointRestore( + player: MediaRestoreTarget, + inPoint: number, + onComplete?: () => void, + onBeforeProgrammaticSeek?: (target: number) => void, +): () => void { + const target = Math.max(0, inPoint); + let disposed = false; + let retries = 0; + + const finish = (completed: boolean) => { + if (disposed) return; + disposed = true; + player.removeEventListener("loadedmetadata", onMetadata); + player.removeEventListener("canplay", onCanPlay); + player.removeEventListener("seeked", onSeeked); + player.removeEventListener("pointerdown", onUserControl); + player.removeEventListener("keydown", onUserControl); + player.removeEventListener("play", onUserControl); + if (completed) { + onComplete?.(); + } + }; + + const cleanup = () => finish(false); + const onUserControl = () => finish(true); + + const onSeeked = () => { + if (disposed) return; + if (Math.abs(player.currentTime - target) <= 0.25) { + player.pause(); + finish(true); + } + }; + + const performSeek = () => { + if (disposed || player.readyState < 1) return; + player.pause(); + if (Math.abs(player.currentTime - target) <= 0.05 && !player.seeking) { + player.pause(); + finish(true); + return; + } + onBeforeProgrammaticSeek?.(target); + player.currentTime = target; + }; + + const onMetadata = () => { + performSeek(); + }; + + const onCanPlay = () => { + if (disposed) return; + if (Math.abs(player.currentTime - target) <= 0.25 && !player.seeking) { + player.pause(); + finish(true); + return; + } + if (retries < 2) { + retries += 1; + performSeek(); + } + }; + + player.addEventListener("pointerdown", onUserControl); + player.addEventListener("keydown", onUserControl); + player.addEventListener("play", onUserControl); + player.addEventListener("seeked", onSeeked); + player.addEventListener("canplay", onCanPlay); + + if (player.readyState >= 1) { + performSeek(); + } else { + player.addEventListener("loadedmetadata", onMetadata); + } + + return cleanup; +} + +function replayBoundaryEpsilon(clip: ClipRangeBounds): number { + const duration = Math.max(0, clip.outPoint - clip.inPoint); + return Math.min(0.05, duration * 0.25); +} + +/** + * Keep saved-clip playback within its source bounds using the media clock. + */ +export function createLinkedPreviewController( + player: MediaPreviewPlayer, + initialClip: ClipRangeBounds | null, + onChange?: (snapshot: LinkedPreviewSnapshot | null) => void, +): LinkedPreviewController { + let clip: ClipRangeBounds | null = initialClip; + let disposed = false; + let scrubbing = false; + let resumeClipAfterScrub = false; + let pendingProgrammaticPlay = false; + let programmaticSeek: { active: boolean; target: number } = { + active: false, + target: 0, + }; + let deferredSeekTarget: number | null = null; + let pendingRestore: { inPoint: number; cleanup: () => void } | null = null; + + const clampTargetTime = (targetSeconds: number): number => { + const nonNegative = Math.max(0, targetSeconds); + if (Number.isFinite(player.duration) && player.duration > 0) { + return Math.min(nonNegative, player.duration); + } + if (clip?.sourceDuration && Number.isFinite(clip.sourceDuration)) { + return Math.min(nonNegative, clip.sourceDuration); + } + return nonNegative; + }; + + const computeSnapshot = (): LinkedPreviewSnapshot | null => { + if (!clip || clip.outPoint <= clip.inPoint) { + return null; + } + const waitingInitialRestore = pendingRestore !== null; + const effectiveSourceTime = waitingInitialRestore + ? pendingRestore!.inPoint + : deferredSeekTarget !== null && player.readyState < 1 + ? deferredSeekTarget + : player.currentTime; + return deriveLinkedPreviewSnapshot({ + clip, + sourceTime: effectiveSourceTime, + paused: waitingInitialRestore ? true : Boolean(player.paused), + ended: waitingInitialRestore ? false : Boolean(player.ended), + mediaDuration: player.duration, + }); + }; + + const emit = () => { + if (disposed) return; + onChange?.(computeSnapshot()); + }; + + const cancelPendingRestore = () => { + if (!pendingRestore) return; + const current = pendingRestore; + pendingRestore = null; + current.cleanup(); + }; + + const programmaticSeekTo = (targetSeconds: number) => { + const clamped = clampTargetTime(targetSeconds); + if (player.readyState < 1) { + deferredSeekTarget = clamped; + return; + } + deferredSeekTarget = null; + if (Math.abs(player.currentTime - clamped) > 1e-4) { + programmaticSeek = { active: true, target: clamped }; + player.currentTime = clamped; + } else if (!player.seeking) { + programmaticSeek = { active: false, target: clamped }; + } + }; + + const requestProgrammaticPlay = () => { + pendingProgrammaticPlay = true; + try { + const maybePromise = player.play(); + if (maybePromise && typeof maybePromise.catch === "function") { + maybePromise.catch(() => { + pendingProgrammaticPlay = false; + emit(); + }); + } + } catch { + pendingProgrammaticPlay = false; + } + }; + + const pauseAtOutPoint = (activeClip: ClipRangeBounds) => { + pendingProgrammaticPlay = false; + player.pause(); + if (player.currentTime > activeClip.outPoint + 1e-4) { + programmaticSeekTo(activeClip.outPoint); + } + emit(); + }; + + const onPlay = () => { + if (disposed) return; + if (pendingProgrammaticPlay) { + pendingProgrammaticPlay = false; + } else { + cancelPendingRestore(); + } + emit(); + }; + + const onPause = () => { + if (disposed) return; + emit(); + }; + + const onEnded = () => { + if (disposed) return; + pendingProgrammaticPlay = false; + emit(); + }; + + const onSeeking = () => { + if (disposed) return; + const matchesProgrammatic = + programmaticSeek.active && + Math.abs(player.currentTime - programmaticSeek.target) <= + SEEK_MATCH_TOLERANCE; + if (!matchesProgrammatic) { + programmaticSeek = { active: false, target: 0 }; + deferredSeekTarget = null; + cancelPendingRestore(); + if (clip) { + programmaticSeekTo(Math.min(clip.outPoint, Math.max(clip.inPoint, player.currentTime))); + } + } + emit(); + }; + + const onSeeked = () => { + if (disposed) return; + if (!player.seeking) { + programmaticSeek = { active: false, target: 0 }; + } + if ( + !scrubbing && + clip && + !player.paused && + player.currentTime >= clip.outPoint + ) { + pauseAtOutPoint(clip); + return; + } + emit(); + }; + + const onTimeUpdate = () => { + if (disposed) return; + if ( + !scrubbing && + clip && + !player.paused && + player.currentTime >= clip.outPoint + ) { + pauseAtOutPoint(clip); + return; + } + emit(); + }; + + const onLoadedMetadata = () => { + if (disposed) return; + if (deferredSeekTarget !== null && player.readyState >= 1) { + const target = deferredSeekTarget; + deferredSeekTarget = null; + programmaticSeekTo(target); + } + emit(); + }; + + const events: ReadonlyArray<[string, () => void]> = [ + ["play", onPlay], + ["pause", onPause], + ["ended", onEnded], + ["seeking", onSeeking], + ["seeked", onSeeked], + ["timeupdate", onTimeUpdate], + ["loadedmetadata", onLoadedMetadata], + ["durationchange", onLoadedMetadata], + ]; + + for (const [type, listener] of events) { + player.addEventListener(type, listener); + } + + return { + getSnapshot: computeSnapshot, + + syncClip(nextClip: ClipRangeBounds | null) { + if (disposed) return; + clip = nextClip && nextClip.outPoint > nextClip.inPoint ? nextClip : null; + if (!clip) { + scrubbing = false; + resumeClipAfterScrub = false; + } else if ( + !scrubbing && + !player.paused && + player.currentTime >= clip.outPoint + ) { + pauseAtOutPoint(clip); + return; + } + emit(); + }, + + restoreToInPoint(inPoint: number) { + if (disposed) return; + cancelPendingRestore(); + scrubbing = false; + resumeClipAfterScrub = false; + pendingProgrammaticPlay = false; + deferredSeekTarget = null; + const target = Math.max(0, inPoint); + let restoreCompleted = false; + const cleanup = bindOneShotInPointRestore( + player, + target, + () => { + restoreCompleted = true; + pendingRestore = null; + emit(); + }, + (seekTarget) => { + programmaticSeek = { active: true, target: clampTargetTime(seekTarget) }; + }, + ); + if (!restoreCompleted) { + pendingRestore = { inPoint: target, cleanup }; + } + emit(); + }, + + cancelPendingRestore, + + toggleClipPlayback() { + if (disposed || !clip || clip.outPoint <= clip.inPoint) return; + cancelPendingRestore(); + if (!player.paused && !player.ended) { + pendingProgrammaticPlay = false; + player.pause(); + emit(); + return; + } + + const endEps = replayBoundaryEpsilon(clip); + const shouldRestartAtInPoint = + player.ended || + player.currentTime < clip.inPoint - RANGE_EPSILON || + player.currentTime >= clip.outPoint - endEps; + + if (shouldRestartAtInPoint) { + programmaticSeekTo(clip.inPoint); + } + if (player.paused || player.ended) { + requestProgrammaticPlay(); + } + emit(); + }, + + beginClipScrub() { + if (disposed || !clip || clip.outPoint <= clip.inPoint) return; + cancelPendingRestore(); + scrubbing = true; + resumeClipAfterScrub = !player.paused && !player.ended; + }, + + scrubClipTo(clipOffsetSeconds: number) { + if (disposed || !clip || clip.outPoint <= clip.inPoint) return; + cancelPendingRestore(); + const clipDuration = Math.max(0, clip.outPoint - clip.inPoint); + const clampedOffset = Math.min( + clipDuration, + Math.max(0, Number.isFinite(clipOffsetSeconds) ? clipOffsetSeconds : 0), + ); + const targetSourceTime = clip.inPoint + clampedOffset; + + if (!scrubbing) { + const wasPlaying = !player.paused && !player.ended; + if (wasPlaying) { + const endEps = replayBoundaryEpsilon(clip); + if (targetSourceTime >= clip.outPoint - endEps) { + programmaticSeekTo(clip.outPoint); + pauseAtOutPoint(clip); + return; + } + } + programmaticSeekTo(targetSourceTime); + emit(); + return; + } + + if (!resumeClipAfterScrub && !player.paused) { + player.pause(); + } + programmaticSeekTo(targetSourceTime); + emit(); + }, + + endClipScrub() { + if (!scrubbing || disposed) return; + scrubbing = false; + const shouldResume = resumeClipAfterScrub; + resumeClipAfterScrub = false; + if (shouldResume && clip && clip.outPoint > clip.inPoint) { + const endEps = replayBoundaryEpsilon(clip); + const currentTarget = + deferredSeekTarget !== null ? deferredSeekTarget : player.currentTime; + if (currentTarget >= clip.outPoint - endEps) { + pauseAtOutPoint(clip); + return; + } + if (player.paused || player.ended) { + requestProgrammaticPlay(); + } + } + emit(); + }, + + dispose() { + if (disposed) return; + disposed = true; + cancelPendingRestore(); + deferredSeekTarget = null; + pendingProgrammaticPlay = false; + programmaticSeek = { active: false, target: 0 }; + for (const [type, listener] of events) { + player.removeEventListener(type, listener); + } + }, + }; +} diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index e617abdc8..4bcd5064a 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -98,7 +98,9 @@ import { subjectImportSelection, subjectTargetIdentity } from "../subjectLibrary import { TextNodeComposer } from "../TextNodeComposer"; import "../themes.css"; +import { LinkedVideoDraftPanel } from "../LinkedVideoDraftPanel.tsx"; import { TimelineEditor } from "../TimelineEditor"; +import { getLinkedDraft, type LinkedDraftView } from "../../backend/linkedDraftClient.ts"; import { TimelineOutputShortcut, useTimelineOutput } from "../TimelineOutput"; import { CANVAS_TOOLS, createCanvasToolTask, initialToolParameters } from "../toolCatalog"; @@ -506,6 +508,19 @@ export function WorkspaceView({ rt, editingState, editSession }: { }, [doc.id, doc.nodes]); const desktop = !!window.opendirectorDesktop; + const [linkedDraftOpen, setLinkedDraftOpen] = useState(false); + const [linkedDraftView, setLinkedDraftView] = useState(null); + useEffect(() => { + if (!desktop || !ready) return; + const controller = new AbortController(); + setLinkedDraftView(null); + void getLinkedDraft(doc.id, controller.signal) + .then((view) => { + if (!controller.signal.aborted) setLinkedDraftView(view); + }) + .catch(() => {}); + return () => controller.abort(); + }, [desktop, ready, doc.id]); const [desktopSidebarOpen, setDesktopSidebarOpen] = useState(() => { try { return desktop && localStorage.getItem("opendirector.desktop.sidebar.v1") === "open"; } catch { return false; } @@ -1226,6 +1241,15 @@ export function WorkspaceView({ rt, editingState, editSession }: { size={20} onClick={exportDocument} /> + {desktop && window.opendirectorDesktop?.pickLinkedVideo && ( + setLinkedDraftOpen(true)} + /> + )} {desktop && window.opendirectorDesktop?.showMore && window.opendirectorDesktop?.showMore?.()} />} )} + {desktop && linkedDraftOpen && ( + void editSession.request()} + initialDraft={linkedDraftView} + onDraftChange={setLinkedDraftView} + onClose={() => setLinkedDraftOpen(false)} + /> + )} {!ready && (
{initializationError ? ( diff --git a/src/desktop.ts b/src/desktop.ts index 5e8471d77..543727d69 100644 --- a/src/desktop.ts +++ b/src/desktop.ts @@ -1,9 +1,27 @@ +export interface DesktopLinkedVideoSource { + sourceId: string; + projectId: string; + title: string; + mimeType: string; + size: number; + modifiedAt: string; + durationSeconds: number; + width?: number | null; + height?: number | null; +} + +export type DesktopPickLinkedVideoResult = + | { ok: true; source: DesktopLinkedVideoSource } + | { ok: false; code: string; message: string } + | null; + /** Desktop lifecycle signals; business commands stay on the shared API. */ export interface DesktopBridge { registerSession(id: string): void; setLocale(locale: "zh-CN" | "en-US"): void; showMore?(): void; setExporting(active: boolean): void; + pickLinkedVideo?(projectId: string): Promise; } declare global { diff --git a/src/i18n/messages/en-US/index.ts b/src/i18n/messages/en-US/index.ts index 86adf91ae..3c68e11ad 100644 --- a/src/i18n/messages/en-US/index.ts +++ b/src/i18n/messages/en-US/index.ts @@ -15,6 +15,7 @@ import { editors } from "./editors.ts"; import { errors } from "./errors.ts"; import { generation } from "./generation.ts"; import { library } from "./library.ts"; +import { linkedDraft } from "./linkedDraft.ts"; import { models } from "./models.ts"; import { settings } from "./settings.ts"; import { timeline } from "./timeline.ts"; @@ -40,6 +41,7 @@ export const enUS: Record = { ...editors, ...timeline, ...library, + ...linkedDraft, ...assistant, ...models, ...api, diff --git a/src/i18n/messages/en-US/linkedDraft.ts b/src/i18n/messages/en-US/linkedDraft.ts new file mode 100644 index 000000000..43b933365 --- /dev/null +++ b/src/i18n/messages/en-US/linkedDraft.ts @@ -0,0 +1,40 @@ +export const linkedDraft = { + "linkedDraft.toolbar.button": "In-Place Video Edit (Draft)", + "linkedDraft.modal.title": "In-Place Video Editing (Single-Clip Draft)", + "linkedDraft.modal.subtitle": + "Streams directly from your local or mounted storage with scrubbing support—no upload staging or full-file copy in project assets.", + "linkedDraft.action.pickVideo": "Choose Mounted Video", + "linkedDraft.action.recheckOriginal": "Recheck Original Media", + "linkedDraft.action.addToTimeline": "Add to Timeline & Trim", + "linkedDraft.action.editInTimeline": "Continue Editing in Timeline", + "linkedDraft.action.close": "Close", + "linkedDraft.status.online": "Source online", + "linkedDraft.status.offline": "Source offline", + "linkedDraft.status.modified": "Source modified", + "linkedDraft.status.unbound": "No source bound", + "linkedDraft.meta.trimValue": "In {inPoint}s → Out {outPoint}s (duration {clipDuration}s)", + "linkedDraft.meta.unsavedHint": "Not added to timeline yet. Scrub the player below to preview another position, then click “Add to Timeline & Trim”.", + "linkedDraft.hint.recheckOriginal": + "Reconnect the original drive and click “Recheck Original Media” to restore preview paused at your saved in-point ({inPoint}s).", + "linkedDraft.player.trimPlaybackHint": + "Preview is paused at saved in-point ({inPoint}s) and pauses automatically at out-point ({outPoint}s) when played.", + "linkedDraft.sourceTimeline.aria": "Source video preview player", + "linkedDraft.clipTimeline.aria": "Saved clip timeline", + "linkedDraft.clipTimeline.label": "Saved clip", + "linkedDraft.clipTimeline.play": "Play clip", + "linkedDraft.clipTimeline.pause": "Pause clip", + "linkedDraft.clipTimeline.playAria": "Play saved clip", + "linkedDraft.clipTimeline.pauseAria": "Pause saved clip", + "linkedDraft.clipTimeline.rangeSummary": "From source {inTime}–{outTime}", + "linkedDraft.clipTimeline.timeReadout": "{current} / {total}", + "linkedDraft.clipTimeline.outsideRange": "Outside clip range", + "linkedDraft.clipTimeline.scrubberAria": "Saved clip playhead", + "linkedDraft.clipTimeline.scrubberValueText": "{current} of {total} in clip (source {source})", + "linkedDraft.empty.hint": "Click “Choose Mounted Video” to pick a video (> 5s) from an external drive or mounted NAS share.", + "linkedDraft.error.singleClipRequired": "This single-clip draft mode requires keeping exactly the 1 bound video clip on the visual track.", + "linkedDraft.error.unsupportedDraftEdits": + "This single-clip draft record persists only the bound clip’s trim range (inPoint / outPoint), not audio tracks, text/font overlays, speed, volume/mute, or FPS changes. Reset those settings before applying.", + "linkedDraft.error.readOnly": "This project is currently read-only. Take edit ownership before saving.", + "linkedDraft.error.saveRestoreSource": + "The source video is currently unavailable. Your unsaved edits are still kept—reconnect or restore the original file, then apply again. ({detail})", +} as const; diff --git a/src/i18n/messages/zh-CN/index.ts b/src/i18n/messages/zh-CN/index.ts index 96bde2cda..ad0b2c639 100644 --- a/src/i18n/messages/zh-CN/index.ts +++ b/src/i18n/messages/zh-CN/index.ts @@ -14,6 +14,7 @@ import { editors } from "./editors.ts"; import { errors } from "./errors.ts"; import { generation } from "./generation.ts"; import { library } from "./library.ts"; +import { linkedDraft } from "./linkedDraft.ts"; import { models } from "./models.ts"; import { settings } from "./settings.ts"; import { timeline } from "./timeline.ts"; @@ -37,6 +38,7 @@ export const zhCN = { ...editors, ...timeline, ...library, + ...linkedDraft, ...assistant, ...models, ...api, diff --git a/src/i18n/messages/zh-CN/linkedDraft.ts b/src/i18n/messages/zh-CN/linkedDraft.ts new file mode 100644 index 000000000..e86cbef1a --- /dev/null +++ b/src/i18n/messages/zh-CN/linkedDraft.ts @@ -0,0 +1,38 @@ +export const linkedDraft = { + "linkedDraft.toolbar.button": "原位视频剪辑(实验)", + "linkedDraft.modal.title": "原位视频剪辑(单文件实验)", + "linkedDraft.modal.subtitle": + "直接从本机或已挂载存储读取原视频(支持拖动跳播,不复制原文件、不写入工程 assets 目录)。", + "linkedDraft.action.pickVideo": "选择挂载盘视频", + "linkedDraft.action.recheckOriginal": "重新检查原素材", + "linkedDraft.action.addToTimeline": "加入时间线裁剪", + "linkedDraft.action.editInTimeline": "在时间线中继续编辑", + "linkedDraft.action.close": "关闭", + "linkedDraft.status.online": "源在线可读", + "linkedDraft.status.offline": "源当前离线", + "linkedDraft.status.modified": "源文件已变化", + "linkedDraft.status.unbound": "尚未绑定视频源", + "linkedDraft.meta.trimValue": "入点 {inPoint}s → 出点 {outPoint}s(片段时长 {clipDuration}s)", + "linkedDraft.meta.unsavedHint": "尚未保存到时间线,可先在下方播放器拖动跳播验证,再点击「加入时间线裁剪」。", + "linkedDraft.hint.recheckOriginal": "接回原盘后点击「重新检查原素材」,将恢复到已保存入点({inPoint}s)。", + "linkedDraft.player.trimPlaybackHint": "预览已暂停在已保存入点 {inPoint}s,点击播放后将在出点 {outPoint}s 自动暂停。", + "linkedDraft.sourceTimeline.aria": "原片预览播放器", + "linkedDraft.clipTimeline.aria": "剪辑片段时间轴", + "linkedDraft.clipTimeline.label": "剪辑片段", + "linkedDraft.clipTimeline.play": "播放片段", + "linkedDraft.clipTimeline.pause": "暂停片段", + "linkedDraft.clipTimeline.playAria": "播放已保存剪辑片段", + "linkedDraft.clipTimeline.pauseAria": "暂停已保存剪辑片段", + "linkedDraft.clipTimeline.rangeSummary": "取自原片 {inTime}–{outTime}", + "linkedDraft.clipTimeline.timeReadout": "{current} / {total}", + "linkedDraft.clipTimeline.outsideRange": "当前位于剪辑范围外", + "linkedDraft.clipTimeline.scrubberAria": "剪辑片段进度", + "linkedDraft.clipTimeline.scrubberValueText": "片段位置 {current},共 {total}(原片 {source})", + "linkedDraft.empty.hint": "点击「选择挂载盘视频」从移动硬盘或已挂载 NAS 共享中选择一个长度超过 5 秒的视频开始演示。", + "linkedDraft.error.singleClipRequired": "当前单文件实验模式要求视觉轨道保留且仅保留这 1 条绑定视频片段。", + "linkedDraft.error.unsupportedDraftEdits": + "当前单文件实验记录仅保存该绑定片段的入点与出点(inPoint / outPoint),暂不保存音频轨、字幕字体、变速、音量静音或帧率修改;请还原这些项后再应用编辑。", + "linkedDraft.error.readOnly": "当前工程处于只读状态,请先获取编辑权后再保存。", + "linkedDraft.error.saveRestoreSource": + "源视频当前不可用,未保存的剪辑输入已保留;请接回原盘或恢复原文件后再次点击应用编辑。({detail})", +} as const; diff --git a/tests/linkedDraftDualTimeline.test.ts b/tests/linkedDraftDualTimeline.test.ts new file mode 100644 index 000000000..4c847ee4d --- /dev/null +++ b/tests/linkedDraftDualTimeline.test.ts @@ -0,0 +1,309 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + createLinkedPreviewController, + formatPreviewClock, + type ClipRangeBounds, + type LinkedPreviewSnapshot, + type MediaPreviewPlayer, +} from "../src/canvas/linkedDraftController.ts"; + +class FakeVideoPlayer implements MediaPreviewPlayer { + readyState = 0; + duration = 30; + paused = true; + ended = false; + seeking = false; + private _currentTime = 0; + private listeners = new Map void>>(); + readonly visitedTimes: number[] = []; + + constructor(duration = 30, initialReadyState = 0) { + this.duration = duration; + this.readyState = initialReadyState; + } + + get currentTime(): number { + return this._currentTime; + } + + set currentTime(value: number) { + const clamped = Math.max(0, Math.min(this.duration, value)); + this._currentTime = clamped; + this.visitedTimes.push(clamped); + if (clamped < this.duration) { + this.ended = false; + } + this.seeking = true; + this.emit("seeking"); + this.seeking = false; + this.emit("timeupdate"); + this.emit("seeked"); + } + + play(): Promise { + if (this.ended && this._currentTime >= this.duration) { + // Browser native play from ended restarts at 0 only when not pre-seeked; + // clip replay pre-seeks to inPoint before calling play(). + this._currentTime = 0; + this.visitedTimes.push(0); + } + this.ended = false; + this.paused = false; + this.emit("play"); + return Promise.resolve(); + } + + pause(): void { + if (this.paused) return; + this.paused = true; + this.emit("pause"); + } + + loadMetadata(): void { + this.readyState = 1; + this.emit("loadedmetadata"); + } + + /** Simulate native media advancing to `nextTime` during playback. */ + advancePlaybackTo(nextTime: number): void { + assert.equal(this.paused, false, "expected player to be playing"); + this._currentTime = Math.min(this.duration, Math.max(0, nextTime)); + this.visitedTimes.push(this._currentTime); + this.emit("timeupdate"); + } + + /** Simulate natural media end (`pause` followed by `ended`, holding end frame). */ + reachNaturalEnd(finalTime = this.duration): void { + this._currentTime = finalTime; + this.visitedTimes.push(finalTime); + this.paused = true; + this.ended = true; + this.emit("timeupdate"); + this.emit("pause"); + this.emit("ended"); + } + + /** Simulate user dragging or clicking the native