From 07dfc7ab71960e1faac466b927da4ec596162e05 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:03:47 +0000 Subject: [PATCH 1/2] feat: export multi-clip scenes and frame custom voice audio - Export trimmed or multi-clip scenes via verified KD.fetch RPCs - Select ready 4K and 1080p video variants and pin matched variant IDs - List custom voices from cj and lr and download character voice audio - Frame raw 24 kHz PCM responses into 44-byte RIFF/WAVE audio files - Skip expired signed URLs, bypass stale caches, and filter extensions - Update the tool reference guides in English, Chinese, and Japanese --- docs/en/tools-reference.md | 8 +- docs/ja/tools-reference.md | 8 +- docs/zh-CN/tools-reference.md | 8 +- src/assets.rs | 246 +++++++++++++++-- src/characters.rs | 26 +- src/download.rs | 303 +++++++++++++++++++-- src/media_files.rs | 40 ++- ts/dom.ts | 170 +++++++++++- ts/fetch_media.ts | 261 ++++++++++++++---- ts/index.ts | 2 + ts/media_variants.ts | 245 +++++++++++++++++ ts/project_store.ts | 304 ++++++++++++++++++++- ts/read_store_snapshot.ts | 339 ++++++++++++++++++------ ts/resolve_video_url.ts | 55 ++-- ts/scene_export.ts | 481 ++++++++++++++++++++++++++++++++++ ts/scene_export_builds.ts | 121 +++++++++ ts/scene_tiles.ts | 37 +++ ts/types.ts | 54 +++- 18 files changed, 2454 insertions(+), 254 deletions(-) create mode 100644 ts/media_variants.ts create mode 100644 ts/scene_export.ts create mode 100644 ts/scene_export_builds.ts diff --git a/docs/en/tools-reference.md b/docs/en/tools-reference.md index d8d6f6a..012a910 100644 --- a/docs/en/tools-reference.md +++ b/docs/en/tools-reference.md @@ -337,8 +337,8 @@ List project assets or upload local images and videos to the active project. | :--- | :--- | :--- | :--- | | `action` | `string` | No | `list` (default) or `upload`. | | `files` | `string[]` | For `upload` | Local image or video paths on the server. | -| `query` | `string` | No | Case-insensitive substring matching asset ID, name, or prompt. | -| `kind` | `string` | No | Filter by `"image"`, `"video"`, `"audio"`, `"scene"`, `"character"`, or `"all"` (default). | +| `query` | `string` | No | Case-insensitive substring matching asset ID, media ID, name, or prompt. | +| `kind` | `string` | No | Filter by `"image"`, `"video"`, `"audio"` (including saved custom voices), `"scene"`, `"character"`, or `"all"` (default). | | `collection` | `string` | No | Filter by collection ID, name substring, `"all"`, `"none"`, or `"uncollected"`. | | `limit` | `integer` | No | Maximum items to return (`>= 1`). | | `resolve_urls` | `boolean` | No | Get missing media URLs. For image or audio requests, the tool resolves assets with an unknown media type before it applies the result limit. Default is `true`. The lookup has a 10-second limit. | @@ -387,11 +387,11 @@ The tool checks the result of each write in a new read of the same project. The ### `flow_download` -Download a matching project media asset (image, video, audio, or character look) to `/downloads` and index it in `flow-mcp.db`. Waits up to `45` seconds (`pending: true` on timeout) and returns `{"file", "resource_uri", "record"}`. If the client supports MCP `2025-06-18` or newer, it also returns a `resource_link`. +Download a matching project media asset (image, video, upscaled `1080p` or `4K` variant, custom voice, character look or assigned voice, or scene) to `/downloads` and index it in `flow-mcp.db`. The tool downloads untrimmed single-clip scenes directly. On verified front-end builds, the tool exports multi-clip or trimmed scenes through the scene export service of Flow (and returns `unsupported_front_end` on unverified builds). Waits up to `45` seconds (`pending: true` on timeout) and returns `{"file", "resource_uri", "record"}`. If the client supports MCP `2025-06-18` or newer, it also returns a `resource_link`. | Parameter | Type | Required | Description | | :--- | :--- | :--- | :--- | -| `match` | `string` | Yes | Exact asset ID, exact name, or case-insensitive substring matching a project asset. | +| `match` | `string` | Yes | Exact asset ID, media or variant ID, exact name, or case-insensitive substring matching a project asset. | ### `flow_downloads` diff --git a/docs/ja/tools-reference.md b/docs/ja/tools-reference.md index 559b074..a3b7f3e 100644 --- a/docs/ja/tools-reference.md +++ b/docs/ja/tools-reference.md @@ -337,8 +337,8 @@ Flow シーンタイムラインの一覧表示、作成、クリップ追加、 | :--- | :--- | :--- | :--- | | `action` | `string` | いいえ | `list`(既定)または `upload`。 | | `files` | `string[]` | `upload` の場合に必須 | サーバー上のローカル画像または動画のパス。 | -| `query` | `string` | いいえ | アセット ID、名前、またはプロンプトに一致する大文字小文字を区別しない部分文字列。 | -| `kind` | `string` | いいえ | `"image"`、`"video"`、`"audio"`、`"scene"`、`"character"`、または `"all"`(既定)で絞り込みます。 | +| `query` | `string` | いいえ | アセット ID、メディア ID、名前、またはプロンプトに一致する大文字小文字を区別しない部分文字列。 | +| `kind` | `string` | いいえ | `"image"`、`"video"`、`"audio"`(保存済みカスタムボイスを含む)、`"scene"`、`"character"`、または `"all"`(既定)で絞り込みます。 | | `collection` | `string` | いいえ | コレクション ID、名前部分文字列、`"all"`、`"none"`、または `"uncollected"` で絞り込みます。 | | `limit` | `integer` | いいえ | 返す最大項目数(`>= 1`)。 | | `resolve_urls` | `boolean` | いいえ | 不足しているメディア URL を取得します。画像または音声で絞り込む場合は、種類が不明なアセットを確認してから件数を制限します。既定値は `true` で、待機時間は最大 10 秒です。 | @@ -387,11 +387,11 @@ Flow シーンタイムラインの一覧表示、作成、クリップ追加、 ### `flow_download` -一致するプロジェクトのメディアアセット(画像、動画、音声、またはキャラクター外見)を `/downloads` へダウンロードし、`flow-mcp.db` に登録します。最大 `45` 秒まで待機し(タイムアウト時は `pending: true`)、`{"file", "resource_uri", "record"}` を返します。クライアントが MCP `2025-06-18` 以降に対応している場合は、`resource_link` も返します。 +一致するプロジェクトのメディアアセット(画像、動画、`1080p` または `4K` アップスケール派生版、カスタムボイス、キャラクター外見または設定済みボイス、シーン)を `/downloads` へダウンロードし、`flow-mcp.db` に登録します。未トリミングの単一クリップシーンは直接ダウンロードし、複数クリップまたはトリミング済みシーンは検証済みフロントエンドビルド上で Flow のシーン書き出しサービスを経由して書き出します(未検証ビルドでは `unsupported_front_end` を返します)。最大 `45` 秒まで待機し(タイムアウト時は `pending: true`)、`{"file", "resource_uri", "record"}` を返します。クライアントが MCP `2025-06-18` 以降に対応している場合は、`resource_link` も返します。 | パラメータ | 型 | 必須 | 説明 | | :--- | :--- | :--- | :--- | -| `match` | `string` | はい | プロジェクトアセットに一致する正確なアセット ID、完全一致名、または大文字小文字を区別しない部分文字列。 | +| `match` | `string` | はい | プロジェクトアセットに一致する正確なアセット ID、メディアまたは派生 ID、完全一致名、または大文字小文字を区別しない部分文字列。 | ### `flow_downloads` diff --git a/docs/zh-CN/tools-reference.md b/docs/zh-CN/tools-reference.md index 748749e..2bc51b8 100644 --- a/docs/zh-CN/tools-reference.md +++ b/docs/zh-CN/tools-reference.md @@ -337,8 +337,8 @@ flow-mcp [OPTIONS] | :--- | :--- | :--- | :--- | | `action` | `string` | 否 | `list`(默认)或 `upload`。 | | `files` | `string[]` | `upload` 时必填 | 服务端所在机器的本地图片或视频路径。 | -| `query` | `string` | 否 | 匹配资产 ID、名称或提示词的忽略大小写子串。 | -| `kind` | `string` | 否 | 按 `"image"`、`"video"`、`"audio"`、`"scene"`、`"character"` 或 `"all"`(默认)筛选。 | +| `query` | `string` | 否 | 匹配资产 ID、媒体 ID、名称或提示词的忽略大小写子串。 | +| `kind` | `string` | 否 | 按 `"image"`、`"video"`、`"audio"`(含已保存的自定义音色)、`"scene"`、`"character"` 或 `"all"`(默认)筛选。 | | `collection` | `string` | 否 | 按集合 ID、名称子串、`"all"`、`"none"` 或 `"uncollected"` 筛选。 | | `limit` | `integer` | 否 | 返回的最大条目数(`>= 1`)。 | | `resolve_urls` | `boolean` | 否 | 补齐缺失的媒体 URL。筛选图片或音频时,先查明媒体类型未知的资源,再应用条数限制。默认 `true`,最多等待 10 秒。 | @@ -387,11 +387,11 @@ flow-mcp [OPTIONS] ### `flow_download` -将匹配的项目媒体资产(图像、视频、音频或角色外观)下载至 `/downloads` 并索引到 `flow-mcp.db`。最多等待 `45` 秒(超时返回 `pending: true`),并返回 `{"file", "resource_uri", "record"}`。如果客户端支持 MCP `2025-06-18` 或更高版本,还会返回 `resource_link`。 +将匹配的项目媒体资产(图像、视频、`1080p` 或 `4K` 超分变体、自定义音色、角色外观或绑定音色、或场景)下载至 `/downloads` 并索引到 `flow-mcp.db`。未裁剪的单片段场景直接下载,多片段或已裁剪场景在已验证的前端构建上通过 Flow 场景导出服务导出(未验证构建返回 `unsupported_front_end`)。最多等待 `45` 秒(超时返回 `pending: true`),并返回 `{"file", "resource_uri", "record"}`。如果客户端支持 MCP `2025-06-18` 或更高版本,还会返回 `resource_link`。 | 参数 | 类型 | 必填 | 说明 | | :--- | :--- | :--- | :--- | -| `match` | `string` | 是 | 匹配项目资产的精确资产 ID、精确名称或忽略大小写子串。 | +| `match` | `string` | 是 | 匹配项目资产的精确资产 ID、媒体或变体 ID、精确名称或忽略大小写子串。 | ### `flow_downloads` diff --git a/src/assets.rs b/src/assets.rs index c3c8975..4ff8c01 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -78,11 +78,64 @@ pub(crate) struct FlowAsset { /// Internal media error payload used for generation failure detection. #[serde(default, skip_serializing)] pub(crate) media_error: Option, + /// Known primary, history, and upscaled variant media IDs on the tile. + #[serde(default, skip_serializing)] + pub(crate) media_ids: Vec, + /// Optional workflow ID associated with a custom voice entry. + #[serde(default, skip_serializing)] + pub(crate) workflow_id: Option, + /// True when a multi-clip or trimmed scene requires Angular scene export. + #[serde(default, skip_serializing)] + pub(crate) requires_scene_export: bool, + /// True when `as29s` case `11` flagged raw 24 kHz PCM audio. + #[serde(default, skip_serializing)] + pub(crate) pcm_audio: bool, + /// Underlying media family override when a tile downloads audio. + #[serde(default, skip_serializing)] + pub(crate) media_kind: Option, /// Creation timestamp (`createTime`) string. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) created_at: Option, } +impl FlowAsset { + /// Creates an image asset descriptor for a generated character look. + pub(crate) fn character_look( + fallback_id: &str, + name: String, + url: Option, + primary_media_id: Option, + ) -> Self { + Self { + id: primary_media_id + .clone() + .unwrap_or_else(|| fallback_id.to_string()), + name, + kind: "image".to_string(), + prompt: None, + url, + collection_id: None, + collection_name: None, + width: None, + height: None, + duration: None, + primary_media_id, + personality_notes: None, + voice: None, + trim_start_seconds: None, + trim_end_seconds: None, + media_status: None, + media_error: None, + media_ids: Vec::new(), + workflow_id: None, + requires_scene_export: false, + pcm_audio: false, + media_kind: None, + created_at: None, + } + } +} + /// Snapshot of active project metadata and asset tiles. #[derive(Debug, Clone)] pub(crate) struct ProjectAssetsSnapshot { @@ -158,7 +211,29 @@ pub(crate) struct TrashParams { pub(crate) r#match: String, } -/// Resolves missing direct media URLs on finished media and character tiles through `as29s` RPCs. +/// Strips a leading `media/` or `workflows/` prefix from a resource identifier. +fn strip_resource_prefix(raw: &str) -> &str { + let trimmed = raw.trim(); + if trimmed.len() > 6 && trimmed[..6].eq_ignore_ascii_case("media/") { + &trimmed[6..] + } else if trimmed.len() > 10 && trimmed[..10].eq_ignore_ascii_case("workflows/") { + &trimmed[10..] + } else { + trimmed + } +} + +/// Strips a leading `media/` prefix from a media resource identifier. +fn strip_media_prefix(raw: &str) -> &str { + let trimmed = raw.trim(); + if trimmed.len() > 6 && trimmed[..6].eq_ignore_ascii_case("media/") { + &trimmed[6..] + } else { + trimmed + } +} + +/// Resolves missing direct media URLs on finished media, character, and 1-clip scene tiles through `as29s` RPCs. async fn populate_missing_media_urls( engine: &ChromeEngine, assets: &mut [FlowAsset], @@ -168,8 +243,9 @@ async fn populate_missing_media_urls( for (index, asset) in assets.iter().enumerate() { if !matches!( asset.kind.as_str(), - "video" | "image" | "character" | "audio" - ) || asset.url.is_some() + "video" | "image" | "character" | "audio" | "scene" + ) || asset.requires_scene_export + || asset.url.is_some() || asset.media_error.is_some() || matches!( asset.media_status.as_deref(), @@ -195,33 +271,44 @@ async fn populate_missing_media_urls( let timeout_ms = deadline.and_then(|at| { u64::try_from(at.saturating_duration_since(Instant::now()).as_millis()).ok() }); - let (resolved, media_kind) = eval_resolve_media_url(engine, &media_id, timeout_ms) - .await - .map(|val| { - let url = val - .get("url") - .and_then(|v| v.as_str()) - .map(str::trim) - .filter(|u| u.starts_with("http")) - .map(str::to_string); - let kind = val - .get("media_kind") - .and_then(|v| v.as_str()) - .map(str::to_string); - (url, kind) - }) - .unwrap_or((None, None)); - (indices, resolved, media_kind) + let (resolved, media_kind, pcm_audio) = + eval_resolve_media_url(engine, &media_id, timeout_ms) + .await + .map(|val| { + let url = val + .get("url") + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|u| u.starts_with("http")) + .map(str::to_string); + let kind = val + .get("media_kind") + .and_then(|v| v.as_str()) + .map(str::to_string); + let pcm = val + .get("pcm_audio") + .and_then(Value::as_bool) + .unwrap_or(false); + (url, kind, pcm) + }) + .unwrap_or((None, None, false)); + (indices, resolved, media_kind, pcm_audio) }) .buffer_unordered(MEDIA_URL_LOOKUPS); futures_util::pin_mut!(lookups); - while let Some((indices, url, media_kind)) = lookups.next().await { + while let Some((indices, url, media_kind, pcm_audio)) = lookups.next().await { for index in indices { if let Some(ref resolved_url) = url { assets[index].url = Some(resolved_url.clone()); } - if assets[index].kind == "image" && media_kind.as_deref() == Some("audio") { - assets[index].kind = "audio".to_string(); + if pcm_audio { + assets[index].pcm_audio = true; + } + if let Some(ref mk) = media_kind { + if assets[index].kind == "image" && mk == "audio" { + assets[index].kind = "audio".to_string(); + } + assets[index].media_kind = Some(mk.clone()); } } } @@ -268,8 +355,27 @@ async fn read_project_assets(engine: &ChromeEngine) -> Result(assets: &[FlowAsset], mut pred: F) -> Option<&FlowAsset> +where + F: FnMut(&FlowAsset) -> bool, +{ + let mut fallback: Option<&FlowAsset> = None; + for asset in assets { + if pred(asset) { + if !matches!(asset.kind.as_str(), "character" | "scene") { + return Some(asset); + } + if fallback.is_none() { + fallback = Some(asset); + } + } + } + fallback +} + +/// Selects the best-matching asset by exact ID, media ID, exact name, name substring, +/// ID or media ID substring, or optional prompt substring. pub(crate) fn match_asset<'a>( assets: &'a [FlowAsset], match_str: &str, @@ -279,11 +385,36 @@ pub(crate) fn match_asset<'a>( if raw.is_empty() { return None; } + let clean_raw = strip_media_prefix(raw); + let clean_res = strip_resource_prefix(raw); let lower = raw.to_lowercase(); + let clean_lower = clean_raw.to_lowercase(); + let clean_res_lower = clean_res.to_lowercase(); assets .iter() .find(|a| a.id == raw) + .or_else(|| { + find_preferring_direct_media(assets, |a| { + a.workflow_id + .as_deref() + .is_some_and(|wf| wf == raw || strip_resource_prefix(wf) == clean_res) + }) + }) + .or_else(|| { + find_preferring_direct_media(assets, |a| { + a.primary_media_id + .as_deref() + .is_some_and(|id| id == raw || strip_media_prefix(id) == clean_raw) + }) + }) + .or_else(|| { + find_preferring_direct_media(assets, |a| { + a.media_ids + .iter() + .any(|id| id == raw || strip_media_prefix(id) == clean_raw) + }) + }) .or_else(|| assets.iter().find(|a| a.name.eq_ignore_ascii_case(raw))) .or_else(|| { assets @@ -291,6 +422,19 @@ pub(crate) fn match_asset<'a>( .find(|a| a.name.to_lowercase().contains(&lower)) }) .or_else(|| assets.iter().find(|a| a.id.to_lowercase().contains(&lower))) + .or_else(|| { + find_preferring_direct_media(assets, |a| { + a.workflow_id + .as_deref() + .is_some_and(|wf| wf.to_lowercase().contains(&clean_res_lower)) + || a.primary_media_id + .as_deref() + .is_some_and(|id| id.to_lowercase().contains(&clean_lower)) + || a.media_ids + .iter() + .any(|id| id.to_lowercase().contains(&clean_lower)) + }) + }) .or_else(|| { if include_prompt { assets.iter().find(|a| { @@ -306,6 +450,42 @@ pub(crate) fn match_asset<'a>( }) } +/// Pins `target.primary_media_id` when `match_str` selects a specific variant in `target.media_ids`. +fn pin_matched_variant_id(target: &mut FlowAsset, match_str: &str) { + let raw = match_str.trim(); + if raw.is_empty() || target.id == raw || target.name.eq_ignore_ascii_case(raw) { + return; + } + let clean_raw = strip_media_prefix(raw); + let exact = target + .media_ids + .iter() + .find(|id| id.as_str() == raw || strip_media_prefix(id) == clean_raw) + .cloned(); + let lower = raw.to_lowercase(); + let clean_lower = clean_raw.to_lowercase(); + let matched = exact.or_else(|| { + if target.name.to_lowercase().contains(&lower) || target.id.to_lowercase().contains(&lower) + { + return None; + } + target + .media_ids + .iter() + .find(|id| id.to_lowercase().contains(&clean_lower)) + .cloned() + }); + if let Some(variant_id) = matched { + let normalized = strip_media_prefix(&variant_id).to_string(); + let changed = + target.primary_media_id.as_deref().map(strip_media_prefix) != Some(normalized.as_str()); + target.primary_media_id = Some(normalized); + if changed { + target.url = None; + } + } +} + /// Resolves the single best-matching asset and active project metadata across all project assets. pub(crate) async fn resolve_asset( engine: &ChromeEngine, @@ -314,7 +494,7 @@ pub(crate) async fn resolve_asset( context_label: &str, ) -> Result<(FlowAsset, Option, Option)> { let snap = read_project_assets(engine).await?; - let target = match_asset(&snap.assets, match_str, include_prompt) + let mut target = match_asset(&snap.assets, match_str, include_prompt) .cloned() .with_context(|| { format!( @@ -322,6 +502,7 @@ pub(crate) async fn resolve_asset( match_str, context_label ) })?; + pin_matched_variant_id(&mut target, match_str); Ok((target, snap.project_id, snap.project_title)) } @@ -355,8 +536,19 @@ pub(crate) async fn list_assets( return false; } if let Some(q) = &q_lower { + let clean_q = strip_media_prefix(q); + let clean_wf_q = strip_resource_prefix(q); let name_hit = a.name.to_lowercase().contains(q); - let id_hit = a.id.to_lowercase().contains(q); + let id_hit = a.id.to_lowercase().contains(q) + || a.workflow_id + .as_deref() + .is_some_and(|wf| wf.to_lowercase().contains(clean_wf_q)) + || a.primary_media_id + .as_deref() + .is_some_and(|id| id.to_lowercase().contains(clean_q)) + || a.media_ids + .iter() + .any(|id| id.to_lowercase().contains(clean_q)); let prompt_hit = a.prompt.as_deref().unwrap_or("").to_lowercase().contains(q); if !name_hit && !id_hit && !prompt_hit { return false; diff --git a/src/characters.rs b/src/characters.rs index 12c6de2..0fb08d5 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -757,26 +757,12 @@ pub(crate) async fn create_or_update_character_job( .filter(|s| s.starts_with("http") || s.starts_with("data:")) .map(str::to_string); if media_id.is_some() || src.is_some() { - let temp_asset = FlowAsset { - id: media_id.clone().unwrap_or_else(|| char_id.clone()), - name: persisted_name.clone(), - kind: "image".to_string(), - prompt: None, - url: src, - collection_id: None, - collection_name: None, - width: None, - height: None, - duration: None, - primary_media_id: media_id, - personality_notes: None, - voice: None, - trim_start_seconds: None, - trim_end_seconds: None, - media_status: None, - media_error: None, - created_at: None, - }; + let temp_asset = FlowAsset::character_look( + &char_id, + persisted_name.clone(), + src, + media_id, + ); if let Ok(rec) = download_resolved_asset( engine, db, diff --git a/src/download.rs b/src/download.rs index 8f79330..5702ea8 100644 --- a/src/download.rs +++ b/src/download.rs @@ -8,6 +8,7 @@ use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; use serde_json::{Value, json}; use std::path::Path; use std::sync::OnceLock; +use std::time::{SystemTime, UNIX_EPOCH}; use tokio::io::{AsyncWriteExt, BufWriter}; use tokio::time::Duration; use url::Url; @@ -41,6 +42,11 @@ enum DownloadSource { }, /// Unsigned media URL when the asset has no media ID. UnsignedUrl(String), + /// Multi-clip or trimmed scene that exports via Angular `KD` RPCs in Chrome. + ExportScene { + /// Project scene tile ID. + scene_id: String, + }, } /// Ordered URL candidates and media kind from `resolveVideoUrl`. @@ -49,6 +55,8 @@ struct ResolvedMediaUrls { urls: Vec, /// Media family from the `as29s` wire message when present. media_kind: Option, + /// True when `as29s` case `11` returned raw 24 kHz PCM audio. + pcm_audio: bool, } /// Returns the shared HTTP client for streaming media downloads. @@ -128,10 +136,14 @@ async fn fetch_via_browser_to_temp( engine: &ChromeEngine, media_url: &str, expected_kind: &str, + frame_pcm_wav: bool, temp_path: &Path, ) -> Result<(Option, Option, u64)> { let val = engine - .call_flow_async("fetchMedia", json!([media_url, expected_kind])) + .call_flow_async( + "fetchMedia", + json!([media_url, expected_kind, frame_pcm_wav]), + ) .await?; let b64 = val .get("b64") @@ -189,6 +201,90 @@ fn is_signed_direct_url(raw_url: &str) -> bool { }) } +/// Converts a proleptic Gregorian UTC date into days since `1970-01-01`. +fn civil_days_from_ymd(year: i64, month: u32, day: u32) -> i64 { + let y = year - i64::from(month <= 2); + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = (y - era * 400) as u64; + let m = u64::from(month); + let d = u64::from(day); + let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + (doe as i64) - 719_468 +} + +/// Parses a compact `YYYYMMDDTHHMMSSZ` timestamp into Unix epoch seconds. +fn parse_goog_date_secs(raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.len() != 16 { + return None; + } + let bytes = trimmed.as_bytes(); + if !matches!(bytes[8], b'T' | b't') || !matches!(bytes[15], b'Z' | b'z') { + return None; + } + let year: i64 = trimmed.get(0..4)?.parse().ok()?; + let month: u32 = trimmed.get(4..6)?.parse().ok()?; + let day: u32 = trimmed.get(6..8)?.parse().ok()?; + let hour: u64 = trimmed.get(9..11)?.parse().ok()?; + let minute: u64 = trimmed.get(11..13)?.parse().ok()?; + let second: u64 = trimmed.get(13..15)?.parse().ok()?; + if !(1..=12).contains(&month) + || !(1..=31).contains(&day) + || hour > 23 + || minute > 59 + || second > 60 + { + return None; + } + let days = civil_days_from_ymd(year, month, day); + let day_secs = u64::try_from(days).ok()?.checked_mul(86_400)?; + day_secs + .checked_add(hour * 3_600) + .and_then(|v| v.checked_add(minute * 60)) + .and_then(|v| v.checked_add(second)) +} + +/// Returns `true` when `raw_url` carries a V4 or V2 GCS signature whose validity window has elapsed. +fn is_expired_signed_url(raw_url: &str) -> bool { + let Ok(parsed) = Url::parse(raw_url.trim()) else { + return false; + }; + let Ok(now_dur) = SystemTime::now().duration_since(UNIX_EPOCH) else { + return false; + }; + let now_secs = now_dur.as_secs(); + let mut goog_date: Option = None; + let mut goog_expires: Option = None; + let mut v2_expires: Option = None; + let mut has_v2_sig = false; + for (k, v) in parsed.query_pairs() { + match k.to_ascii_lowercase().as_str() { + "x-goog-date" => goog_date = Some(v.into_owned()), + "x-goog-expires" => goog_expires = Some(v.into_owned()), + "expires" => v2_expires = Some(v.into_owned()), + "signature" | "googleaccessid" => has_v2_sig = true, + _ => {} + } + } + if let (Some(date_str), Some(exp_str)) = (goog_date, goog_expires) { + let Some(issued_secs) = parse_goog_date_secs(&date_str) else { + return true; + }; + let Ok(expires_secs) = exp_str.trim().parse::() else { + return true; + }; + return now_secs >= issued_secs.saturating_add(expires_secs); + } + if has_v2_sig && let Some(v2_str) = v2_expires { + let Ok(exp_secs) = v2_str.trim().parse::() else { + return true; + }; + return now_secs >= exp_secs; + } + false +} + /// Appends `raw` to `out` when it uses an allowed scheme and is not already present. fn push_unique_url(out: &mut Vec, raw: &str) { let trimmed = raw.trim(); @@ -307,12 +403,17 @@ async fn query_resolved_media_urls( return ResolvedMediaUrls { urls: Vec::new(), media_kind: None, + pcm_audio: false, }; }; let media_kind = val .get("media_kind") .and_then(|v| v.as_str()) .map(str::to_string); + let pcm_audio = val + .get("pcm_audio") + .and_then(Value::as_bool) + .unwrap_or(false); let effective_kind = if media_kind.as_deref() == Some("audio") { "audio" } else { @@ -346,17 +447,29 @@ async fn query_resolved_media_urls( for cand in unsigned { push_unique_url(&mut urls, &cand); } - ResolvedMediaUrls { urls, media_kind } + ResolvedMediaUrls { + urls, + media_kind, + pcm_audio, + } } /// Selects the [`DownloadSource`] for `target` from its pre-populated URL and media ID. fn select_download_source(target: &FlowAsset, label: &str) -> Result { + if target.kind == "scene" && target.requires_scene_export { + return Ok(DownloadSource::ExportScene { + scene_id: target.id.trim().to_string(), + }); + } let raw_url = target .url .as_deref() .map(str::trim) .filter(|s| !s.is_empty()) .map(str::to_string); + let raw_usable = raw_url + .as_deref() + .is_some_and(|u| !(is_signed_direct_url(u) && is_expired_signed_url(u))); let media_id = target .primary_media_id .as_deref() @@ -364,12 +477,14 @@ fn select_download_source(target: &FlowAsset, label: &str) -> Result { Ok(DownloadSource::DirectSigned { url, @@ -385,11 +500,12 @@ fn select_download_source(target: &FlowAsset, label: &str) -> Result Result<((Option, Option, u64), String)> { let mut attempts = Vec::new(); @@ -398,16 +514,40 @@ async fn try_download_candidates( let is_http = lower.starts_with("http://") || lower.starts_with("https://"); if is_http && is_signed_direct_url(cand_url) { let _ = tokio::fs::remove_file(temp_path).await; + if is_expired_signed_url(cand_url) { + attempts.push(format!("{} (signed URL expired)", cand_url)); + continue; + } + if frame_pcm_wav { + match fetch_via_browser_to_temp(engine, cand_url, expected_kind, true, temp_path) + .await + { + Ok(res) => return Ok((res, cand_url.clone())), + Err(browser_err) => { + let _ = tokio::fs::remove_file(temp_path).await; + attempts.push(format!("{} (browser: {})", cand_url, browser_err)); + } + } + continue; + } match stream_http_to_temp(engine, cand_url, expected_kind, temp_path).await { Ok(res) => return Ok((res, cand_url.clone())), Err(http_err) => { let _ = tokio::fs::remove_file(temp_path).await; - if http_err.to_string().contains(MEDIA_KIND_MISMATCH_TAG) { + if http_err.to_string().contains(MEDIA_KIND_MISMATCH_TAG) + || is_expired_signed_url(cand_url) + { attempts.push(format!("{} (HTTP: {})", cand_url, http_err)); continue; } - match fetch_via_browser_to_temp(engine, cand_url, expected_kind, temp_path) - .await + match fetch_via_browser_to_temp( + engine, + cand_url, + expected_kind, + false, + temp_path, + ) + .await { Ok(res) => return Ok((res, cand_url.clone())), Err(browser_err) => { @@ -422,7 +562,15 @@ async fn try_download_candidates( } } else if is_http { let _ = tokio::fs::remove_file(temp_path).await; - match fetch_via_browser_to_temp(engine, cand_url, expected_kind, temp_path).await { + match fetch_via_browser_to_temp( + engine, + cand_url, + expected_kind, + frame_pcm_wav, + temp_path, + ) + .await + { Ok(res) => return Ok((res, cand_url.clone())), Err(browser_err) => { let _ = tokio::fs::remove_file(temp_path).await; @@ -430,6 +578,10 @@ async fn try_download_candidates( attempts.push(format!("{} (browser: {})", cand_url, browser_err)); continue; } + if frame_pcm_wav { + attempts.push(format!("{} (browser: {})", cand_url, browser_err)); + continue; + } match stream_http_to_temp(engine, cand_url, expected_kind, temp_path).await { Ok(res) => return Ok((res, cand_url.clone())), Err(http_err) => { @@ -444,7 +596,15 @@ async fn try_download_candidates( } } else { let _ = tokio::fs::remove_file(temp_path).await; - match fetch_via_browser_to_temp(engine, cand_url, expected_kind, temp_path).await { + match fetch_via_browser_to_temp( + engine, + cand_url, + expected_kind, + frame_pcm_wav, + temp_path, + ) + .await + { Ok(res) => return Ok((res, cand_url.clone())), Err(browser_err) => { let _ = tokio::fs::remove_file(temp_path).await; @@ -456,6 +616,32 @@ async fn try_download_candidates( anyhow::bail!("{}", attempts.join(" | ")) } +/// Exports a multi-clip or trimmed scene in Chrome and writes the MP4 bytes to `temp_path`. +async fn export_scene_via_browser( + engine: &ChromeEngine, + scene_id: &str, + temp_path: &Path, +) -> Result<((Option, Option, u64), String)> { + let val = engine + .call_flow_async("sceneExport", json!([scene_id])) + .await?; + if val.get("ok").and_then(Value::as_bool) != Some(true) { + let err = val + .get("error") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .unwrap_or("scene_export_failed"); + anyhow::bail!("{}", err); + } + let blob_url = val + .get("url") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .context("Scene export returned no media URL")?; + let res = fetch_via_browser_to_temp(engine, blob_url, "video", false, temp_path).await?; + Ok((res, blob_url.to_string())) +} + /// Downloads a resolved [`FlowAsset`] into `/downloads` and indexes it in SQLite. pub(crate) async fn download_resolved_asset( engine: &ChromeEngine, @@ -477,39 +663,57 @@ pub(crate) async fn download_resolved_asset( let temp_name = format!(".flow-mcp-{}.part", &uuid::Uuid::new_v4().to_string()[..8]); let temp_path = stage_dir.join(temp_name); - let mut effective_kind = target.kind.clone(); + let mut effective_kind = if target.kind == "scene" { + "video".to_string() + } else if target.kind == "character" && target.media_kind.as_deref() == Some("audio") { + "audio".to_string() + } else { + target.kind.clone() + }; + let mut pcm_audio = target.pcm_audio; let download_res = match source { + DownloadSource::ExportScene { scene_id } => { + export_scene_via_browser(engine, &scene_id, &temp_path).await + } DownloadSource::DirectSigned { url, fallback_media_id, } => { let direct = std::slice::from_ref(&url); - match try_download_candidates(engine, direct, &effective_kind, &temp_path).await { + match try_download_candidates(engine, direct, &effective_kind, pcm_audio, &temp_path) + .await + { Ok(res) => Ok(res), Err(first_err) => { if let Some(media_id) = fallback_media_id { let resolved = query_resolved_media_urls(engine, &media_id, &effective_kind, true) .await; - if effective_kind == "image" - && resolved.media_kind.as_deref() == Some("audio") - { + let kind_changed = matches!(effective_kind.as_str(), "image" | "character") + && resolved.media_kind.as_deref() == Some("audio"); + if kind_changed { effective_kind = "audio".to_string(); } + let pcm_changed = !pcm_audio && resolved.pcm_audio; + pcm_audio |= resolved.pcm_audio; let mut extra = Vec::new(); for cand in resolved.urls { - if cand != url { + if cand != url || kind_changed || pcm_changed { push_unique_url(&mut extra, &cand); } } if extra.is_empty() { Err(first_err) } else { - try_download_candidates(engine, &extra, &effective_kind, &temp_path) - .await - .map_err(|extra_err| { - anyhow::anyhow!("{} | {}", first_err, extra_err) - }) + try_download_candidates( + engine, + &extra, + &effective_kind, + pcm_audio, + &temp_path, + ) + .await + .map_err(|extra_err| anyhow::anyhow!("{} | {}", first_err, extra_err)) } } else { Err(first_err) @@ -523,28 +727,71 @@ pub(crate) async fn download_resolved_asset( } => { let resolved = query_resolved_media_urls(engine, &media_id, &effective_kind, false).await; - if effective_kind == "image" && resolved.media_kind.as_deref() == Some("audio") { + if matches!(effective_kind.as_str(), "image" | "character") + && resolved.media_kind.as_deref() == Some("audio") + { effective_kind = "audio".to_string(); } + pcm_audio |= resolved.pcm_audio; let mut candidates = resolved.urls; - if let Some(raw_fallback) = fallback_url { - push_fife_candidates(&mut candidates, &raw_fallback, &effective_kind); - push_unique_url(&mut candidates, &raw_fallback); + if let Some(ref raw_fallback) = fallback_url + && !(is_signed_direct_url(raw_fallback) && is_expired_signed_url(raw_fallback)) + { + push_fife_candidates(&mut candidates, raw_fallback, &effective_kind); + push_unique_url(&mut candidates, raw_fallback); } - if candidates.is_empty() { + let first_attempt = if candidates.is_empty() { Err(anyhow::anyhow!( "media lookup returned no URLs for media ID '{}'", media_id )) } else { - try_download_candidates(engine, &candidates, &effective_kind, &temp_path).await + try_download_candidates(engine, &candidates, &effective_kind, pcm_audio, &temp_path) + .await + }; + match first_attempt { + Ok(res) => Ok(res), + Err(first_err) => { + let refreshed = + query_resolved_media_urls(engine, &media_id, &effective_kind, true).await; + let kind_changed = matches!(effective_kind.as_str(), "image" | "character") + && refreshed.media_kind.as_deref() == Some("audio"); + if kind_changed { + effective_kind = "audio".to_string(); + } + let pcm_changed = !pcm_audio && refreshed.pcm_audio; + pcm_audio |= refreshed.pcm_audio; + let mut extra = Vec::new(); + for cand in refreshed.urls { + if kind_changed + || pcm_changed + || !candidates.iter().any(|existing| existing == &cand) + { + push_unique_url(&mut extra, &cand); + } + } + if extra.is_empty() { + Err(first_err) + } else { + try_download_candidates( + engine, + &extra, + &effective_kind, + pcm_audio, + &temp_path, + ) + .await + .map_err(|extra_err| anyhow::anyhow!("{} | {}", first_err, extra_err)) + } + } } } DownloadSource::UnsignedUrl(raw_url) => { let mut candidates = Vec::new(); push_fife_candidates(&mut candidates, &raw_url, &effective_kind); push_unique_url(&mut candidates, &raw_url); - try_download_candidates(engine, &candidates, &effective_kind, &temp_path).await + try_download_candidates(engine, &candidates, &effective_kind, pcm_audio, &temp_path) + .await } }; diff --git a/src/media_files.rs b/src/media_files.rs index f3b34fb..7733e3d 100644 --- a/src/media_files.rs +++ b/src/media_files.rs @@ -132,6 +132,36 @@ fn extract_disposition_filename(disposition: &str) -> Option { ext_name.or(plain_name) } +/// Returns `true` when `ext` matches a known image, video, or audio file extension. +fn is_allowed_media_extension(ext: &str) -> bool { + matches!( + ext.to_ascii_lowercase().as_str(), + "mp4" + | "webm" + | "mov" + | "m4v" + | "avi" + | "mkv" + | "png" + | "jpg" + | "jpeg" + | "webp" + | "gif" + | "avif" + | "heic" + | "heif" + | "wav" + | "mp3" + | "m4a" + | "aac" + | "ogg" + | "opus" + | "flac" + | "aiff" + | "aif" + ) +} + /// Picks the default file extension from `content_type` or `expected_kind`. fn default_extension_for_asset(expected_kind: &str, content_type: Option<&str>) -> &'static str { match mime_essence(content_type).as_str() { @@ -166,7 +196,11 @@ fn default_extension_for_asset(expected_kind: &str, content_type: Option<&str>) | "flac" ) }) - .or_else(|| exts.first().copied()) + .or_else(|| { + exts.iter() + .copied() + .find(|&e| is_allowed_media_extension(e)) + }) }) .unwrap_or(match expected_kind { "video" => "mp4", @@ -187,7 +221,7 @@ pub(crate) fn natural_asset_filename( if Path::new(&name) .extension() .and_then(|e| e.to_str()) - .is_some_and(|e| !e.is_empty()) + .is_some_and(is_allowed_media_extension) { return name; } @@ -204,7 +238,7 @@ pub(crate) fn natural_asset_filename( && Path::new(&clean) .extension() .and_then(|e| e.to_str()) - .is_some_and(|e| !e.is_empty() && e.chars().all(|c| c.is_ascii_alphanumeric())) + .is_some_and(is_allowed_media_extension) { return clean; } diff --git a/ts/dom.ts b/ts/dom.ts index c2e9607..55266d1 100644 --- a/ts/dom.ts +++ b/ts/dom.ts @@ -4,6 +4,7 @@ // Shared DOM, event, input, and FIFE URL helpers for Flow browser modules. import { snapshotFormat } from "./frontend_builds"; +import { selectBestVideoVariant } from "./media_variants"; import type { CharacterLookEntry, FifeEnv, FlowMediaPayload, FlowTile } from "./types"; /** Reads an own data property from `o` without invoking prototype getters. */ @@ -21,6 +22,79 @@ export function asHttpOrDataUrl(v: unknown): string | null { return typeof v === "string" && /^(?:https?:|blob:|data:)/i.test(v) ? v : null; } +/** Parses an `X-Goog-Date` value (`YYYYMMDDTHHMMSSZ` or ISO-8601) into epoch milliseconds. */ +function parseGoogDateMs(raw: string): number | null { + const trimmed = raw.trim(); + const compact = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/i.exec(trimmed); + if (compact) { + const year = Number(compact[1]); + const month = Number(compact[2]); + const day = Number(compact[3]); + const hour = Number(compact[4]); + const minute = Number(compact[5]); + const second = Number(compact[6]); + if ( + month < 1 || + month > 12 || + day < 1 || + day > 31 || + hour > 23 || + minute > 59 || + second > 60 + ) { + return null; + } + const ms = Date.UTC(year, month - 1, day, hour, minute, second); + return Number.isFinite(ms) ? ms : null; + } + const isoMs = Date.parse(trimmed); + return Number.isFinite(isoMs) ? isoMs : null; +} + +/** Returns true when `rawUrl` carries a V4 or V2 GCS signature whose validity window has elapsed. */ +export function isExpiredSignedUrl( + rawUrl: string | null | undefined, + nowMs = Date.now(), +): boolean { + if (typeof rawUrl !== "string" || !/^https?:\/\//i.test(rawUrl.trim())) { + return false; + } + let parsed: URL; + try { + parsed = new URL(rawUrl.trim()); + } catch { + return false; + } + let googDate: string | null = null; + let googExpires: string | null = null; + let v2Expires: string | null = null; + let hasV2Sig = false; + for (const [k, v] of parsed.searchParams.entries()) { + const lower = k.toLowerCase(); + if (lower === "x-goog-date") googDate = v; + else if (lower === "x-goog-expires") googExpires = v; + else if (lower === "expires") v2Expires = v; + else if (lower === "signature" || lower === "googleaccessid") hasV2Sig = true; + } + if (googDate !== null && googExpires !== null) { + const issuedMs = parseGoogDateMs(googDate); + const trimmedExp = googExpires.trim(); + if (issuedMs === null || !/^\d+$/.test(trimmedExp)) { + return true; + } + const expiresSec = Number(trimmedExp); + if (!Number.isFinite(expiresSec)) return true; + return nowMs >= issuedMs + expiresSec * 1000; + } + if (hasV2Sig && v2Expires !== null) { + const trimmedV2 = v2Expires.trim(); + if (!/^\d+$/.test(trimmedV2)) return true; + const expSec = Number(trimmedV2); + return !Number.isFinite(expSec) || nowMs >= expSec * 1000; + } + return false; +} + /** Reads the first direct media URL from a tile, media payload, clip, or picker item. */ export function readMediaUrl(source: unknown, videoOnly = false): string | null { if (!source || typeof source !== "object") return null; @@ -242,10 +316,66 @@ export function characterLooksOf( return null; } -/** Extracts the preferred look image URL and primary media ID from character tile `t`. */ +/** Reads a 1-based field from a dense or sparse serialized JSPB array. */ +function serializedProtoField(message: unknown, field: number): unknown { + if (!Array.isArray(message) || field < 1) return undefined; + const tail: unknown = message[message.length - 1]; + if (tail && typeof tail === "object" && !Array.isArray(tail)) { + const mapped = readMediaField(tail, String(field)); + if (mapped !== undefined) return mapped; + } + return message[field - 1]; +} + +/** Extracts the assigned custom or preset voice ID from a character tile when present. */ +function characterAssignedVoiceId(t: FlowTile): string | null { + const format = snapshotFormat()?.character; + const entity = readMediaField(t, format?.entity ?? "Rc"); + const serialize = readMediaField(entity, "toJSON"); + if (typeof serialize === "function") { + try { + const root: unknown = serialize.call(entity); + const info = serializedProtoField( + serializedProtoField(root, format?.entityInfoField ?? 4), + format?.characterInfoField ?? 3, + ); + const refs = serializedProtoField(info, format?.audioReferencesField ?? 2); + if (Array.isArray(refs) && refs.length > 0) { + const first: unknown = refs[0]; + const custom = serializedProtoField(first, format?.customVoiceField ?? 1); + if (typeof custom === "string" && custom.trim()) { + return custom.trim().replace(/^media\//i, ""); + } + const preset = serializedProtoField(first, format?.presetVoiceField ?? 2); + if (typeof preset === "string" && preset.trim()) { + return preset.trim(); + } + } + } catch { + // Fall through to plain tile voice fields. + } + } + for (const cand of [t.voiceId, t.Vo, t.voice]) { + if (typeof cand === "string" && cand.trim()) { + return cand.trim().replace(/^media\//i, ""); + } + if (cand && typeof cand === "object" && !Array.isArray(cand)) { + const nested = + readMediaField(cand, "mediaId") ?? + readMediaField(cand, "voiceId") ?? + readMediaField(cand, "id"); + if (typeof nested === "string" && nested.trim()) { + return nested.trim().replace(/^media\//i, ""); + } + } + } + return null; +} + +/** Extracts the preferred look image URL and primary media ID (or voice ID on look-less characters) from character tile `t`. */ export function characterLookMedia( t: FlowTile | null | undefined, -): { url: string | null; primaryMediaId: string | null } { +): { url: string | null; primaryMediaId: string | null; isVoice?: boolean } { if (!t || typeof t !== "object") return { url: null, primaryMediaId: null }; const charFmt = snapshotFormat()?.character; const previewRaw = (charFmt ? readMediaField(t, charFmt.previewMediaId) : undefined) ?? t.Kd; @@ -286,9 +416,17 @@ export function characterLookMedia( } } } + const lookUrl = preferredId ? preferredUrl : fallbackUrl; + const lookPrimaryId = preferredId || firstPrimaryId; + if (!lookUrl && !lookPrimaryId && String(t.type ?? "").toUpperCase() === "CHARACTER") { + const voiceId = characterAssignedVoiceId(t); + if (voiceId) { + return { url: null, primaryMediaId: voiceId, isVoice: true }; + } + } return { - url: preferredId ? preferredUrl : fallbackUrl, - primaryMediaId: preferredId || firstPrimaryId, + url: lookUrl, + primaryMediaId: lookPrimaryId, }; } @@ -554,15 +692,23 @@ export function pickTileUrl(tile: FlowTile | null | undefined): string | null { const t = legacyTile(tile); if (!t) return null; const kind = String(t.type ?? "").toUpperCase() === "VIDEO" ? "video" : "image"; - const videoUrl = kind === "video" - ? readMediaUrl(t.Fb, true) || readMediaUrl(t, true) || readMediaUrl(t.fb, true) - : null; + const nonExpired = (cand: string | null): string | null => + cand && !isExpiredSignedUrl(cand) ? cand : null; + const variantChoice = kind === "video" ? selectBestVideoVariant(t) : null; + const videoUrl = + kind === "video" + ? variantChoice?.url || + nonExpired(readMediaUrl(t.Fb, true)) || + nonExpired(readMediaUrl(t, true)) || + nonExpired(readMediaUrl(t.fb, true)) + : null; const raw = - videoUrl || readMediaUrl(t.Fb) || - readMediaUrl(t) || - readMediaUrl(t.fb) || - characterLookMedia(t).url || - asHttpOrDataUrl(t.ue) || + videoUrl || + nonExpired(readMediaUrl(t.Fb)) || + nonExpired(readMediaUrl(t)) || + nonExpired(readMediaUrl(t.fb)) || + nonExpired(characterLookMedia(t).url) || + nonExpired(asHttpOrDataUrl(t.ue)) || null; return raw ? normalizeFlowMediaUrl(raw, kind) : null; } diff --git a/ts/fetch_media.ts b/ts/fetch_media.ts index be09e98..782c923 100644 --- a/ts/fetch_media.ts +++ b/ts/fetch_media.ts @@ -4,12 +4,143 @@ // Fetch media bytes inside Chrome using credentials matched to same-origin proxies and CDNs. import { fifeEnv } from "./dom"; +import { consumeExportedBlobUrl } from "./scene_export"; +import { runtimeState } from "./state"; import type { FetchedMediaPayload } from "./types"; +/** Default sample rate in Hz for Flow custom voice PCM audio (`BXb`). */ +const FLOW_PCM_SAMPLE_RATE = 24000; + +/** Channel count for Flow custom voice PCM audio (`BXb`). */ +const FLOW_PCM_CHANNELS = 1; + +/** Bits per sample for Flow custom voice PCM audio (`BXb`). */ +const FLOW_PCM_BITS_PER_SAMPLE = 16; + +/** Returns true when `bytes` match `ascii` starting at `offset`. */ +function hasAsciiAt(bytes: Uint8Array, ascii: string, offset = 0): boolean { + if (bytes.byteLength < offset + ascii.length) return false; + for (let i = 0; i < ascii.length; i += 1) { + if (bytes[offset + i] !== ascii.charCodeAt(i)) return false; + } + return true; +} + +/** Returns true when `bytes` already begin with a known audio, image, or video container header. */ +function hasKnownMediaContainer(bytes: Uint8Array): boolean { + if (hasAsciiAt(bytes, "RIFF") && (hasAsciiAt(bytes, "WAVE", 8) || hasAsciiAt(bytes, "WEBP", 8) || hasAsciiAt(bytes, "AVI ", 8))) { + return true; + } + if (hasAsciiAt(bytes, "fLaC") || hasAsciiAt(bytes, "OggS") || hasAsciiAt(bytes, "ID3")) { + return true; + } + if (hasAsciiAt(bytes, "FORM") && (hasAsciiAt(bytes, "AIFF", 8) || hasAsciiAt(bytes, "AIFC", 8))) { + return true; + } + if ( + bytes.byteLength >= 8 && + (hasAsciiAt(bytes, "ftyp", 4) || + hasAsciiAt(bytes, "styp", 4) || + hasAsciiAt(bytes, "moov", 4) || + hasAsciiAt(bytes, "mdat", 4) || + hasAsciiAt(bytes, "wide", 4) || + hasAsciiAt(bytes, "free", 4) || + hasAsciiAt(bytes, "skip", 4)) + ) { + return true; + } + if ( + bytes.byteLength >= 4 && + bytes[0] === 0x1a && + bytes[1] === 0x45 && + bytes[2] === 0xdf && + bytes[3] === 0xa3 + ) { + return true; + } + if (bytes.byteLength >= 2 && bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0) { + return true; + } + return false; +} + +/** Returns true when leading non-whitespace bytes match HTML, XML, playlist, or XSSI text. */ +function looksLikeMarkupPayload(bytes: Uint8Array): boolean { + let start = 0; + while ( + start < bytes.byteLength && + (bytes[start] === 0x20 || bytes[start] === 0x09 || bytes[start] === 0x0a || bytes[start] === 0x0d) + ) { + start += 1; + } + const head = Array.from(bytes.subarray(start, Math.min(bytes.byteLength, start + 16))) + .map((b) => String.fromCharCode(b)) + .join("") + .toLowerCase(); + return ( + head.startsWith(" { const kind = expectedKind ? String(expectedKind).toLowerCase() : ""; const parsed = ((): URL | null => { @@ -34,63 +165,81 @@ export async function fetchMedia( let r: Response | null = null; let lastErr: unknown = null; - for (const mode of modes) { - try { - const resp = await fetch( - u, - isSignedCdn - ? { credentials: mode, referrerPolicy: "no-referrer" } - : { credentials: mode }, - ); - if (resp.ok) { - r = resp; - break; + try { + for (const mode of modes) { + try { + const resp = await fetch( + u, + isSignedCdn + ? { credentials: mode, referrerPolicy: "no-referrer" } + : { credentials: mode }, + ); + if (resp.ok) { + r = resp; + break; + } + lastErr = new Error(`HTTP ${resp.status}`); + } catch (err) { + lastErr = err; } - lastErr = new Error(`HTTP ${resp.status}`); - } catch (err) { - lastErr = err; + } + if (!r) { + throw lastErr instanceof Error + ? lastErr + : new Error(String(lastErr || "Media fetch failed")); + } + const ct = r.headers.get("content-type") || null; + if ( + ct && + /^\s*(?:text\/|application\/(?:json|xml|dash\+xml|xhtml\+xml|vnd\.apple\.mpegurl|x-mpegurl)|audio\/mpegurl)\b/i.test( + ct, + ) + ) { + throw new Error(`Media URL returned non-media content-type: ${ct}`); + } + if (ct && kind === "video" && /^\s*(?:image|audio)\//i.test(ct)) { + throw new Error(`Media URL returned non-video content-type: ${ct}`); + } + if (ct && kind === "audio" && /^\s*(?:image|video)\//i.test(ct)) { + throw new Error(`Media URL returned non-audio content-type: ${ct}`); + } + if ( + ct && + (kind === "image" || kind === "character") && + /^\s*(?:video|audio)\//i.test(ct) + ) { + throw new Error(`Media URL returned non-image content-type: ${ct}`); + } + const buf = await r.arrayBuffer(); + const rawBytes = new Uint8Array(buf); + if (rawBytes.length === 0) { + throw new Error("Media URL returned empty body"); + } + + const explicitPcmMime = Boolean( + ct && /^\s*audio\/(?:x-)?(?:pcm|l16|raw)\b/i.test(ct), + ); + const shouldFrameWav = + kind === "audio" && + (framePcmWav || explicitPcmMime || isCachedPcmUrl(u)) && + !hasKnownMediaContainer(rawBytes) && + !looksLikeMarkupPayload(rawBytes); + const bytes = shouldFrameWav ? framePcm24kMonoWav(rawBytes) : rawBytes; + const finalCt = shouldFrameWav ? "audio/wav" : ct; + + const chunks: string[] = []; + const chunk = 0x4000; + for (let i = 0; i < bytes.length; i += chunk) { + chunks.push(String.fromCharCode(...bytes.subarray(i, i + chunk))); + } + return { + b64: btoa(chunks.join("")), + contentType: finalCt, + disposition: r.headers.get("content-disposition") || null, + }; + } finally { + if (parsed?.protocol === "blob:") { + consumeExportedBlobUrl(u); } } - if (!r) { - throw lastErr instanceof Error - ? lastErr - : new Error(String(lastErr || "Media fetch failed")); - } - const ct = r.headers.get("content-type") || null; - if ( - ct && - /^\s*(?:text\/|application\/(?:json|xml|dash\+xml|xhtml\+xml|vnd\.apple\.mpegurl|x-mpegurl)|audio\/mpegurl)\b/i.test( - ct, - ) - ) { - throw new Error(`Media URL returned non-media content-type: ${ct}`); - } - if (ct && kind === "video" && /^\s*(?:image|audio)\//i.test(ct)) { - throw new Error(`Media URL returned non-video content-type: ${ct}`); - } - if (ct && kind === "audio" && /^\s*(?:image|video)\//i.test(ct)) { - throw new Error(`Media URL returned non-audio content-type: ${ct}`); - } - if ( - ct && - (kind === "image" || kind === "character") && - /^\s*(?:video|audio)\//i.test(ct) - ) { - throw new Error(`Media URL returned non-image content-type: ${ct}`); - } - const buf = await r.arrayBuffer(); - const bytes = new Uint8Array(buf); - if (bytes.length === 0) { - throw new Error("Media URL returned empty body"); - } - const chunks: string[] = []; - const chunk = 0x4000; - for (let i = 0; i < bytes.length; i += chunk) { - chunks.push(String.fromCharCode(...bytes.subarray(i, i + chunk))); - } - return { - b64: btoa(chunks.join("")), - contentType: ct, - disposition: r.headers.get("content-disposition") || null, - }; } diff --git a/ts/index.ts b/ts/index.ts index f28568a..a6699a8 100644 --- a/ts/index.ts +++ b/ts/index.ts @@ -37,6 +37,7 @@ import { projectUpload, stageMediaFiles } from "./project_upload"; import { projectsOp } from "./projects_ops"; import { readStoreSnapshot } from "./read_store_snapshot"; import { resolveVideoUrl } from "./resolve_video_url"; +import { sceneExport } from "./scene_export"; import { sceneOp } from "./scene_ops"; import { setupGeneration } from "./setup_generation"; import { submitGeneration } from "./submit_generation"; @@ -70,6 +71,7 @@ if (!window.__flowMcp) { bindProjectStore, projectStoreStatus, fetchMedia, + sceneExport, resolveVideoUrl, setupGeneration, attachIngredients, diff --git a/ts/media_variants.ts b/ts/media_variants.ts new file mode 100644 index 0000000..5581dcd --- /dev/null +++ b/ts/media_variants.ts @@ -0,0 +1,245 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Select ready 4K and 1080p video variants from tile.yn and collect tile media IDs. + +import { readOwn } from "./angular"; +import { isExpiredSignedUrl, legacyMedia, legacyTile, readMediaUrl } from "./dom"; +import type { FlowMediaPayload, FlowTile } from "./types"; + +/** Selected media variant details for a video tile. */ +export interface SelectedVideoVariant { + /** Normalized media payload for the chosen variant or base video. */ + media: FlowMediaPayload | null; + /** Primary media ID of the chosen variant when available. */ + primaryMediaId: string | null; + /** Direct non-expired URL of the chosen variant when available on the tile. */ + url: string | null; + /** Pixel width of the chosen variant when known. */ + width: number | null; + /** Pixel height of the chosen variant when known. */ + height: number | null; + /** Duration in seconds of the chosen variant when known. */ + duration: number | null; + /** True when the chosen variant comes from `tile.yn`. */ + fromUpscale: boolean; +} + +/** Strips an optional leading `media/` prefix from a media identifier. */ +export function cleanVariantMediaId(value: unknown): string | null { + if (typeof value !== "string" && typeof value !== "number") return null; + const cleaned = String(value).trim().replace(/^media\//i, ""); + return cleaned || null; +} + +/** Returns true when `variant` has finished generating or uploading without errors. */ +export function isReadyMediaVariant(variant: FlowMediaPayload | null | undefined): boolean { + if (!variant || typeof variant !== "object") return false; + const normalized = legacyMedia(variant); + if (normalized.nf != null && normalized.nf !== "") return false; + const uploaded = readOwn(variant, "vp"); + if (uploaded === false) return false; + const source = readOwn(variant, "source"); + const status = normalized.Zc?.toLowerCase(); + if ( + status === "pending" || + status === "scheduled" || + status === "failed" || + status === "canceled" + ) { + return false; + } + if (source === "GENERATED") return status === "success"; + if (source === "UPLOADED" && typeof uploaded === "boolean" && !uploaded) return false; + return status === undefined || status === "success"; +} + +/** Reads the pixel width and height from a normalized media payload. */ +function payloadDimensions( + media: FlowMediaPayload | null | undefined, +): { width: number | null; height: number | null } { + if (!media) return { width: null, height: null }; + const width = + typeof media.width === "number" && media.width > 0 + ? media.width + : typeof media.tc?.width === "number" && media.tc.width > 0 + ? media.tc.width + : typeof media.xc?.width === "number" && media.xc.width > 0 + ? media.xc.width + : null; + const height = + typeof media.height === "number" && media.height > 0 + ? media.height + : typeof media.tc?.height === "number" && media.tc.height > 0 + ? media.tc.height + : typeof media.xc?.height === "number" && media.xc.height > 0 + ? media.xc.height + : null; + return { width, height }; +} + +/** Reads the duration in seconds from a normalized media payload. */ +function payloadDuration(media: FlowMediaPayload | null | undefined): number | null { + if (!media) return null; + if (typeof media.durationSeconds === "number") return media.durationSeconds; + if (typeof media.duration === "number") return media.duration; + if (typeof media.Lf === "number") return media.Lf; + if (typeof media.xf === "number") return media.xf; + return null; +} + +/** Returns a resolution priority rank (`3` = 4K, `2` = 1080p, `1` = base or lower). */ +export function variantResolutionRank(variant: FlowMediaPayload | null | undefined): number { + if (!variant || typeof variant !== "object") return 0; + const normalized = legacyMedia(variant); + const rawRes = readOwn(variant, "resolution") ?? normalized.resolution; + if (rawRes === 3) return 3; + if (rawRes === 2) return 2; + if (typeof rawRes === "string") { + const lower = rawRes.trim().toLowerCase(); + if (lower === "4k" || lower === "2160p") return 3; + if (lower === "1080p") return 2; + } + const { width, height } = payloadDimensions(normalized); + if (width !== null && height !== null) { + const shortEdge = Math.min(width, height); + if (shortEdge > 1200) return 3; + if (shortEdge > 800) return 2; + } + return 1; +} + +/** Reads the first non-expired video or media URL from `source`. */ +function nonExpiredVariantUrl(source: unknown): string | null { + for (const cand of [readMediaUrl(source, true), readMediaUrl(source, false)]) { + if (cand && !isExpiredSignedUrl(cand)) { + return cand; + } + } + return null; +} + +/** Selects the highest ready variant in `tile.yn` (`4K`, then `1080p`, then base). */ +export function selectBestVideoVariant(tile: FlowTile | null | undefined): SelectedVideoVariant { + const t = legacyTile(tile); + if (!t) { + return { + media: null, + primaryMediaId: null, + url: null, + width: null, + height: null, + duration: null, + fromUpscale: false, + }; + } + + const upsampled = Array.isArray(t.yn) ? t.yn : []; + let chosenUpscale: FlowMediaPayload | null = null; + let chosenRank = 1; + for (const item of upsampled) { + if (!isReadyMediaVariant(item)) continue; + const rank = variantResolutionRank(item); + if (rank >= 2 && rank >= chosenRank) { + chosenUpscale = legacyMedia(item); + chosenRank = rank; + } + } + + if (chosenUpscale) { + const variantId = + cleanVariantMediaId(readOwn(chosenUpscale, "id")) ?? + cleanVariantMediaId(chosenUpscale.mediaId); + const { width, height } = payloadDimensions(chosenUpscale); + return { + media: chosenUpscale, + primaryMediaId: variantId, + url: nonExpiredVariantUrl(chosenUpscale), + width, + height, + duration: payloadDuration(chosenUpscale), + fromUpscale: true, + }; + } + + const baseMedia = t.Fb ?? t.fb ?? null; + const baseId = + cleanVariantMediaId(t.primaryMediaId) ?? + cleanVariantMediaId(baseMedia?.id) ?? + cleanVariantMediaId(baseMedia?.mediaId) ?? + cleanVariantMediaId(t.mediaId); + const baseDims = payloadDimensions(baseMedia); + const width = + baseDims.width ?? + (typeof t.width === "number" && t.width > 0 + ? t.width + : typeof t.tc?.width === "number" && t.tc.width > 0 + ? t.tc.width + : null); + const height = + baseDims.height ?? + (typeof t.height === "number" && t.height > 0 + ? t.height + : typeof t.tc?.height === "number" && t.tc.height > 0 + ? t.tc.height + : null); + const duration = + payloadDuration(baseMedia) ?? + (typeof t.durationSeconds === "number" + ? t.durationSeconds + : typeof t.duration === "number" + ? t.duration + : typeof t.Lf === "number" + ? t.Lf + : null); + const baseUrl = + nonExpiredVariantUrl(t.Fb) ?? + nonExpiredVariantUrl(t) ?? + nonExpiredVariantUrl(t.fb); + + return { + media: baseMedia, + primaryMediaId: baseId, + url: baseUrl, + width, + height, + duration, + fromUpscale: false, + }; +} + +/** Collects all unique primary, history, and `tile.yn` media IDs from `tile`. */ +export function collectTileMediaIds( + tile: FlowTile | null | undefined, + primaryMediaId: string | null, +): string[] { + const out: string[] = []; + const pushId = (raw: unknown): void => { + const cleaned = cleanVariantMediaId(raw); + if (cleaned && !out.includes(cleaned)) { + out.push(cleaned); + } + }; + pushId(primaryMediaId); + if (!tile || typeof tile !== "object") return out; + pushId(tile.primaryMediaId); + pushId(tile.Fb?.id); + pushId(tile.Fb?.mediaId); + pushId(tile.Kb?.id); + pushId(tile.Eb?.id); + pushId(tile.fb?.mediaId); + pushId(tile.mediaId); + if (Array.isArray(tile.history)) { + for (const item of tile.history) { + pushId(readOwn(item, "id")); + pushId(readOwn(item, "mediaId")); + } + } + if (Array.isArray(tile.yn)) { + for (const item of tile.yn) { + pushId(readOwn(item, "id")); + pushId(readOwn(item, "mediaId")); + } + } + return out; +} diff --git a/ts/project_store.ts b/ts/project_store.ts index a161906..2875d9b 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -8,7 +8,13 @@ import { delay } from "./dom"; import { activeProjectStoreFormat, readBuildLabel, withMutationAliases } from "./frontend_builds"; import type { ProjectStoreFormat } from "./frontend_builds"; import { clearStore, runtimeState } from "./state"; -import type { FlowStoreHandle, FlowTile, NgLView, StoreProbeCheck } from "./types"; +import type { + CustomVoiceItem, + FlowStoreHandle, + FlowTile, + NgLView, + StoreProbeCheck, +} from "./types"; /** A Flow query for the tiles of one project. */ interface ProjectTileQuery { @@ -144,6 +150,301 @@ function tileMap(data: unknown, field: string): Map | null { return indexTileRows(readOwn(data, field)); } +/** Reads the raw settled query payload for `store` when available. */ +function readStoreQueryData(store: ProjectStore): unknown { + if (!isCurrent(store) || isProjectStorePending(store)) return null; + const query = projectQuery(store); + if (query && query.state.data != null) { + return query.state.data; + } + const signalQuery = readOwn(store.service, store.format.tileQuery); + if (!signalQuery || typeof signalQuery !== "object" || !("data" in signalQuery)) return null; + const readData = readOwn(signalQuery, "data"); + return typeof readData === "function" ? readData.call(signalQuery) : readData; +} + +/** Reads a 1-based field from a dense or sparse serialized JSPB array. */ +function voiceProtoField(msg: unknown, field: number): unknown { + if (!Array.isArray(msg) || field < 1) return undefined; + const tail: unknown = msg[msg.length - 1]; + if (tail && typeof tail === "object" && !Array.isArray(tail)) { + const mapped = readOwn(tail, String(field)); + if (mapped !== undefined) return mapped; + } + return msg[field - 1]; +} + +/** Iterates values from a `Map`, array, or plain record. */ +function mapValues(source: unknown): unknown[] { + if (source instanceof Map) return Array.from(source.values()); + if (Array.isArray(source)) return source; + if (source && typeof source === "object") return Object.values(source); + return []; +} + +/** Builds a workflow and tile display-name lookup map from `lr` and `yb`. */ +function buildVoiceNameMap(data: unknown, rowsField: string): Map { + const names = new Map(); + const register = (key: unknown, title: unknown): void => { + if (typeof key !== "string" || typeof title !== "string") return; + const cleanKey = key.trim(); + const cleanTitle = title.trim(); + if (!cleanKey || !cleanTitle) return; + names.set(cleanKey, cleanTitle); + names.set(cleanKey.replace(/^(?:media|workflows)\//i, ""), cleanTitle); + }; + + const rows = readOwn(data, rowsField); + if (Array.isArray(rows)) { + for (const row of rows) { + const displayName = readOwn(row, "displayName"); + register(readOwn(row, "id"), displayName); + register(readOwn(row, "workflowId"), displayName); + register(readOwn(row, "primaryMediaId"), displayName); + } + } + + const lr = readOwn(data, "lr"); + const lrEntries: Array<[unknown, unknown]> = + lr instanceof Map + ? Array.from(lr.entries()) + : lr && typeof lr === "object" && !Array.isArray(lr) + ? Object.entries(lr) + : []; + for (const [wfKey, wfVal] of lrEntries) { + let wfId: unknown = wfKey; + let wfTitle: unknown = readOwn(wfVal, "displayName") ?? readOwn(wfVal, "name"); + const getNameFn = readOwn(wfVal, "getName"); + if (typeof getNameFn === "function") { + try { + wfId = getNameFn.call(wfVal) ?? wfId; + } catch { + // Keep map key fallback. + } + } + const getMetaFn = readOwn(wfVal, "getMetadata"); + if (!wfTitle && typeof getMetaFn === "function") { + try { + const meta: unknown = getMetaFn.call(wfVal); + const qdFn = readOwn(meta, "Qd"); + if (typeof qdFn === "function") { + wfTitle = qdFn.call(meta); + } + } catch { + // Fall through to serialized JSON check. + } + } + const toJsonFn = readOwn(wfVal, "toJSON"); + if (!wfTitle && typeof toJsonFn === "function") { + try { + const rawWf: unknown = toJsonFn.call(wfVal); + wfId = voiceProtoField(rawWf, 1) ?? wfId; + const rawMeta = voiceProtoField(rawWf, 4) ?? voiceProtoField(rawWf, 3); + wfTitle = voiceProtoField(rawMeta, 1); + } catch { + // Ignore malformed workflow entry. + } + } + register(wfId, wfTitle); + } + return names; +} + +/** Extracts saved custom voices from `cj` and `lr` on `store` without changing `getTileMap()`. */ +function readCustomVoices(store: ProjectStore): CustomVoiceItem[] { + const data = readStoreQueryData(store); + if (!data || typeof data !== "object") return []; + const cj = readOwn(data, "cj"); + const candidates = mapValues(cj); + if (candidates.length === 0) return []; + + const nameMap = buildVoiceNameMap(data, store.format.rows); + const frontEnd = readOwn(window, "default_AiSandboxAngularFrontend"); + const hUbFn = readOwn(frontEnd, "hUb"); + const fvFn = readOwn(frontEnd, "fv"); + const brOneof = readOwn(frontEnd, "Br"); + + const out: CustomVoiceItem[] = []; + const seen = new Set(); + const lookupTitle = (wfId: string | null, mediaId: string): string | null => { + if (wfId) { + const hit = nameMap.get(wfId) ?? nameMap.get(wfId.replace(/^workflows\//i, "")); + if (hit) return hit; + } + return nameMap.get(mediaId) ?? nameMap.get(mediaId.replace(/^media\//i, "")) ?? null; + }; + + for (const item of candidates) { + if (!item || typeof item !== "object") continue; + + if ( + typeof hUbFn === "function" && + typeof fvFn === "function" && + Array.isArray(brOneof) + ) { + try { + const isAudio = Boolean( + (fvFn as (msg: unknown, field: number, oneof: unknown[]) => unknown).call( + frontEnd, + item, + 11, + brOneof, + ), + ); + if (!isAudio) continue; + const mapped = ( + hUbFn as (msg: unknown, names: Map) => Record | undefined + ).call(frontEnd, item, nameMap); + if (!mapped || mapped.Rv === true || mapped.Db === true) continue; + const rawId = String(mapped.id ?? mapped.workflowId ?? mapped.mediaId ?? "").trim(); + if (!rawId || /^voices\//i.test(rawId)) continue; + const mediaId = String(mapped.mediaId ?? rawId) + .trim() + .replace(/^(?:media|workflows)\//i, ""); + if (!mediaId || seen.has(mediaId)) continue; + seen.add(mediaId); + const wfId = + typeof mapped.workflowId === "string" && mapped.workflowId.trim() + ? mapped.workflowId.trim() + : null; + const assetId = rawId.replace(/^(?:media|workflows)\//i, "") || mediaId; + const prompt = + typeof mapped.description === "string" && mapped.description.trim() + ? mapped.description.trim() + : typeof mapped.f7 === "string" && mapped.f7.trim() + ? mapped.f7.trim() + : null; + const rawUrl = typeof mapped.NU === "string" ? mapped.NU.trim() : ""; + const created = + mapped.rm instanceof Date && mapped.rm.getTime() > 0 + ? mapped.rm.toISOString() + : null; + out.push({ + id: assetId, + name: + (typeof mapped.title === "string" && mapped.title.trim()) || + lookupTitle(wfId, mediaId) || + "Custom voice", + mediaId, + workflowId: wfId, + prompt, + url: /^https?:\/\//i.test(rawUrl) ? rawUrl : null, + createdAt: created, + }); + continue; + } catch { + // Fall through to structural JSPB and plain-object inspection. + } + } + + const toJsonFn = readOwn(item, "toJSON"); + const serialized: unknown = + typeof toJsonFn === "function" + ? (() => { + try { + return toJsonFn.call(item); + } catch { + return null; + } + })() + : Array.isArray(item) + ? item + : null; + + if (Array.isArray(serialized)) { + const audioBranch = voiceProtoField(serialized, 11); + if (!audioBranch || typeof audioBranch !== "object") continue; + const audioInner = Array.isArray(audioBranch) + ? (voiceProtoField(audioBranch, 1) ?? audioBranch) + : (readOwn(audioBranch, "1") ?? audioBranch); + if (voiceProtoField(audioInner, 3) === true) continue; + const rawName = voiceProtoField(serialized, 1); + if (typeof rawName !== "string" || !rawName.trim() || /^voices\//i.test(rawName.trim())) { + continue; + } + const mediaId = rawName.trim().replace(/^media\//i, ""); + if (!mediaId || seen.has(mediaId)) continue; + const meta = + voiceProtoField(serialized, 4) ?? + voiceProtoField(serialized, 5) ?? + voiceProtoField(serialized, 6); + if (voiceProtoField(meta, 4) === true) continue; + seen.add(mediaId); + const wfRaw = voiceProtoField(serialized, 3); + const wfId = typeof wfRaw === "string" && wfRaw.trim() ? wfRaw.trim() : null; + const metaTitle = voiceProtoField(meta, 2); + const audioName = voiceProtoField(audioInner, 1); + const title = + (typeof metaTitle === "string" && metaTitle.trim()) || + (typeof audioName === "string" && audioName.trim()) || + lookupTitle(wfId, mediaId) || + "Custom voice"; + const desc = + voiceProtoField(audioInner, 8) ?? + voiceProtoField(audioInner, 2) ?? + voiceProtoField(audioInner, 5); + const urlCand = voiceProtoField(audioInner, 4) ?? voiceProtoField(audioInner, 6); + out.push({ + id: mediaId, + name: title, + mediaId, + workflowId: wfId, + prompt: typeof desc === "string" && desc.trim() ? desc.trim() : null, + url: + typeof urlCand === "string" && /^https?:\/\//i.test(urlCand.trim()) + ? urlCand.trim() + : null, + createdAt: null, + }); + continue; + } + + if (readOwn(item, "Rv") === true || readOwn(item, "Db") === true || readOwn(item, "trashed") === true) { + continue; + } + const kindHint = String(readOwn(item, "type") ?? readOwn(item, "kind") ?? "").toUpperCase(); + const hasAudioField = + kindHint === "VOICE" || + kindHint === "AUDIO" || + readOwn(item, "audio") != null || + typeof readOwn(item, "NU") === "string"; + if (!hasAudioField) continue; + const rawId = String(readOwn(item, "mediaId") ?? readOwn(item, "id") ?? "").trim(); + if (!rawId || /^voices\//i.test(rawId)) continue; + const mediaId = rawId.replace(/^media\//i, ""); + if (!mediaId || seen.has(mediaId)) continue; + seen.add(mediaId); + const wfRaw = readOwn(item, "workflowId"); + const wfId = typeof wfRaw === "string" && wfRaw.trim() ? wfRaw.trim() : null; + const rawTitle = readOwn(item, "title") ?? readOwn(item, "displayName") ?? readOwn(item, "name"); + const rawPrompt = readOwn(item, "description") ?? readOwn(item, "prompt") ?? readOwn(item, "f7"); + const rawUrl = readOwn(item, "NU") ?? readOwn(item, "url"); + const rawCreated = readOwn(item, "rm") ?? readOwn(item, "createdAt") ?? readOwn(item, "createTime"); + out.push({ + id: mediaId, + name: + (typeof rawTitle === "string" && rawTitle.trim()) || + lookupTitle(wfId, mediaId) || + "Custom voice", + mediaId, + workflowId: wfId, + prompt: typeof rawPrompt === "string" && rawPrompt.trim() ? rawPrompt.trim() : null, + url: + typeof rawUrl === "string" && /^https?:\/\//i.test(rawUrl.trim()) + ? rawUrl.trim() + : null, + createdAt: + rawCreated instanceof Date + ? rawCreated.toISOString() + : typeof rawCreated === "string" && rawCreated.trim() + ? rawCreated.trim() + : null, + }); + } + + return out; +} + /** Reads the cached rows for the active project when the query settles. */ export function readProjectStore(store: ProjectStore): Map | null { if (!isCurrent(store) || isProjectStorePending(store)) return null; @@ -294,6 +595,7 @@ export function installProjectStore(store: ProjectStore, views?: Map isCurrent(store), getTileMap: () => readProjectStore(store), + getCustomVoices: () => readCustomVoices(store), isReady: () => isCurrent(store) && !isProjectStorePending(store), mutate: (payload) => mutateStore(store, payload), rename: (id, displayName) => diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 67e6de1..2187077 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -6,13 +6,19 @@ import { readOwn } from "./angular"; import { characterPersonalityNotes, characterVoice } from "./character_bio"; import { activeProjectStoreFormat, snapshotFormat } from "./frontend_builds"; +import { + cleanVariantMediaId, + collectTileMediaIds, + selectBestVideoVariant, +} from "./media_variants"; import { currentProjectStore, projectInRoute } from "./project_store"; -import { sceneContents } from "./scene_tiles"; +import { isSceneClipTrimmed, sceneContents } from "./scene_tiles"; import { asHttpOrDataUrl, characterLookMedia, collectionIdOf, fifeEnv as getFifeEnv, + isExpiredSignedUrl, isNonAssetTileType, isTrashedTile, legacyMedia, @@ -23,6 +29,7 @@ import { } from "./dom"; import { clearStore, runtimeState } from "./state"; import type { + CustomVoiceItem, FlowMediaPayload, FlowTile, SceneClipItem, @@ -212,7 +219,8 @@ export function readStoreSnapshot(): StoreSnapshotResult { return { ok: false, error: "store_not_bound" }; } - const { assets, collections } = readStoreTiles(tileMap); + const customVoices = helper.getCustomVoices?.() ?? []; + const { assets, collections } = readStoreTiles(tileMap, customVoices); const titleEl = document.querySelector( 'input[aria-label="Editable text"], .editable-text-input, [data-testid="project-title"]', ); @@ -229,18 +237,25 @@ export function readStoreSnapshot(): StoreSnapshotResult { return { ok: true, projectId, projectTitle, credits, assets, collections }; } -/** Reads asset and collection details from the tile map. */ -export function readStoreTiles(tileMap: Map): { +/** Reads asset and collection details from the tile map and optional custom voice list. */ +export function readStoreTiles( + tileMap: Map, + customVoices: CustomVoiceItem[] = [], +): { assets: SnapshotAssetItem[]; collections: SnapshotCollectionItem[]; } { const cols = new Map(); const counts = new Map(); const byId = new Map>(); - const sceneTiles: FlowTile[] = []; + const sceneTiles: Array<[FlowTile, ReturnType]> = []; const rawList: Omit[] = []; const env = getFifeEnv(); const collectionType = snapshotFormat()?.tileTypes.collection ?? "COLLECTION"; + const nonExpiredUrl = (raw: unknown): string | null => { + const direct = asHttpOrDataUrl(raw); + return direct && !isExpiredSignedUrl(direct) ? direct : null; + }; const isSignedUrlStr = (url: string | null): url is string => { if (url === null) return false; try { @@ -309,38 +324,140 @@ export function readStoreTiles(tileMap: Map): { : ttype === "CHARACTER" ? "character" : "image"; + let scenePrimaryMediaId: string | null = null; + let sceneRequiresExport = false; + let sceneSingleUrl: string | null = null; + let sceneWidth: number | null = null; + let sceneHeight: number | null = null; + let sceneDuration: number | null = null; if (baseKind === "scene") { - sceneTiles.push(t); + const parsedScene = sceneContents(t); + sceneTiles.push([t, parsedScene]); + const { clips, history } = parsedScene; + if (clips.length === 1) { + const c0 = clips[0]; + const wfId = c0?.workflowId ? String(c0.workflowId) : null; + const hist = wfId ? history.get(wfId) : undefined; + const clipMid = cleanVariantMediaId(c0?.primaryMediaId); + const rawClipMedia = Array.isArray(hist) + ? hist.find((x) => x && cleanVariantMediaId(x.id) === clipMid) || hist[0] || null + : null; + const m0 = legacyMedia(rawClipMedia); + if (isSceneClipTrimmed(c0, m0)) { + sceneRequiresExport = true; + } else { + const wfTile = wfId ? tileMap.get(wfId) : undefined; + const wfVariant = wfTile ? selectBestVideoVariant(wfTile) : null; + scenePrimaryMediaId = + clipMid ?? + cleanVariantMediaId(m0?.id) ?? + wfVariant?.primaryMediaId ?? + null; + const m0Status = String(m0?.Zc ?? c0?.Zc ?? "").toLowerCase(); + const m0NotReady = + m0Status === "pending" || + m0Status === "scheduled" || + m0Status === "failed" || + m0Status === "canceled" || + Boolean(m0?.nf || c0?.nf); + if (!m0NotReady) { + sceneSingleUrl = + nonExpiredUrl(readMediaUrl(m0, true)) || + nonExpiredUrl(readMediaUrl(c0, true)) || + nonExpiredUrl(readMediaUrl(m0)) || + nonExpiredUrl(readMediaUrl(c0)) || + (wfVariant && wfVariant.primaryMediaId === scenePrimaryMediaId + ? wfVariant.url + : null); + } + sceneWidth = + typeof m0?.width === "number" + ? m0.width + : typeof m0?.tc?.width === "number" + ? m0.tc.width + : wfVariant?.width ?? null; + sceneHeight = + typeof m0?.height === "number" + ? m0.height + : typeof m0?.tc?.height === "number" + ? m0.tc.height + : wfVariant?.height ?? null; + sceneDuration = + typeof c0?.nc === "number" + ? c0.nc + : typeof c0?.rc === "number" + ? c0.rc + : typeof m0?.Lf === "number" + ? m0.Lf + : wfVariant?.duration ?? null; + } + } else if (clips.length > 1) { + sceneRequiresExport = true; + } } - const charMedia = baseKind === "character" ? characterLookMedia(t) : { url: null, primaryMediaId: null }; - const charFallbackUrl = charMedia.url; - const charLookPrimaryMediaId = charMedia.primaryMediaId; + const charMedia = + baseKind === "character" + ? characterLookMedia(t) + : { url: null, primaryMediaId: null }; + const rawCharVoiceRef = charMedia.isVoice ? charMedia.primaryMediaId : null; + const cleanCharVoiceRef = rawCharVoiceRef + ? rawCharVoiceRef.replace(/^(?:media|workflows)\//i, "") + : null; + const matchedCharVoice = cleanCharVoiceRef + ? customVoices.find( + (v) => + v.id === rawCharVoiceRef || + v.id === cleanCharVoiceRef || + v.mediaId === cleanCharVoiceRef || + (v.workflowId !== null && + (v.workflowId === rawCharVoiceRef || + v.workflowId.replace(/^workflows\//i, "") === cleanCharVoiceRef)), + ) + : undefined; + const charFallbackUrl = + nonExpiredUrl(charMedia.url) ?? nonExpiredUrl(matchedCharVoice?.url); + const charLookPrimaryMediaId = matchedCharVoice + ? matchedCharVoice.mediaId + : charMedia.primaryMediaId; + const videoVariant = baseKind === "video" ? selectBestVideoVariant(t) : null; const videoMediaUrl = baseKind === "video" - ? readMediaUrl(t.Fb, true) || - readMediaUrl(t, true) || - readMediaUrl(t.fb, true) + ? videoVariant?.fromUpscale + ? videoVariant.url + : videoVariant?.url || + nonExpiredUrl(readMediaUrl(t.Fb, true)) || + nonExpiredUrl(readMediaUrl(t, true)) || + nonExpiredUrl(readMediaUrl(t.fb, true)) : null; - const mediaStatus = String(t.Fb?.Zc ?? t.fb?.Zc ?? t.Zc ?? "").toLowerCase(); - const mediaError = formatMediaError(t.Fb?.nf ?? t.fb?.nf ?? t.nf); + const activeMedia = videoVariant?.fromUpscale ? videoVariant.media : (t.Fb ?? t.fb ?? t); + const mediaStatus = String( + activeMedia?.Zc ?? t.Fb?.Zc ?? t.fb?.Zc ?? t.Zc ?? "", + ).toLowerCase(); + const mediaError = formatMediaError( + activeMedia?.nf ?? t.Fb?.nf ?? t.fb?.nf ?? t.nf, + ); const mediaNotReady = mediaStatus === "pending" || mediaStatus === "scheduled" || mediaStatus === "failed" || mediaStatus === "canceled" || - Boolean(t.Fb?.nf || t.fb?.nf || t.nf); + Boolean(activeMedia?.nf || t.Fb?.nf || t.fb?.nf || t.nf); const primaryMediaId = - charLookPrimaryMediaId || - t.primaryMediaId || - t.Fb?.id || - t.Fb?.mediaId || - t.fb?.mediaId || - t.mediaId || - null; + baseKind === "scene" + ? scenePrimaryMediaId + : baseKind === "video" + ? videoVariant?.primaryMediaId ?? null + : charLookPrimaryMediaId || + cleanVariantMediaId(t.primaryMediaId) || + cleanVariantMediaId(t.Fb?.id) || + cleanVariantMediaId(t.Fb?.mediaId) || + cleanVariantMediaId(t.fb?.mediaId) || + cleanVariantMediaId(t.mediaId) || + null; const cachedEntry = primaryMediaId ? runtimeState.mediaInfoCache.get(String(primaryMediaId)) @@ -349,22 +466,30 @@ export function readStoreTiles(tileMap: Map): { baseKind === "image" && cachedEntry?.media_kind === "audio" ? "audio" : baseKind; - const cachedMediaUrl = asHttpOrDataUrl(cachedEntry?.url); - - const tileMediaUrl = baseKind === "character" && charLookPrimaryMediaId - ? charFallbackUrl - : videoMediaUrl || - readMediaUrl(t.Fb) || - readMediaUrl(t) || - readMediaUrl(t.fb) || - charFallbackUrl || - null; + const cachedMediaUrl = nonExpiredUrl(cachedEntry?.url); + + const tileMediaUrl = + baseKind === "scene" + ? sceneSingleUrl + : baseKind === "video" && videoVariant?.fromUpscale + ? videoMediaUrl + : baseKind === "character" && charLookPrimaryMediaId + ? charFallbackUrl + : videoMediaUrl || + nonExpiredUrl(readMediaUrl(t.Fb)) || + nonExpiredUrl(readMediaUrl(t)) || + nonExpiredUrl(readMediaUrl(t.fb)) || + charFallbackUrl || + null; const rawMediaUrl = isSignedUrlStr(tileMediaUrl) ? tileMediaUrl : isSignedUrlStr(cachedMediaUrl) ? cachedMediaUrl : tileMediaUrl || cachedMediaUrl || null; - const mediaUrl = mediaNotReady ? null : rawMediaUrl; + const mediaUrl = + mediaNotReady || (baseKind === "scene" && sceneRequiresExport) + ? null + : rawMediaUrl; const bio = (ttype === "CHARACTER" ? characterPersonalityNotes(t) : null) ?? @@ -389,6 +514,12 @@ export function readStoreTiles(tileMap: Map): { null; const { start: trimStart, end: trimEnd } = videoTrimBounds(t); + const tileMediaIds = collectTileMediaIds( + t, + primaryMediaId ? String(primaryMediaId) : null, + ); + const underlyingMediaKind = + charMedia.isVoice === true ? "audio" : (cachedEntry?.media_kind ?? null); const topEntry: Omit = { id: tid, @@ -401,7 +532,7 @@ export function readStoreTiles(tileMap: Map): { : t.prompt ? String(t.prompt) : null, - url: mediaUrl ? normalizeFlowMediaUrl(String(mediaUrl), kind, env) : null, + url: mediaUrl ? normalizeFlowMediaUrl(String(mediaUrl), kind === "scene" ? "video" : kind, env) : null, collection_id: cid, primary_media_id: primaryMediaId ? String(primaryMediaId) : null, personality_notes: bio == null ? null : String(bio), @@ -411,39 +542,51 @@ export function readStoreTiles(tileMap: Map): { media_status: mediaStatus || null, media_error: mediaError, width: - typeof t.width === "number" - ? t.width - : typeof t.Fb?.width === "number" - ? t.Fb.width - : typeof t.Fb?.tc?.width === "number" - ? t.Fb.tc.width - : typeof t.tc?.width === "number" - ? t.tc.width - : null, + baseKind === "video" + ? (videoVariant?.width ?? null) + : baseKind === "scene" + ? sceneWidth + : typeof t.width === "number" + ? t.width + : typeof t.Fb?.width === "number" + ? t.Fb.width + : typeof t.Fb?.tc?.width === "number" + ? t.Fb.tc.width + : typeof t.tc?.width === "number" + ? t.tc.width + : null, height: - typeof t.height === "number" - ? t.height - : typeof t.Fb?.height === "number" - ? t.Fb.height - : typeof t.Fb?.tc?.height === "number" - ? t.Fb.tc.height - : typeof t.tc?.height === "number" - ? t.tc.height - : null, - duration: - typeof t.durationSeconds === "number" - ? t.durationSeconds - : typeof t.duration === "number" - ? t.duration - : typeof t.Fb?.durationSeconds === "number" - ? t.Fb.durationSeconds - : typeof t.Fb?.duration === "number" - ? t.Fb.duration - : typeof t.Fb?.Lf === "number" - ? t.Fb.Lf - : typeof t.Lf === "number" - ? t.Lf + baseKind === "video" + ? (videoVariant?.height ?? null) + : baseKind === "scene" + ? sceneHeight + : typeof t.height === "number" + ? t.height + : typeof t.Fb?.height === "number" + ? t.Fb.height + : typeof t.Fb?.tc?.height === "number" + ? t.Fb.tc.height + : typeof t.tc?.height === "number" + ? t.tc.height : null, + duration: + baseKind === "video" + ? (videoVariant?.duration ?? null) + : baseKind === "scene" + ? sceneDuration + : typeof t.durationSeconds === "number" + ? t.durationSeconds + : typeof t.duration === "number" + ? t.duration + : typeof t.Fb?.durationSeconds === "number" + ? t.Fb.durationSeconds + : typeof t.Fb?.duration === "number" + ? t.Fb.duration + : typeof t.Fb?.Lf === "number" + ? t.Fb.Lf + : typeof t.Lf === "number" + ? t.Lf + : null, created_at: t.hc instanceof Date ? t.hc.toISOString() @@ -452,14 +595,18 @@ export function readStoreTiles(tileMap: Map): { : t.createTime ? String(t.createTime) : null, + media_ids: tileMediaIds, + ...(baseKind === "scene" ? { requires_scene_export: sceneRequiresExport } : {}), + ...(cachedEntry?.pcm_audio || Boolean(matchedCharVoice) ? { pcm_audio: true } : {}), + ...(underlyingMediaKind ? { media_kind: underlyingMediaKind } : {}), }; rawList.push(topEntry); byId.set(tid, topEntry); } - for (const st of sceneTiles) { + for (const [st, parsedScene] of sceneTiles) { const sceneCid = collectionIdOf(st, isCollectionId); - const { clips, history } = sceneContents(st); + const { clips, history } = parsedScene; const candidates: Array< [string, SceneClipItem | null, FlowMediaPayload | null] > = []; @@ -516,16 +663,15 @@ export function readStoreTiles(tileMap: Map): { : mObj?.id ? String(mObj.id) : null; - const cachedClipVideoUrl = clipPrimaryMediaId - ? asHttpOrDataUrl( - runtimeState.mediaInfoCache.get(clipPrimaryMediaId)?.url, - ) - : null; + const cachedClipEntry = clipPrimaryMediaId + ? runtimeState.mediaInfoCache.get(clipPrimaryMediaId) + : undefined; + const cachedClipVideoUrl = nonExpiredUrl(cachedClipEntry?.url); const tileClipUrl = - readMediaUrl(mObj, true) || - readMediaUrl(clip, true) || - readMediaUrl(mObj) || - readMediaUrl(clip) || + nonExpiredUrl(readMediaUrl(mObj, true)) || + nonExpiredUrl(readMediaUrl(clip, true)) || + nonExpiredUrl(readMediaUrl(mObj)) || + nonExpiredUrl(readMediaUrl(clip)) || null; const rawClipUrl = isSignedUrlStr(tileClipUrl) ? tileClipUrl @@ -579,6 +725,7 @@ export function readStoreTiles(tileMap: Map): { : st.hc ? String(st.hc) : null; + const clipMediaIds = clipPrimaryMediaId ? [clipPrimaryMediaId] : []; const sceneEntry: Omit = { id: wfId, name: String((mObj as FlowTile | null)?.displayName || st.displayName || ""), @@ -607,12 +754,52 @@ export function readStoreTiles(tileMap: Map): { : null, duration: durVal, created_at: clipCreated, + media_ids: clipMediaIds, }; rawList.push(sceneEntry); byId.set(wfId, sceneEntry); } } + for (const voice of customVoices) { + if (!voice.id || byId.has(voice.id)) continue; + if (voice.workflowId && byId.has(voice.workflowId)) continue; + const cachedVoice = runtimeState.mediaInfoCache.get(voice.mediaId); + const directVoiceUrl = nonExpiredUrl(voice.url); + const cachedVoiceUrl = nonExpiredUrl(cachedVoice?.url); + const rawVoiceUrl = isSignedUrlStr(directVoiceUrl) + ? directVoiceUrl + : isSignedUrlStr(cachedVoiceUrl) + ? cachedVoiceUrl + : directVoiceUrl || cachedVoiceUrl || null; + const voiceMediaIds = voice.mediaId ? [voice.mediaId] : []; + const voiceEntry: Omit = { + id: voice.id, + name: voice.name, + kind: "audio", + prompt: voice.prompt, + url: rawVoiceUrl ? normalizeFlowMediaUrl(rawVoiceUrl, "audio", env) : null, + collection_id: null, + primary_media_id: voice.mediaId, + personality_notes: null, + voice: voice.name, + trim_start_seconds: null, + trim_end_seconds: null, + media_status: "success", + media_error: null, + width: null, + height: null, + duration: null, + created_at: voice.createdAt, + media_ids: voiceMediaIds, + workflow_id: voice.workflowId, + pcm_audio: true, + media_kind: "audio", + }; + rawList.push(voiceEntry); + byId.set(voice.id, voiceEntry); + } + const assets: SnapshotAssetItem[] = rawList.map((a) => ({ ...a, collection_name: a.collection_id diff --git a/ts/resolve_video_url.ts b/ts/resolve_video_url.ts index 403b2bc..d6f3325 100644 --- a/ts/resolve_video_url.ts +++ b/ts/resolve_video_url.ts @@ -3,7 +3,7 @@ // Resolve stream and download media URLs for a primary media ID via batchexecute RPC. -import { fifeEnv as getFifeEnv } from "./dom"; +import { fifeEnv as getFifeEnv, isExpiredSignedUrl } from "./dom"; import { readBuildLabel } from "./frontend_builds"; import { runtimeState } from "./state"; import type { ResolvedMediaResult } from "./types"; @@ -27,6 +27,8 @@ interface MediaExtractState { unsignedCandidates: string[]; /** Media family from the wire message. */ mediaKind: ResolvedMediaKind | null; + /** True when the `as29s` response came from case `11` PCM audio. */ + pcmAudio: boolean; } /** Returns true when `val` is a plain sparse JSPB field map object. */ @@ -79,24 +81,36 @@ export async function resolveVideoUrl( const cachedInfo = bypassCache ? undefined : runtimeState.mediaInfoCache.get(cacheKey); - if ( - cachedInfo && - typeof cachedInfo.url === "string" && - /^https?:\/\//i.test(cachedInfo.url) && - Array.isArray(cachedInfo.candidates) && - cachedInfo.candidates.length > 0 - ) { - return { - ok: true, - url: cachedInfo.url, - download_url: + if (cachedInfo && Array.isArray(cachedInfo.candidates)) { + const validCandidates = cachedInfo.candidates.filter( + (cand) => + typeof cand === "string" && + /^https?:\/\//i.test(cand) && + !isExpiredSignedUrl(cand), + ); + const validUrl = + typeof cachedInfo.url === "string" && + /^https?:\/\//i.test(cachedInfo.url) && + !isExpiredSignedUrl(cachedInfo.url) + ? cachedInfo.url + : validCandidates[0]; + if (validUrl && validCandidates.length > 0) { + const validDl = typeof cachedInfo.download_url === "string" && - /^https?:\/\//i.test(cachedInfo.download_url) + /^https?:\/\//i.test(cachedInfo.download_url) && + !isExpiredSignedUrl(cachedInfo.download_url) ? cachedInfo.download_url - : cachedInfo.url, - candidates: cachedInfo.candidates.slice(), - ...(cachedInfo.media_kind ? { media_kind: cachedInfo.media_kind } : {}), - }; + : validUrl; + return { + ok: true, + url: validUrl, + download_url: validDl, + candidates: validCandidates, + ...(cachedInfo.media_kind ? { media_kind: cachedInfo.media_kind } : {}), + ...(cachedInfo.pcm_audio ? { pcm_audio: true } : {}), + }; + } + runtimeState.mediaInfoCache.delete(cacheKey); } const { fifeHost, authuser, isSignedCdnHost } = getFifeEnv(); @@ -106,7 +120,8 @@ export async function resolveVideoUrl( const trimmed = rawUrl.trim(); if (!/^https?:\/\//i.test(trimmed)) return null; try { - return new URL(trimmed).toString(); + const normalized = new URL(trimmed).toString(); + return isExpiredSignedUrl(normalized) ? null : normalized; } catch { return null; } @@ -362,6 +377,7 @@ export async function resolveVideoUrl( } if (hasExtractedUrls(state)) { state.mediaKind ||= "audio"; + state.pcmAudio = true; } } }; @@ -444,6 +460,7 @@ export async function resolveVideoUrl( unsignedDownloadUrl: null, unsignedCandidates: [], mediaKind: null, + pcmAudio: false, }; let lastErr = await fetchAs29s([cacheKey, null, [1]], state); if ( @@ -484,6 +501,7 @@ export async function resolveVideoUrl( download_url: finalDl, candidates: candidates.slice(), ...(state.mediaKind ? { media_kind: state.mediaKind } : {}), + ...(state.pcmAudio ? { pcm_audio: true } : {}), }); return { ok: true, @@ -491,5 +509,6 @@ export async function resolveVideoUrl( download_url: finalDl, candidates: candidates.slice(), ...(state.mediaKind ? { media_kind: state.mediaKind } : {}), + ...(state.pcmAudio ? { pcm_audio: true } : {}), }; } diff --git a/ts/scene_export.ts b/ts/scene_export.ts new file mode 100644 index 0000000..f96d603 --- /dev/null +++ b/ts/scene_export.ts @@ -0,0 +1,481 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Export multi-clip or trimmed Google Flow scenes via verified Angular KD RPCs. + +import { readOwn } from "./angular"; +import { discoverStore } from "./discover_store"; +import { delay, isTrashedTile, legacyMedia } from "./dom"; +import { readBuildLabel } from "./frontend_builds"; +import { currentProjectStore, projectInRoute } from "./project_store"; +import { sceneExportFormat, type SceneExportBuildFormat } from "./scene_export_builds"; +import { sceneContents } from "./scene_tiles"; +import { runtimeState } from "./state"; +import type { FlowMediaPayload, SceneClipItem, SceneExportResult } from "./types"; + +/** Maximum number of `IxdSwd` status polls per scene export job. */ +const MAX_SCENE_EXPORT_POLLS = 40; + +/** Default poll interval in milliseconds matching Flow `vHb`. */ +const DEFAULT_POLL_DELAY_MS = 3000; + +/** Time in milliseconds to retain an unconsumed exported `blob:` URL. */ +const EXPORT_BLOB_TTL_MS = 120_000; + +/** Active exported `blob:` URLs awaiting browser fetch and revocation. */ +const exportedBlobUrls = new Map>(); + +/** Minimal shape of the Angular `KD` (`ImmutableGenericDataInterface`) client. */ +interface GenericDataClient { + /** Sends a unary RPC request built by `kx.prototype.Eb`. */ + fetch: (request: unknown) => Promise; +} + +/** Constructable JSPB message class. */ +type ProtoCtor = new (raw?: unknown) => object; + +/** Constructable unary RPC descriptor class (`kx`). */ +type UnaryDescriptorCtor = new (spec: Record) => { + /** Builds a unary RPC transport request from a cloned JSPB message. */ + Eb: (message: unknown) => unknown; +}; + +/** Verified runtime functions and constructors bound from the Flow namespace. */ +interface BoundSceneExportSymbols { + /** Angular DI token for `KD`. */ + dataToken: unknown; + /** Optional Angular video service constructor (`bO`). */ + videoServiceCtor: Function | null; + /** Unary RPC descriptor constructor (`kx`). */ + UnaryDescriptor: UnaryDescriptorCtor; + /** Marker symbol or key set to `true` on raw descriptor objects (`Zw`). */ + descriptorMarker: PropertyKey; + /** Base JSPB message class (`n`). */ + ProtoBase: ProtoCtor; + /** Request constructor for `GjQLTd`. */ + StartRequest: ProtoCtor; + /** Response constructor for `GjQLTd`. */ + StartResponse: ProtoCtor; + /** Request constructor for `IxdSwd`. */ + PollRequest: ProtoCtor; + /** Response constructor for `IxdSwd`. */ + PollResponse: ProtoCtor; + /** Clip message constructor (`WBb`). */ + ClipMessage: ProtoCtor; + /** Sets the clip media ID field (`TBb`). */ + setClipMediaId: (msg: object, mediaId: string) => object; + /** Sets the clip start duration field (`UBb`). */ + setClipStart: (msg: object, duration: unknown) => object; + /** Sets the clip end duration field (`VBb`). */ + setClipEnd: (msg: object, duration: unknown) => object; + /** Converts seconds to a frozen `Duration` proto (`zK`). */ + secondsToDuration: (seconds: number) => unknown; + /** Normalizes a media resource ID (`Iq`). */ + cleanMediaId: (mediaId: string) => string; + /** Freezes a JSPB message (`dr`). */ + freezeMsg: (msg: object) => object; + /** Clones a JSPB message for RPC transport (`cc`). */ + cloneMsg: (msg: object) => unknown; + /** Sets a repeated submessage array (`mv`). */ + setRepeatedSubmessage: (msg: object, field: number, items: unknown[]) => object; + /** Sets a singular submessage (`al`). */ + setSubmessage: (msg: object, ctor: ProtoCtor, field: number, value: unknown) => object; + /** Reads a singular submessage (`X`). */ + getSubmessage: (msg: unknown, ctor: ProtoCtor, field: number) => unknown; + /** Reads a byte field (`iv`). */ + getBytesField: (msg: unknown, field: number) => unknown; + /** Converts a JSPB byte wrapper into a `Uint8Array` (`Tc`). */ + bytesToUint8Array: (bytes: unknown) => Uint8Array; +} + +/** Revokes and forgets an exported scene `blob:` URL if tracked. */ +export function consumeExportedBlobUrl(url: string): void { + const timer = exportedBlobUrls.get(url); + if (timer !== undefined) { + clearTimeout(timer); + exportedBlobUrls.delete(url); + try { + URL.revokeObjectURL(url); + } catch { + // Ignore revocation failures on already-released object URLs. + } + } +} + +/** Registers an exported `blob:` URL with a bounded lifetime. */ +function trackExportedBlobUrl(url: string): void { + const timer = setTimeout(() => { + exportedBlobUrls.delete(url); + try { + URL.revokeObjectURL(url); + } catch { + // Ignore revocation failures on expired object URLs. + } + }, EXPORT_BLOB_TTL_MS); + exportedBlobUrls.set(url, timer); +} + +/** Resolves and validates all compiled Angular symbols required by `format`. */ +async function bindSceneExportSymbols( + format: SceneExportBuildFormat, +): Promise { + const ns = readOwn(window, format.namespace); + if (!ns || typeof ns !== "object") return null; + + if (typeof readOwn(ns, format.clipCtor) !== "function") { + const loader = readOwn(ns, format.moduleLoader); + if (typeof loader === "function") { + try { + await Promise.resolve((loader as (chunk: string) => unknown).call(ns, format.projectChunk)); + } catch { + // Symbol check below reports unsupported_front_end when chunk loading fails. + } + } + } + + const dataToken = readOwn(ns, format.dataToken); + const videoServiceRaw = readOwn(ns, format.videoService); + const UnaryDescriptor = readOwn(ns, format.unaryDescriptorCtor); + const descriptorMarker = readOwn(ns, format.descriptorMarker); + const ProtoBase = readOwn(ns, format.protoBaseCtor); + const StartRequest = readOwn(ns, format.startRequestCtor); + const StartResponse = readOwn(ns, format.startResponseCtor); + const PollRequest = readOwn(ns, format.pollRequestCtor); + const PollResponse = readOwn(ns, format.pollResponseCtor); + const ClipMessage = readOwn(ns, format.clipCtor); + const setClipMediaId = readOwn(ns, format.setClipMediaId); + const setClipStart = readOwn(ns, format.setClipStart); + const setClipEnd = readOwn(ns, format.setClipEnd); + const secondsToDuration = readOwn(ns, format.secondsToDuration); + const cleanMediaId = readOwn(ns, format.cleanMediaId); + const freezeMsg = readOwn(ns, format.freezeMsg); + const cloneMsg = readOwn(ns, format.cloneMsg); + const setRepeatedSubmessage = readOwn(ns, format.setRepeatedSubmessage); + const setSubmessage = readOwn(ns, format.setSubmessage); + const getSubmessage = readOwn(ns, format.getSubmessage); + const getBytesField = readOwn(ns, format.getBytesField); + const bytesToUint8Array = readOwn(ns, format.bytesToUint8Array); + + if ( + !dataToken || + typeof UnaryDescriptor !== "function" || + (typeof descriptorMarker !== "symbol" && typeof descriptorMarker !== "string") || + typeof ProtoBase !== "function" || + typeof StartRequest !== "function" || + typeof StartResponse !== "function" || + typeof PollRequest !== "function" || + typeof PollResponse !== "function" || + typeof ClipMessage !== "function" || + typeof setClipMediaId !== "function" || + typeof setClipStart !== "function" || + typeof setClipEnd !== "function" || + typeof secondsToDuration !== "function" || + typeof cleanMediaId !== "function" || + typeof freezeMsg !== "function" || + typeof cloneMsg !== "function" || + typeof setRepeatedSubmessage !== "function" || + typeof setSubmessage !== "function" || + typeof getSubmessage !== "function" || + typeof getBytesField !== "function" || + typeof bytesToUint8Array !== "function" + ) { + return null; + } + + return { + dataToken, + videoServiceCtor: typeof videoServiceRaw === "function" ? videoServiceRaw : null, + UnaryDescriptor: UnaryDescriptor as UnaryDescriptorCtor, + descriptorMarker, + ProtoBase: ProtoBase as ProtoCtor, + StartRequest: StartRequest as ProtoCtor, + StartResponse: StartResponse as ProtoCtor, + PollRequest: PollRequest as ProtoCtor, + PollResponse: PollResponse as ProtoCtor, + ClipMessage: ClipMessage as ProtoCtor, + setClipMediaId: setClipMediaId as BoundSceneExportSymbols["setClipMediaId"], + setClipStart: setClipStart as BoundSceneExportSymbols["setClipStart"], + setClipEnd: setClipEnd as BoundSceneExportSymbols["setClipEnd"], + secondsToDuration: secondsToDuration as BoundSceneExportSymbols["secondsToDuration"], + cleanMediaId: cleanMediaId as BoundSceneExportSymbols["cleanMediaId"], + freezeMsg: freezeMsg as BoundSceneExportSymbols["freezeMsg"], + cloneMsg: cloneMsg as BoundSceneExportSymbols["cloneMsg"], + setRepeatedSubmessage: + setRepeatedSubmessage as BoundSceneExportSymbols["setRepeatedSubmessage"], + setSubmessage: setSubmessage as BoundSceneExportSymbols["setSubmessage"], + getSubmessage: getSubmessage as BoundSceneExportSymbols["getSubmessage"], + getBytesField: getBytesField as BoundSceneExportSymbols["getBytesField"], + bytesToUint8Array: bytesToUint8Array as BoundSceneExportSymbols["bytesToUint8Array"], + }; +} + +/** Returns `candidate` when it implements `KD.fetch`. */ +function asDataClient(candidate: unknown): GenericDataClient | null { + if (!candidate || typeof candidate !== "object") return null; + const fetchFn = readOwn(candidate, "fetch"); + return typeof fetchFn === "function" ? (candidate as GenericDataClient) : null; +} + +/** Resolves the live `KD` data client from the bound project store or Angular views. */ +function locateDataClient( + format: SceneExportBuildFormat, + symbols: BoundSceneExportSymbols, +): GenericDataClient | null { + const projectId = projectInRoute() ?? runtimeState.projectId; + const store = projectId ? currentProjectStore(projectId) : null; + if (store) { + const tilesService = readOwn(store.service, store.format.tilesService); + const direct = asDataClient(readOwn(tilesService, format.serviceDataField)); + if (direct) return direct; + if (tilesService && typeof tilesService === "object") { + for (const key of Object.keys(tilesService)) { + const sub = readOwn(tilesService, key); + const nested = + asDataClient(sub) ?? asDataClient(readOwn(sub, format.serviceDataField)); + if (nested) return nested; + } + } + } + + const views = runtimeState.ngLViewMap; + if (views instanceof Map) { + for (const view of views.values()) { + if (!Array.isArray(view)) continue; + for (const slot of view) { + if (!slot || typeof slot !== "object" || slot instanceof Node) continue; + if (symbols.videoServiceCtor && slot instanceof symbols.videoServiceCtor) { + const fromSvc = asDataClient(readOwn(slot, format.serviceDataField)); + if (fromSvc) return fromSvc; + } + const injector = readOwn(slot, "Ab") ?? slot; + const getFn = readOwn(injector, "get"); + if (typeof getFn === "function") { + try { + const kd: unknown = getFn.call(injector, symbols.dataToken, null); + const client = asDataClient(kd); + if (client) return client; + } catch { + // Ignore non-Angular get methods. + } + if (symbols.videoServiceCtor) { + try { + const svc: unknown = getFn.call(injector, symbols.videoServiceCtor, null); + const client = asDataClient(readOwn(svc, format.serviceDataField)); + if (client) return client; + } catch { + // Ignore optional video service lookup misses. + } + } + } + } + } + } + return null; +} + +/** Builds a frozen clip export protobuf message matching the scene download handler of Flow. */ +function buildClipMessage( + clip: SceneClipItem, + media: FlowMediaPayload | null, + symbols: BoundSceneExportSymbols, +): object | null { + const rawMediaId = + clip.primaryMediaId != null + ? String(clip.primaryMediaId).trim() + : media?.id != null + ? String(media.id).trim() + : ""; + if (!rawMediaId) return null; + const mediaId = symbols.cleanMediaId(rawMediaId); + if (!mediaId) return null; + + const duration = + typeof clip.nc === "number" && Number.isFinite(clip.nc) && clip.nc > 0 + ? clip.nc + : typeof clip.rc === "number" && Number.isFinite(clip.rc) && clip.rc > 0 + ? clip.rc + : typeof media?.durationSeconds === "number" && media.durationSeconds > 0 + ? media.durationSeconds + : typeof media?.Lf === "number" && media.Lf > 0 + ? media.Lf + : 8; + const startSec = + typeof clip.Ji === "number" && Number.isFinite(clip.Ji) + ? Math.max(0, clip.Ji) + : typeof clip.Mh === "number" && Number.isFinite(clip.Mh) + ? Math.max(0, clip.Mh) + : typeof media?.Jc === "number" && Number.isFinite(media.Jc) + ? Math.max(0, media.Jc) + : 0; + const rawEnd = + typeof clip.Ci === "number" && Number.isFinite(clip.Ci) && clip.Ci > 0 + ? clip.Ci + : typeof clip.Eh === "number" && Number.isFinite(clip.Eh) && clip.Eh > 0 + ? clip.Eh + : typeof media?.Pc === "number" && Number.isFinite(media.Pc) && media.Pc > 0 + ? media.Pc + : duration; + const endSec = Math.max(startSec, rawEnd); + + const msg = new symbols.ClipMessage(); + const withMedia = symbols.setClipMediaId(msg, mediaId); + const withStart = symbols.setClipStart(withMedia, symbols.secondsToDuration(startSec)); + const withEnd = symbols.setClipEnd(withStart, symbols.secondsToDuration(endSec)); + return symbols.freezeMsg(withEnd); +} + +/** Exports a multi-clip or trimmed scene through `GjQLTd` and `IxdSwd` on `KD`. */ +export async function sceneExport( + sceneId: string, + pollDelayMs?: number, +): Promise { + const format = sceneExportFormat(readBuildLabel()); + if (!format) { + return { ok: false, error: "unsupported_front_end" }; + } + const symbols = await bindSceneExportSymbols(format); + if (!symbols) { + return { ok: false, error: "unsupported_front_end" }; + } + + const trimmedId = String(sceneId || "").trim(); + if (!trimmedId) { + return { ok: false, error: "missing_scene_id" }; + } + + if (!runtimeState.store || !runtimeState.store.isCurrent() || !runtimeState.store.isReady()) { + await discoverStore(); + } + const tileMap = runtimeState.store?.getTileMap?.(); + if (!(tileMap instanceof Map)) { + return { ok: false, error: "store_not_bound" }; + } + const sceneTile = tileMap.get(trimmedId); + if ( + !sceneTile || + isTrashedTile(sceneTile) || + String(sceneTile.type ?? "").toUpperCase() !== "SCENE" + ) { + return { ok: false, error: "scene_not_found" }; + } + + const { clips, history } = sceneContents(sceneTile); + if (clips.length === 0) { + return { ok: false, error: "scene_empty" }; + } + + const clipMessages: object[] = []; + for (const clip of clips) { + const wfId = clip.workflowId != null ? String(clip.workflowId) : ""; + const histList = wfId ? history.get(wfId) : undefined; + const rawClipMid = clip.primaryMediaId != null ? symbols.cleanMediaId(String(clip.primaryMediaId)) : ""; + const rawMedia = Array.isArray(histList) + ? histList.find((m) => m && symbols.cleanMediaId(String(m.id ?? "")) === rawClipMid) ?? + histList[0] ?? + null + : null; + const built = buildClipMessage(clip, legacyMedia(rawMedia), symbols); + if (!built) { + return { ok: false, error: "scene_clip_missing_media_id" }; + } + clipMessages.push(built); + } + + let dataClient = locateDataClient(format, symbols); + if (!dataClient) { + await discoverStore(); + dataClient = locateDataClient(format, symbols); + } + if (!dataClient) { + return { ok: false, error: "scene_export_service_unavailable" }; + } + + const startSpec: Record = { + Xa: format.startRpcId, + kb: undefined, + hb: true, + Ya: symbols.StartResponse, + lb: symbols.StartRequest, + }; + startSpec[symbols.descriptorMarker] = true; + const startDescriptor = new symbols.UnaryDescriptor(startSpec); + + const pollSpec: Record = { + Xa: format.pollRpcId, + kb: undefined, + hb: true, + Ya: symbols.PollResponse, + lb: symbols.PollRequest, + }; + pollSpec[symbols.descriptorMarker] = true; + const pollDescriptor = new symbols.UnaryDescriptor(pollSpec); + + const OpTokenCtor = class extends symbols.ProtoBase { + constructor(raw?: unknown) { + super(raw); + } + }; + + try { + const startReq = symbols.setRepeatedSubmessage( + new symbols.StartRequest(), + format.startClipsField, + clipMessages, + ); + const startResp = await dataClient.fetch(startDescriptor.Eb(symbols.cloneMsg(startReq))); + const operationToken = symbols.getSubmessage( + startResp, + OpTokenCtor, + format.startOperationField, + ); + if (!operationToken) { + return { ok: false, error: "scene_export_missing_operation" }; + } + + const waitMs = + typeof pollDelayMs === "number" && Number.isFinite(pollDelayMs) && pollDelayMs >= 0 + ? pollDelayMs + : DEFAULT_POLL_DELAY_MS; + + for (let attempt = 0; attempt < MAX_SCENE_EXPORT_POLLS; attempt += 1) { + if (waitMs > 0) { + await delay(attempt === 0 ? Math.min(1000, waitMs) : waitMs); + } + const pollReq = symbols.setSubmessage( + new symbols.PollRequest(), + OpTokenCtor, + format.pollOperationField, + operationToken, + ); + const pollResp = await dataClient.fetch(pollDescriptor.Eb(symbols.cloneMsg(pollReq))); + const statusFn = readOwn(pollResp, format.pollStatusMethod); + const status = + typeof statusFn === "function" ? statusFn.call(pollResp) : undefined; + + if (status === 3) { + const rawBytesField = symbols.getBytesField(pollResp, format.pollBytesField); + const mp4Bytes = rawBytesField == null ? null : symbols.bytesToUint8Array(rawBytesField); + if (!mp4Bytes || mp4Bytes.byteLength === 0) { + return { ok: false, error: "scene_export_empty_payload" }; + } + const safeBytes = new Uint8Array(mp4Bytes.byteLength); + safeBytes.set(mp4Bytes); + const blobUrl = URL.createObjectURL(new Blob([safeBytes], { type: "video/mp4" })); + trackExportedBlobUrl(blobUrl); + return { ok: true, url: blobUrl, contentType: "video/mp4" }; + } + if (status === 1 || status === 2 || status === 6) { + continue; + } + if (status === 0 || status === 4 || status === 5 || status === 7) { + return { ok: false, error: `scene_export_failed_${String(status)}` }; + } + return { ok: false, error: `scene_export_unexpected_status_${String(status)}` }; + } + + return { ok: false, error: "scene_export_timeout" }; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + return { ok: false, error: message || "scene_export_rpc_failed" }; + } +} diff --git a/ts/scene_export_builds.ts b/ts/scene_export_builds.ts new file mode 100644 index 0000000..96be9f3 --- /dev/null +++ b/ts/scene_export_builds.ts @@ -0,0 +1,121 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Verified Angular symbol descriptors for multi-clip and trimmed scene exports. + +/** Compiled symbol and field layout for Flow scene export RPCs on one build. */ +export interface SceneExportBuildFormat { + /** Global Closure namespace object on `window`. */ + namespace: string; + /** Optional lazy chunk loader function on the namespace. */ + moduleLoader: string; + /** Lazy route module ID that registers scene clip protobuf helpers. */ + projectChunk: string; + /** Angular DI token for `ImmutableGenericDataInterface`. */ + dataToken: string; + /** Angular video and export service constructor holding the data client. */ + videoService: string; + /** Field on the project tiles or video service that stores the `KD` client. */ + serviceDataField: string; + /** Unary RPC descriptor constructor (`kx`). */ + unaryDescriptorCtor: string; + /** Symbol property marking raw RPC descriptor objects (`Zw`). */ + descriptorMarker: string; + /** Base Closure JSPB message class (`n`). */ + protoBaseCtor: string; + /** RPC ID that starts an asynchronous scene export job. */ + startRpcId: string; + /** Request message constructor for `startRpcId`. */ + startRequestCtor: string; + /** Response message constructor for `startRpcId`. */ + startResponseCtor: string; + /** Repeated clip submessage field number on the start request. */ + startClipsField: number; + /** Operation token submessage field number on the start response. */ + startOperationField: number; + /** RPC ID that polls a running scene export job. */ + pollRpcId: string; + /** Request message constructor for `pollRpcId`. */ + pollRequestCtor: string; + /** Response message constructor for `pollRpcId`. */ + pollResponseCtor: string; + /** Operation token submessage field number on the poll request. */ + pollOperationField: number; + /** Method on the poll response returning the numeric job state. */ + pollStatusMethod: string; + /** Exported MP4 byte payload field number on the poll response. */ + pollBytesField: number; + /** Scene clip message constructor (`WBb`). */ + clipCtor: string; + /** Helper setting the clip primary media ID on a clip message (`TBb`). */ + setClipMediaId: string; + /** Helper setting the clip start `Duration` on a clip message (`UBb`). */ + setClipStart: string; + /** Helper setting the clip end `Duration` on a clip message (`VBb`). */ + setClipEnd: string; + /** Helper converting finite seconds into a frozen `Duration` message (`zK`). */ + secondsToDuration: string; + /** Helper normalizing a media resource name (`Iq`). */ + cleanMediaId: string; + /** Helper freezing a JSPB message (`dr`). */ + freezeMsg: string; + /** Helper cloning or finalizing a JSPB message for wire transport (`cc`). */ + cloneMsg: string; + /** Helper setting a repeated submessage array on a JSPB message (`mv`). */ + setRepeatedSubmessage: string; + /** Helper setting a singular submessage field on a JSPB message (`al`). */ + setSubmessage: string; + /** Helper reading a singular submessage field from a JSPB message (`X`). */ + getSubmessage: string; + /** Helper reading a byte string field from a JSPB message (`iv`). */ + getBytesField: string; + /** Helper converting a JSPB byte string wrapper into a `Uint8Array` (`Tc`). */ + bytesToUint8Array: string; +} + +/** Verified scene export symbol table for `boq_labs-ai-sandbox-frontend_20261120.00_p0`. */ +const NOVEMBER_20_SCENE_EXPORT: SceneExportBuildFormat = { + namespace: "default_AiSandboxAngularFrontend", + moduleLoader: "bn", + projectChunk: "wO1vlb", + dataToken: "KD", + videoService: "bO", + serviceDataField: "ha", + unaryDescriptorCtor: "kx", + descriptorMarker: "Zw", + protoBaseCtor: "n", + startRpcId: "GjQLTd", + startRequestCtor: "aVa", + startResponseCtor: "cVa", + startClipsField: 1, + startOperationField: 2, + pollRpcId: "IxdSwd", + pollRequestCtor: "XUa", + pollResponseCtor: "ZUa", + pollOperationField: 1, + pollStatusMethod: "Pf", + pollBytesField: 5, + clipCtor: "WBb", + setClipMediaId: "TBb", + setClipStart: "UBb", + setClipEnd: "VBb", + secondsToDuration: "zK", + cleanMediaId: "Iq", + freezeMsg: "dr", + cloneMsg: "cc", + setRepeatedSubmessage: "mv", + setSubmessage: "al", + getSubmessage: "X", + getBytesField: "iv", + bytesToUint8Array: "Tc", +}; + +/** Verified scene export formats indexed by exact Flow build label. */ +const VERIFIED_SCENE_EXPORT_BUILDS: ReadonlyMap = new Map([ + ["boq_labs-ai-sandbox-frontend_20261120.00_p0", NOVEMBER_20_SCENE_EXPORT], +]); + +/** Returns the verified scene export symbol format for `label`, or undefined. */ +export function sceneExportFormat(label: string | null): SceneExportBuildFormat | undefined { + return label === null ? undefined : VERIFIED_SCENE_EXPORT_BUILDS.get(label); +} diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index df2b2b4..24bb600 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -20,3 +20,40 @@ export function sceneContents(tile: FlowTile) { history: new Map(Array.from(entries, ([id, media]) => [String(id), media])), }; } + +/** Returns true when `clip` trims the start or end of its underlying video duration. */ +export function isSceneClipTrimmed( + clip: SceneClipItem | null | undefined, + media: FlowMediaPayload | null | undefined, +): boolean { + if (!clip) return false; + const dur = + typeof clip.nc === "number" && Number.isFinite(clip.nc) && clip.nc > 0 + ? clip.nc + : typeof clip.rc === "number" && Number.isFinite(clip.rc) && clip.rc > 0 + ? clip.rc + : typeof media?.durationSeconds === "number" && media.durationSeconds > 0 + ? media.durationSeconds + : typeof media?.Lf === "number" && media.Lf > 0 + ? media.Lf + : 8; + const startRaw = + typeof clip.Ji === "number" && Number.isFinite(clip.Ji) + ? clip.Ji + : typeof clip.Mh === "number" && Number.isFinite(clip.Mh) + ? clip.Mh + : typeof media?.Jc === "number" && Number.isFinite(media.Jc) + ? media.Jc + : 0; + const start = Math.max(0, startRaw); + const endRaw = + typeof clip.Ci === "number" && Number.isFinite(clip.Ci) && clip.Ci > 0 + ? clip.Ci + : typeof clip.Eh === "number" && Number.isFinite(clip.Eh) && clip.Eh > 0 + ? clip.Eh + : typeof media?.Pc === "number" && Number.isFinite(media.Pc) && media.Pc > 0 + ? media.Pc + : dur; + const end = Math.min(endRaw, dur); + return end > start && (start > 0 || end < dur - 0.01); +} diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..1405bb6 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -256,6 +256,10 @@ export interface FlowTile extends FlowMediaPayload { Oc?: SceneClipItem[]; /** Scene clip workflow history lookup. */ Yf?: Map | Record; + /** Media generation history list on image and video tiles. */ + history?: FlowMediaPayload[]; + /** Upscaled video variant list (`1080p` and `4K`) in build 20261120.00. */ + yn?: FlowMediaPayload[]; /** Tile width alias. */ width?: number; /** Tile height alias. */ @@ -264,6 +268,24 @@ export interface FlowTile extends FlowMediaPayload { createDate?: string; } +/** Saved custom voice entry extracted from `PROJECT_TILES` `cj` and `lr` maps. */ +export interface CustomVoiceItem { + /** Voice asset identifier. */ + id: string; + /** Human-readable voice display name. */ + name: string; + /** Underlying audio media identifier for `as29s` resolution. */ + mediaId: string; + /** Optional workflow identifier associated with the voice. */ + workflowId: string | null; + /** Voice performance description or sample text. */ + prompt: string | null; + /** Direct audio URL when present on the voice proto. */ + url: string | null; + /** ISO creation timestamp string when known. */ + createdAt: string | null; +} + /** Unified project store handle bound into module state. */ export interface FlowStoreHandle { /** Active project identifier extracted from the route. */ @@ -272,6 +294,8 @@ export interface FlowStoreHandle { isCurrent: () => boolean; /** Returns the current project tile map if available. */ getTileMap: () => Map | null | undefined; + /** Returns saved custom voices from `cj` and `lr` without altering `getTileMap()`. */ + getCustomVoices?: () => CustomVoiceItem[]; /** Returns true when pending store fetches have settled. */ isReady: () => boolean; /** Dispatches a store mutation payload and waits for completion. */ @@ -486,6 +510,8 @@ export interface CachedMediaInfo { candidates: string[]; /** Media kind from the wire response when known. */ media_kind?: "video" | "image" | "audio"; + /** True when `as29s` case `11` returned raw 24 kHz PCM audio requiring WAV framing. */ + pcm_audio?: boolean; } /** Result returned by `checkAuth`. */ @@ -554,6 +580,16 @@ export interface SnapshotAssetItem { duration: number | null; /** ISO creation timestamp string. */ created_at: string | null; + /** All known primary, history, and upscaled variant media IDs on the tile. */ + media_ids?: string[]; + /** Optional workflow identifier associated with a custom voice asset. */ + workflow_id?: string | null; + /** True when a multi-clip or trimmed scene requires Angular `sceneExport`. */ + requires_scene_export?: boolean; + /** True when cached resolution flagged raw 24 kHz PCM audio. */ + pcm_audio?: boolean; + /** Underlying media family override when a tile downloads audio. */ + media_kind?: "video" | "image" | "audio" | null; } /** Collection summary returned inside `StoreSnapshotResult`. */ @@ -615,6 +651,16 @@ export type ResolvedMediaResult = download_url: string; candidates: string[]; media_kind?: "video" | "image" | "audio"; + pcm_audio?: boolean; + }; + +/** Result returned by `sceneExport`. */ +export type SceneExportResult = + | { ok: false; error: string } + | { + ok: true; + url: string; + contentType: string; }; /** Configuration payload shared by `setupGeneration` and `attachIngredients`. */ @@ -832,7 +878,13 @@ export interface FlowMcpRuntime { request: import("./collection_ops").CollectionRequest, ) => Promise; /** Fetches a media URL with page credentials and returns Base64 payload metadata. */ - fetchMedia: (u: string, expectedKind: string) => Promise; + fetchMedia: ( + u: string, + expectedKind: string, + framePcmWav?: boolean, + ) => Promise; + /** Exports a multi-clip or trimmed scene via Angular `KD` RPCs and returns a `blob:` URL. */ + sceneExport: (sceneId: string, pollDelayMs?: number) => Promise; /** Resolves stream and download URLs for a primary media identifier via `as29s`. */ resolveVideoUrl: ( primaryMediaId: string, From d624e0b7407007241c06f6c2328901a05eb31484 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:30:13 +0000 Subject: [PATCH 2/2] fix: harden WAV framing, scene export budget, and quality selection - Reject leading JSON or XML error bytes before PCM WAV framing - Verify two MPEG or ADTS frames so FF FF PCM gets a WAV header - Cap sceneExport at 25 polls and 90 s below the 120 s CDP limit - Map GI video resolution codes per build and add quality option - Resolve : clips without triggering scene export - Split voice, URL, and matching helpers to keep files small --- docs/en/tools-reference.md | 5 +- docs/ja/tools-reference.md | 5 +- docs/zh-CN/tools-reference.md | 5 +- src/asset_matching.rs | 268 ++++++++++++++++++++ src/assets.rs | 210 ++++------------ src/characters.rs | 115 +-------- src/download.rs | 461 ++++++++++++---------------------- src/download_urls.rs | 304 ++++++++++++++++++++++ src/main.rs | 2 + src/mcp.rs | 6 +- src/media_files.rs | 52 +++- src/service.rs | 8 +- src/voices.rs | 112 ++++++++- ts/custom_voices.ts | 445 ++++++++++++++++++++++++++++++++ ts/dom.ts | 77 +----- ts/fetch_media.ts | 115 ++++++++- ts/frontend_builds.ts | 18 ++ ts/media_variants.ts | 276 +++++++++++++------- ts/project_store.ts | 287 +-------------------- ts/read_store_snapshot.ts | 233 +++++------------ ts/scene_export.ts | 87 ++++++- ts/scene_tiles.ts | 173 ++++++++++++- ts/types.ts | 39 ++- 23 files changed, 2080 insertions(+), 1223 deletions(-) create mode 100644 src/asset_matching.rs create mode 100644 src/download_urls.rs create mode 100644 ts/custom_voices.ts diff --git a/docs/en/tools-reference.md b/docs/en/tools-reference.md index 012a910..ea32f09 100644 --- a/docs/en/tools-reference.md +++ b/docs/en/tools-reference.md @@ -387,11 +387,12 @@ The tool checks the result of each write in a new read of the same project. The ### `flow_download` -Download a matching project media asset (image, video, upscaled `1080p` or `4K` variant, custom voice, character look or assigned voice, or scene) to `/downloads` and index it in `flow-mcp.db`. The tool downloads untrimmed single-clip scenes directly. On verified front-end builds, the tool exports multi-clip or trimmed scenes through the scene export service of Flow (and returns `unsupported_front_end` on unverified builds). Waits up to `45` seconds (`pending: true` on timeout) and returns `{"file", "resource_uri", "record"}`. If the client supports MCP `2025-06-18` or newer, it also returns a `resource_link`. +Download a matching project media asset (image, video, custom voice, character look or assigned voice, scene, or scene clip) to `/downloads` and index it in `flow-mcp.db`. By default, video downloads keep the primary rendition of the asset. Set `quality` to `"360p"`, `"720p"`, `"1080p"`, `"4k"`, or `"best"` to select a verified video variant. Use `` to download a scene (directly for untrimmed single-clip scenes, or through the scene export service of Flow on verified front-end builds; unverified builds return `unsupported_front_end`). Use `:` to download one clip workflow from a scene. Waits up to `45` seconds (`pending: true` on timeout) and returns `{"file", "resource_uri", "record"}`. If the client supports MCP `2025-06-18` or newer, it also returns a `resource_link`. | Parameter | Type | Required | Description | | :--- | :--- | :--- | :--- | -| `match` | `string` | Yes | Exact asset ID, media or variant ID, exact name, or case-insensitive substring matching a project asset. | +| `match` | `string` | Yes | Exact asset ID, `:` scene clip ID, media or variant ID, exact name, or case-insensitive substring matching a project asset. | +| `quality` | `string` | No | Video quality selector: `"original"` (default), `"360p"`, `"720p"`, `"1080p"`, `"4k"`, or `"best"`. | ### `flow_downloads` diff --git a/docs/ja/tools-reference.md b/docs/ja/tools-reference.md index a3b7f3e..9cf001d 100644 --- a/docs/ja/tools-reference.md +++ b/docs/ja/tools-reference.md @@ -387,11 +387,12 @@ Flow シーンタイムラインの一覧表示、作成、クリップ追加、 ### `flow_download` -一致するプロジェクトのメディアアセット(画像、動画、`1080p` または `4K` アップスケール派生版、カスタムボイス、キャラクター外見または設定済みボイス、シーン)を `/downloads` へダウンロードし、`flow-mcp.db` に登録します。未トリミングの単一クリップシーンは直接ダウンロードし、複数クリップまたはトリミング済みシーンは検証済みフロントエンドビルド上で Flow のシーン書き出しサービスを経由して書き出します(未検証ビルドでは `unsupported_front_end` を返します)。最大 `45` 秒まで待機し(タイムアウト時は `pending: true`)、`{"file", "resource_uri", "record"}` を返します。クライアントが MCP `2025-06-18` 以降に対応している場合は、`resource_link` も返します。 +一致するプロジェクトのメディアアセット(画像、動画、カスタムボイス、キャラクター外見または設定済みボイス、シーン、またはシーンクリップ)を `/downloads` へダウンロードし、`flow-mcp.db` に登録します。動画ダウンロードは既定でアセット本来のプライマリ版を保持し、`quality` に `"360p"`、`"720p"`、`"1080p"`、`"4k"`、または `"best"` を指定すると検証済みの動画解像度派生版を選択できます。`` でシーン全体をダウンロードし(未トリミングの単一クリップシーンは直接ダウンロードし、複数クリップまたはトリミング済みシーンは検証済みフロントエンドビルド上で Flow のシーン書き出しサービスを経由して書き出し、未検証ビルドでは `unsupported_front_end` を返します)、`:` でシーン内の単一クリップワークフローをダウンロードします。最大 `45` 秒まで待機し(タイムアウト時は `pending: true`)、`{"file", "resource_uri", "record"}` を返します。クライアントが MCP `2025-06-18` 以降に対応している場合は、`resource_link` も返します。 | パラメータ | 型 | 必須 | 説明 | | :--- | :--- | :--- | :--- | -| `match` | `string` | はい | プロジェクトアセットに一致する正確なアセット ID、メディアまたは派生 ID、完全一致名、または大文字小文字を区別しない部分文字列。 | +| `match` | `string` | はい | プロジェクトアセットに一致する正確なアセット ID、`:` シーンクリップ ID、メディアまたは派生 ID、完全一致名、または大文字小文字を区別しない部分文字列。 | +| `quality` | `string` | いいえ | 動画品質の選択:`"original"`(既定)、`"360p"`、`"720p"`、`"1080p"`、`"4k"`、または `"best"`。 | ### `flow_downloads` diff --git a/docs/zh-CN/tools-reference.md b/docs/zh-CN/tools-reference.md index 2bc51b8..5467d75 100644 --- a/docs/zh-CN/tools-reference.md +++ b/docs/zh-CN/tools-reference.md @@ -387,11 +387,12 @@ flow-mcp [OPTIONS] ### `flow_download` -将匹配的项目媒体资产(图像、视频、`1080p` 或 `4K` 超分变体、自定义音色、角色外观或绑定音色、或场景)下载至 `/downloads` 并索引到 `flow-mcp.db`。未裁剪的单片段场景直接下载,多片段或已裁剪场景在已验证的前端构建上通过 Flow 场景导出服务导出(未验证构建返回 `unsupported_front_end`)。最多等待 `45` 秒(超时返回 `pending: true`),并返回 `{"file", "resource_uri", "record"}`。如果客户端支持 MCP `2025-06-18` 或更高版本,还会返回 `resource_link`。 +将匹配的项目媒体资产(图像、视频、自定义音色、角色外观或绑定音色、场景或场景片段)下载至 `/downloads` 并索引到 `flow-mcp.db`。视频下载默认保留资产本身的主版本;可将 `quality` 设为 `"360p"`、`"720p"`、`"1080p"`、`"4k"` 或 `"best"` 以选择已验证的视频清晰度变体。传入 `` 下载整个场景(未裁剪的单片段场景直接下载,多片段或已裁剪场景在已验证的前端构建上通过 Flow 场景导出服务导出,未验证构建返回 `unsupported_front_end`);传入 `:` 下载场景内的单个片段工作流。最多等待 `45` 秒(超时返回 `pending: true`),并返回 `{"file", "resource_uri", "record"}`。如果客户端支持 MCP `2025-06-18` 或更高版本,还会返回 `resource_link`。 | 参数 | 类型 | 必填 | 说明 | | :--- | :--- | :--- | :--- | -| `match` | `string` | 是 | 匹配项目资产的精确资产 ID、媒体或变体 ID、精确名称或忽略大小写子串。 | +| `match` | `string` | 是 | 匹配项目资产的精确资产 ID、`:` 场景片段 ID、媒体或变体 ID、精确名称或忽略大小写子串。 | +| `quality` | `string` | 否 | 视频清晰度选择:`"original"`(默认)、`"360p"`、`"720p"`、`"1080p"`、`"4k"` 或 `"best"`。 | ### `flow_downloads` diff --git a/src/asset_matching.rs b/src/asset_matching.rs new file mode 100644 index 0000000..ec42003 --- /dev/null +++ b/src/asset_matching.rs @@ -0,0 +1,268 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Asset ID, variant media ID, and `:` scene clip matching helpers. + +use anyhow::{Context, Result}; + +use crate::assets::FlowAsset; + +/// Strips a leading `media/` or `workflows/` prefix from a resource identifier. +pub(crate) fn strip_resource_prefix(raw: &str) -> &str { + let trimmed = raw.trim(); + if trimmed.len() > 6 && trimmed[..6].eq_ignore_ascii_case("media/") { + &trimmed[6..] + } else if trimmed.len() > 10 && trimmed[..10].eq_ignore_ascii_case("workflows/") { + &trimmed[10..] + } else { + trimmed + } +} + +/// Strips a leading `media/` prefix from a media resource identifier. +pub(crate) fn strip_media_prefix(raw: &str) -> &str { + let trimmed = raw.trim(); + if trimmed.len() > 6 && trimmed[..6].eq_ignore_ascii_case("media/") { + &trimmed[6..] + } else { + trimmed + } +} + +/// Finds the first asset matching `pred`, preferring `video`, `image`, and `audio` tiles over referencing `character` and `scene` tiles. +fn find_preferring_direct_media(assets: &[FlowAsset], mut pred: F) -> Option<&FlowAsset> +where + F: FnMut(&FlowAsset) -> bool, +{ + let mut fallback: Option<&FlowAsset> = None; + for asset in assets { + if pred(asset) { + if !matches!(asset.kind.as_str(), "character" | "scene") { + return Some(asset); + } + if fallback.is_none() { + fallback = Some(asset); + } + } + } + fallback +} + +/// Selects the best-matching asset by exact ID, media ID, exact name, name substring, +/// ID or media ID substring, or optional prompt substring. +pub(crate) fn match_asset<'a>( + assets: &'a [FlowAsset], + match_str: &str, + include_prompt: bool, +) -> Option<&'a FlowAsset> { + let raw = match_str.trim(); + if raw.is_empty() { + return None; + } + let clean_raw = strip_media_prefix(raw); + let clean_res = strip_resource_prefix(raw); + let lower = raw.to_lowercase(); + let clean_lower = clean_raw.to_lowercase(); + let clean_res_lower = clean_res.to_lowercase(); + + assets + .iter() + .find(|a| a.id == raw) + .or_else(|| { + find_preferring_direct_media(assets, |a| { + a.workflow_id + .as_deref() + .is_some_and(|wf| wf == raw || strip_resource_prefix(wf) == clean_res) + }) + }) + .or_else(|| { + find_preferring_direct_media(assets, |a| { + a.primary_media_id + .as_deref() + .is_some_and(|id| id == raw || strip_media_prefix(id) == clean_raw) + }) + }) + .or_else(|| { + find_preferring_direct_media(assets, |a| { + a.media_ids + .iter() + .any(|id| id == raw || strip_media_prefix(id) == clean_raw) + }) + }) + .or_else(|| assets.iter().find(|a| a.name.eq_ignore_ascii_case(raw))) + .or_else(|| { + assets + .iter() + .find(|a| a.name.to_lowercase().contains(&lower)) + }) + .or_else(|| { + assets + .iter() + .find(|a| !a.id.contains(':') && a.id.to_lowercase().contains(&lower)) + }) + .or_else(|| assets.iter().find(|a| a.id.to_lowercase().contains(&lower))) + .or_else(|| { + find_preferring_direct_media(assets, |a| { + a.workflow_id + .as_deref() + .is_some_and(|wf| wf.to_lowercase().contains(&clean_res_lower)) + || a.primary_media_id + .as_deref() + .is_some_and(|id| id.to_lowercase().contains(&clean_lower)) + || a.media_ids + .iter() + .any(|id| id.to_lowercase().contains(&clean_lower)) + }) + }) + .or_else(|| { + if include_prompt { + assets.iter().find(|a| { + a.prompt + .as_deref() + .unwrap_or("") + .to_lowercase() + .contains(&lower) + }) + } else { + None + } + }) +} + +/// Pins `target.primary_media_id` when `match_str` selects a specific variant in `target.media_ids`. +pub(crate) fn pin_matched_variant_id(target: &mut FlowAsset, match_str: &str) { + let raw = match_str.trim(); + if raw.is_empty() || target.id == raw || target.name.eq_ignore_ascii_case(raw) { + return; + } + let clean_raw = strip_media_prefix(raw); + let exact = target + .media_ids + .iter() + .find(|id| id.as_str() == raw || strip_media_prefix(id) == clean_raw) + .cloned(); + let lower = raw.to_lowercase(); + let clean_lower = clean_raw.to_lowercase(); + let matched = exact.or_else(|| { + if target.name.to_lowercase().contains(&lower) || target.id.to_lowercase().contains(&lower) + { + return None; + } + target + .media_ids + .iter() + .find(|id| id.to_lowercase().contains(&clean_lower)) + .cloned() + }); + if let Some(variant_id) = matched { + let normalized = strip_media_prefix(&variant_id).to_string(); + let changed = + target.primary_media_id.as_deref().map(strip_media_prefix) != Some(normalized.as_str()); + target.primary_media_id = Some(normalized); + if changed { + target.url = None; + } + } +} + +/// Resolves an explicit `:` clip selector against a scene tile in `assets`. +pub(crate) fn resolve_scene_clip_selector( + assets: &[FlowAsset], + match_str: &str, + context_label: &str, +) -> Result> { + let raw = match_str.trim(); + if assets.iter().any(|a| a.id == raw) { + return Ok(None); + } + let Some((raw_scene, raw_wf)) = raw.split_once(':') else { + return Ok(None); + }; + let scene_key = strip_resource_prefix(raw_scene); + let Some(scene) = assets + .iter() + .find(|a| a.kind == "scene" && (a.id == raw_scene.trim() || a.id == scene_key)) + else { + return Ok(None); + }; + let wf_id = strip_resource_prefix(raw_wf); + if wf_id.is_empty() || wf_id.contains(':') { + anyhow::bail!( + "Invalid scene clip selector '{}' for {}: expected ':'", + raw, + context_label + ); + } + let clip = scene + .scene_clips + .iter() + .find(|c| c.workflow_id == wf_id || strip_resource_prefix(&c.workflow_id) == wf_id) + .with_context(|| { + format!( + "Scene '{}' has no clip workflow '{}' for {}", + scene.id, wf_id, context_label + ) + })?; + let standalone = assets.iter().find(|a| { + a.kind == "video" + && (a.id == clip.workflow_id + || a.id == wf_id + || a.workflow_id + .as_deref() + .is_some_and(|wf| wf == wf_id || strip_resource_prefix(wf) == wf_id)) + }); + let primary_media_id = clip + .primary_media_id + .clone() + .or_else(|| standalone.and_then(|v| v.primary_media_id.clone())); + let url = clip + .url + .clone() + .or_else(|| standalone.and_then(|v| v.url.clone())); + let mut media_ids = standalone.map(|v| v.media_ids.clone()).unwrap_or_default(); + if let Some(ref mid) = primary_media_id + && !media_ids.iter().any(|existing| existing == mid) + { + media_ids.insert(0, mid.clone()); + } + let resolved_id = if context_label == "flow_download" || standalone.is_none() { + format!("{}:{}", scene.id, clip.workflow_id) + } else if let Some(v) = standalone { + v.id.clone() + } else { + format!("{}:{}", scene.id, clip.workflow_id) + }; + let name = standalone + .map(|v| v.name.clone()) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| format!("{} ({})", scene.name, clip.workflow_id)); + Ok(Some(FlowAsset { + id: resolved_id, + name, + kind: "video".to_string(), + prompt: standalone.and_then(|v| v.prompt.clone()), + url, + collection_id: scene.collection_id.clone(), + collection_name: scene.collection_name.clone(), + width: standalone.and_then(|v| v.width), + height: standalone.and_then(|v| v.height), + duration: standalone.and_then(|v| v.duration), + primary_media_id, + personality_notes: None, + voice: None, + trim_start_seconds: standalone.and_then(|v| v.trim_start_seconds), + trim_end_seconds: standalone.and_then(|v| v.trim_end_seconds), + media_status: standalone.and_then(|v| v.media_status.clone()), + media_error: standalone.and_then(|v| v.media_error.clone()), + media_ids, + workflow_id: Some(clip.workflow_id.clone()), + requires_scene_export: false, + pcm_audio: false, + media_kind: Some("video".to_string()), + variants: standalone.map(|v| v.variants.clone()).unwrap_or_default(), + scene_clips: Vec::new(), + created_at: standalone + .and_then(|v| v.created_at.clone()) + .or_else(|| scene.created_at.clone()), + })) +} diff --git a/src/assets.rs b/src/assets.rs index 4ff8c01..56d3bf0 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -13,9 +13,13 @@ use serde_json::{Value, json}; use std::collections::HashMap; use tokio::time::{Duration, Instant}; +pub(crate) use crate::asset_matching::match_asset; +use crate::asset_matching::{ + pin_matched_variant_id, resolve_scene_clip_selector, strip_media_prefix, strip_resource_prefix, +}; use crate::collections::{FlowCollection, find_collection}; use crate::db::FlowDb; -use crate::download::eval_resolve_media_url; +use crate::download_urls::eval_resolve_media_url; use crate::engine::ChromeEngine; use crate::project::{ensure_flow_store, read_snapshot}; use crate::project_store::ProjectStoreSession; @@ -27,6 +31,41 @@ const MEDIA_URL_LOOKUPS: usize = 4; /// Time to resolve missing URLs in one asset list response. const ASSET_LIST_URL_BUDGET: Duration = Duration::from_secs(10); +/// Ready video variant entry recorded on a project video or single-clip scene tile. +#[derive(Debug, Clone, Deserialize)] +pub(crate) struct VideoVariantAsset { + /// Media ID of the variant without a `media/` prefix. + pub(crate) media_id: String, + /// Verified quality label (`"360p"`, `"720p"`, `"1080p"`, or `"4k"`). + #[serde(default)] + pub(crate) quality: Option, + /// Direct media URL on the variant when available. + #[serde(default)] + pub(crate) url: Option, + /// Variant width in pixels when available. + #[serde(default)] + pub(crate) width: Option, + /// Variant height in pixels when available. + #[serde(default)] + pub(crate) height: Option, + /// Variant duration in seconds when available. + #[serde(default)] + pub(crate) duration: Option, +} + +/// Clip workflow entry inside a project scene tile. +#[derive(Debug, Clone, Deserialize)] +pub(crate) struct SceneClipAsset { + /// Clip workflow ID inside the scene. + pub(crate) workflow_id: String, + /// Primary media ID of the clip when available. + #[serde(default)] + pub(crate) primary_media_id: Option, + /// Direct media URL of the clip when available. + #[serde(default)] + pub(crate) url: Option, +} + /// Media asset or scene item inside a Google Flow project. #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct FlowAsset { @@ -93,6 +132,12 @@ pub(crate) struct FlowAsset { /// Underlying media family override when a tile downloads audio. #[serde(default, skip_serializing)] pub(crate) media_kind: Option, + /// Ready video variants (original and upscaled resolutions) on the tile. + #[serde(default, skip_serializing)] + pub(crate) variants: Vec, + /// Ordered clip workflow entries on a scene tile. + #[serde(default, skip_serializing)] + pub(crate) scene_clips: Vec, /// Creation timestamp (`createTime`) string. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) created_at: Option, @@ -131,6 +176,8 @@ impl FlowAsset { requires_scene_export: false, pcm_audio: false, media_kind: None, + variants: Vec::new(), + scene_clips: Vec::new(), created_at: None, } } @@ -198,9 +245,12 @@ pub(crate) struct RenameParams { /// Parameters for `flow_download`. #[derive(Debug, Clone, Deserialize, JsonSchema)] pub(crate) struct DownloadParams { - /// Exact asset ID, exact name, or case-insensitive asset substring to download. + /// Exact asset ID, `:` scene clip ID, media or variant ID, exact name, or case-insensitive asset substring to download. #[serde(rename = "match")] pub(crate) r#match: String, + /// Optional video quality selector: `"original"` (default), `"360p"`, `"720p"`, `"1080p"`, `"4k"`, or `"best"`. + #[serde(default, alias = "resolution")] + pub(crate) quality: Option, } /// Parameters for `flow_trash`. @@ -211,28 +261,6 @@ pub(crate) struct TrashParams { pub(crate) r#match: String, } -/// Strips a leading `media/` or `workflows/` prefix from a resource identifier. -fn strip_resource_prefix(raw: &str) -> &str { - let trimmed = raw.trim(); - if trimmed.len() > 6 && trimmed[..6].eq_ignore_ascii_case("media/") { - &trimmed[6..] - } else if trimmed.len() > 10 && trimmed[..10].eq_ignore_ascii_case("workflows/") { - &trimmed[10..] - } else { - trimmed - } -} - -/// Strips a leading `media/` prefix from a media resource identifier. -fn strip_media_prefix(raw: &str) -> &str { - let trimmed = raw.trim(); - if trimmed.len() > 6 && trimmed[..6].eq_ignore_ascii_case("media/") { - &trimmed[6..] - } else { - trimmed - } -} - /// Resolves missing direct media URLs on finished media, character, and 1-clip scene tiles through `as29s` RPCs. async fn populate_missing_media_urls( engine: &ChromeEngine, @@ -355,137 +383,6 @@ async fn read_project_assets(engine: &ChromeEngine) -> Result(assets: &[FlowAsset], mut pred: F) -> Option<&FlowAsset> -where - F: FnMut(&FlowAsset) -> bool, -{ - let mut fallback: Option<&FlowAsset> = None; - for asset in assets { - if pred(asset) { - if !matches!(asset.kind.as_str(), "character" | "scene") { - return Some(asset); - } - if fallback.is_none() { - fallback = Some(asset); - } - } - } - fallback -} - -/// Selects the best-matching asset by exact ID, media ID, exact name, name substring, -/// ID or media ID substring, or optional prompt substring. -pub(crate) fn match_asset<'a>( - assets: &'a [FlowAsset], - match_str: &str, - include_prompt: bool, -) -> Option<&'a FlowAsset> { - let raw = match_str.trim(); - if raw.is_empty() { - return None; - } - let clean_raw = strip_media_prefix(raw); - let clean_res = strip_resource_prefix(raw); - let lower = raw.to_lowercase(); - let clean_lower = clean_raw.to_lowercase(); - let clean_res_lower = clean_res.to_lowercase(); - - assets - .iter() - .find(|a| a.id == raw) - .or_else(|| { - find_preferring_direct_media(assets, |a| { - a.workflow_id - .as_deref() - .is_some_and(|wf| wf == raw || strip_resource_prefix(wf) == clean_res) - }) - }) - .or_else(|| { - find_preferring_direct_media(assets, |a| { - a.primary_media_id - .as_deref() - .is_some_and(|id| id == raw || strip_media_prefix(id) == clean_raw) - }) - }) - .or_else(|| { - find_preferring_direct_media(assets, |a| { - a.media_ids - .iter() - .any(|id| id == raw || strip_media_prefix(id) == clean_raw) - }) - }) - .or_else(|| assets.iter().find(|a| a.name.eq_ignore_ascii_case(raw))) - .or_else(|| { - assets - .iter() - .find(|a| a.name.to_lowercase().contains(&lower)) - }) - .or_else(|| assets.iter().find(|a| a.id.to_lowercase().contains(&lower))) - .or_else(|| { - find_preferring_direct_media(assets, |a| { - a.workflow_id - .as_deref() - .is_some_and(|wf| wf.to_lowercase().contains(&clean_res_lower)) - || a.primary_media_id - .as_deref() - .is_some_and(|id| id.to_lowercase().contains(&clean_lower)) - || a.media_ids - .iter() - .any(|id| id.to_lowercase().contains(&clean_lower)) - }) - }) - .or_else(|| { - if include_prompt { - assets.iter().find(|a| { - a.prompt - .as_deref() - .unwrap_or("") - .to_lowercase() - .contains(&lower) - }) - } else { - None - } - }) -} - -/// Pins `target.primary_media_id` when `match_str` selects a specific variant in `target.media_ids`. -fn pin_matched_variant_id(target: &mut FlowAsset, match_str: &str) { - let raw = match_str.trim(); - if raw.is_empty() || target.id == raw || target.name.eq_ignore_ascii_case(raw) { - return; - } - let clean_raw = strip_media_prefix(raw); - let exact = target - .media_ids - .iter() - .find(|id| id.as_str() == raw || strip_media_prefix(id) == clean_raw) - .cloned(); - let lower = raw.to_lowercase(); - let clean_lower = clean_raw.to_lowercase(); - let matched = exact.or_else(|| { - if target.name.to_lowercase().contains(&lower) || target.id.to_lowercase().contains(&lower) - { - return None; - } - target - .media_ids - .iter() - .find(|id| id.to_lowercase().contains(&clean_lower)) - .cloned() - }); - if let Some(variant_id) = matched { - let normalized = strip_media_prefix(&variant_id).to_string(); - let changed = - target.primary_media_id.as_deref().map(strip_media_prefix) != Some(normalized.as_str()); - target.primary_media_id = Some(normalized); - if changed { - target.url = None; - } - } -} - /// Resolves the single best-matching asset and active project metadata across all project assets. pub(crate) async fn resolve_asset( engine: &ChromeEngine, @@ -494,6 +391,9 @@ pub(crate) async fn resolve_asset( context_label: &str, ) -> Result<(FlowAsset, Option, Option)> { let snap = read_project_assets(engine).await?; + if let Some(clip_asset) = resolve_scene_clip_selector(&snap.assets, match_str, context_label)? { + return Ok((clip_asset, snap.project_id, snap.project_title)); + } let mut target = match_asset(&snap.assets, match_str, include_prompt) .cloned() .with_context(|| { diff --git a/src/characters.rs b/src/characters.rs index 0fb08d5..a5e7801 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -1,7 +1,7 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -//! Google Flow character entity workflows, voice discovery, and SQLite persistence. +//! Google Flow character entity workflows and SQLite persistence. use anyhow::{Context, Result}; use schemars::JsonSchema; @@ -10,7 +10,7 @@ use serde_json::{Value, json}; use std::collections::HashMap; use tokio::time::{Duration, Instant}; -use crate::assets::{FlowAsset, list_assets_with_project, match_asset, trash_asset}; +use crate::assets::{FlowAsset, list_assets_with_project, match_asset}; use crate::character_bio::{edit_character_bio, set_character_bio}; use crate::db::FlowDb; use crate::download::download_resolved_asset; @@ -23,9 +23,7 @@ use crate::project::{ use crate::project_route::character_id_from_url; use crate::project_store::ProjectStoreSession; use crate::queue::{ProgressCallback, SceneParams}; -use crate::voices::{ - VoiceRequest, apply_voice_with_fallback, delete_portrait, list_all_voices, scene_voice, -}; +use crate::voices::{VoiceRequest, apply_voice_with_fallback, delete_portrait, scene_voice}; /// Parameters for `flow_character`. #[derive(Debug, Clone, Deserialize, JsonSchema)] @@ -79,13 +77,6 @@ pub(crate) struct CharacterEditParams { pub(crate) prompt: Option, } -/// Parameters for `flow_voices`. -#[derive(Debug, Clone, Deserialize, JsonSchema)] -pub(crate) struct VoicesParams { - /// Optional character ID or name whose editor opens the voice picker. - pub(crate) character: Option, -} - /// Saves `scene.character_look` under `scene.character_role` or reads the saved /// look from SQLite, then appends `", character {role}: {look}"` to `scene.prompt`. pub(crate) async fn apply_character_look(db: &FlowDb, scene: &mut SceneParams) -> Result<()> { @@ -169,106 +160,6 @@ pub(crate) async fn exit_character_editor(engine: &ChromeEngine, project_id: Opt let _ = ensure_flow_store(engine).await; } -/// Lists available Flow character voices from the character editor voice picker. -pub(crate) async fn list_voices( - engine: &ChromeEngine, - db: &FlowDb, - character: Option<&str>, -) -> Result { - ensure_flow_store(engine).await?; - let initial_url = engine.current_url().await.unwrap_or_default(); - let mut project_id = project_id_from_url(&initial_url); - let mut temp_char_id: Option = None; - - if !initial_url.contains("/character/") { - let snap = list_assets_with_project(engine).await?; - if project_id.is_none() { - project_id = snap.project_id.clone(); - } - let pid = project_id - .as_deref() - .ok_or_else(|| anyhow::anyhow!("Missing project ID for character route"))?; - let chars: Vec = snap - .assets - .into_iter() - .filter(|a| a.kind == "character") - .collect(); - let target_cid = if let Some(q) = character.map(str::trim).filter(|s| !s.is_empty()) { - match_asset(&chars, q, false).map(|c| c.id.clone()) - } else { - chars.first().map(|c| c.id.clone()) - }; - - let cid = if let Some(existing_cid) = target_cid { - existing_cid - } else { - let created = engine - .call_flow_async( - "characterOp", - json!([{ - "action": "create", - "name": "__tmp_voice_probe__", - }]), - ) - .await?; - if created.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to create temporary character for voice lookup: {}", - created - .get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); - } - let tmp_cid = created - .get("id") - .and_then(|v| v.as_str()) - .map(str::to_string) - .ok_or_else(|| { - anyhow::anyhow!("Temporary character creation returned no character ID") - })?; - temp_char_id = Some(tmp_cid.clone()); - tmp_cid - }; - - open_character_editor(engine, &initial_url, pid, &cid).await?; - } - - let full_list = list_all_voices(engine).await; - let voices_res = match full_list { - Some(voices) => Ok(json!({ "ok": true, "voices": voices })), - None => { - engine - .call_flow_async("characterVoiceOp", json!([{ "action": "list_voices" }])) - .await - } - }; - - exit_character_editor(engine, project_id.as_deref()).await; - if let Some(tmp_id) = temp_char_id { - let _ = trash_asset(engine, db, &tmp_id).await; - } - - let res = voices_res?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to list Flow character voices: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); - } - let count = res - .get("voices") - .and_then(|v| v.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - Ok(json!({ - "count": count, - "voices": res.get("voices").cloned().unwrap_or_else(|| json!([])), - })) -} - /// Clicks `look_submit_point` when present and returns `(slot, prev_media_id, prev_src)`. async fn click_look_submit_if_present( engine: &ChromeEngine, diff --git a/src/download.rs b/src/download.rs index 5702ea8..365ff11 100644 --- a/src/download.rs +++ b/src/download.rs @@ -8,7 +8,6 @@ use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; use serde_json::{Value, json}; use std::path::Path; use std::sync::OnceLock; -use std::time::{SystemTime, UNIX_EPOCH}; use tokio::io::{AsyncWriteExt, BufWriter}; use tokio::time::Duration; use url::Url; @@ -16,6 +15,10 @@ use url::Url; use crate::assets::{FlowAsset, resolve_asset}; use crate::config::downloads_dir; use crate::db::{DownloadRecord, FlowDb, NewDownloadRecord}; +use crate::download_urls::{ + is_expired_signed_url, is_signed_direct_url, push_fife_candidates, push_unique_url, + query_resolved_media_urls, +}; use crate::engine::{ChromeEngine, DEFAULT_CHROME_UA}; use crate::media_files::{ MEDIA_KIND_MISMATCH_TAG, disambiguate_dest, natural_asset_filename, resolve_stored_path, @@ -49,14 +52,18 @@ enum DownloadSource { }, } -/// Ordered URL candidates and media kind from `resolveVideoUrl`. -struct ResolvedMediaUrls { - /// Candidate URLs with signed direct URLs before unsigned URLs. - urls: Vec, - /// Media family from the `as29s` wire message when present. - media_kind: Option, - /// True when `as29s` case `11` returned raw 24 kHz PCM audio. - pcm_audio: bool, +/// Browser time limit (`90_000` ms) passed to `sceneExport` so polling ends before the 120 s CDP timeout. +const SCENE_EXPORT_TIMEOUT_MS: u64 = 90_000; + +/// Requested video resolution mode for `flow_download`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum RequestedQuality { + /// Keep the primary rendition recorded on the tile. + Original, + /// Require one specific verified resolution label. + Exact(&'static str), + /// Select the highest verified resolution available on the tile. + Best, } /// Returns the shared HTTP client for streaming media downloads. @@ -170,290 +177,6 @@ async fn fetch_via_browser_to_temp( Ok((validated_ct, disp, size_bytes)) } -/// Returns `true` when `raw_url` carries signed GCS/Flow CDN hosts or V2/V4 query signatures. -fn is_signed_direct_url(raw_url: &str) -> bool { - let Ok(parsed) = Url::parse(raw_url) else { - return false; - }; - let Some(host) = parsed.host_str().map(str::to_ascii_lowercase) else { - return false; - }; - host == "storage.googleapis.com" - || host.ends_with(".storage.googleapis.com") - || host == "flow-content.google" - || host.ends_with(".flow-content.google") - || host == "labs-flow.dev" - || host.ends_with(".labs-flow.dev") - || host == "video-downloads.googleusercontent.com" - || host.ends_with(".video-downloads.googleusercontent.com") - || parsed.query_pairs().any(|(k, _)| { - matches!( - k.to_ascii_lowercase().as_str(), - "signature" - | "googleaccessid" - | "x-goog-signature" - | "x-goog-algorithm" - | "x-goog-credential" - | "x-goog-date" - | "x-goog-expires" - | "x-goog-signedheaders" - ) - }) -} - -/// Converts a proleptic Gregorian UTC date into days since `1970-01-01`. -fn civil_days_from_ymd(year: i64, month: u32, day: u32) -> i64 { - let y = year - i64::from(month <= 2); - let era = if y >= 0 { y } else { y - 399 } / 400; - let yoe = (y - era * 400) as u64; - let m = u64::from(month); - let d = u64::from(day); - let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; - let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; - era * 146_097 + (doe as i64) - 719_468 -} - -/// Parses a compact `YYYYMMDDTHHMMSSZ` timestamp into Unix epoch seconds. -fn parse_goog_date_secs(raw: &str) -> Option { - let trimmed = raw.trim(); - if trimmed.len() != 16 { - return None; - } - let bytes = trimmed.as_bytes(); - if !matches!(bytes[8], b'T' | b't') || !matches!(bytes[15], b'Z' | b'z') { - return None; - } - let year: i64 = trimmed.get(0..4)?.parse().ok()?; - let month: u32 = trimmed.get(4..6)?.parse().ok()?; - let day: u32 = trimmed.get(6..8)?.parse().ok()?; - let hour: u64 = trimmed.get(9..11)?.parse().ok()?; - let minute: u64 = trimmed.get(11..13)?.parse().ok()?; - let second: u64 = trimmed.get(13..15)?.parse().ok()?; - if !(1..=12).contains(&month) - || !(1..=31).contains(&day) - || hour > 23 - || minute > 59 - || second > 60 - { - return None; - } - let days = civil_days_from_ymd(year, month, day); - let day_secs = u64::try_from(days).ok()?.checked_mul(86_400)?; - day_secs - .checked_add(hour * 3_600) - .and_then(|v| v.checked_add(minute * 60)) - .and_then(|v| v.checked_add(second)) -} - -/// Returns `true` when `raw_url` carries a V4 or V2 GCS signature whose validity window has elapsed. -fn is_expired_signed_url(raw_url: &str) -> bool { - let Ok(parsed) = Url::parse(raw_url.trim()) else { - return false; - }; - let Ok(now_dur) = SystemTime::now().duration_since(UNIX_EPOCH) else { - return false; - }; - let now_secs = now_dur.as_secs(); - let mut goog_date: Option = None; - let mut goog_expires: Option = None; - let mut v2_expires: Option = None; - let mut has_v2_sig = false; - for (k, v) in parsed.query_pairs() { - match k.to_ascii_lowercase().as_str() { - "x-goog-date" => goog_date = Some(v.into_owned()), - "x-goog-expires" => goog_expires = Some(v.into_owned()), - "expires" => v2_expires = Some(v.into_owned()), - "signature" | "googleaccessid" => has_v2_sig = true, - _ => {} - } - } - if let (Some(date_str), Some(exp_str)) = (goog_date, goog_expires) { - let Some(issued_secs) = parse_goog_date_secs(&date_str) else { - return true; - }; - let Ok(expires_secs) = exp_str.trim().parse::() else { - return true; - }; - return now_secs >= issued_secs.saturating_add(expires_secs); - } - if has_v2_sig && let Some(v2_str) = v2_expires { - let Ok(exp_secs) = v2_str.trim().parse::() else { - return true; - }; - return now_secs >= exp_secs; - } - false -} - -/// Appends `raw` to `out` when it uses an allowed scheme and is not already present. -fn push_unique_url(out: &mut Vec, raw: &str) { - let trimmed = raw.trim(); - let lower = trimmed.to_ascii_lowercase(); - if !(lower.starts_with("http://") - || lower.starts_with("https://") - || lower.starts_with("blob:") - || lower.starts_with("data:")) - { - return; - } - if !out.iter().any(|existing| existing == trimmed) { - out.push(trimmed.to_string()); - } -} - -/// Removes trailing `=...` FIFE resize/format suffixes from the final path segment. -fn strip_fife_path_options(path: &str) -> String { - match path.rsplit_once('/') { - Some((dir, leaf)) => { - let clean_leaf = match leaf.rfind('=') { - Some(idx) => &leaf[..idx], - None => leaf, - }; - format!("{}/{}", dir, clean_leaf) - } - None => match path.rfind('=') { - Some(idx) => path[..idx].to_string(), - None => path.to_string(), - }, - } -} - -/// Expands unsigned image or video FIFE URLs into prioritized original/download variants. -fn push_fife_candidates(out: &mut Vec, raw_url: &str, expected_kind: &str) { - if expected_kind == "audio" || is_signed_direct_url(raw_url) { - return; - } - let Ok(parsed) = Url::parse(raw_url) else { - return; - }; - let Some(host) = parsed.host_str().map(str::to_ascii_lowercase) else { - return; - }; - if !(host == "flow.google.com" - || host.ends_with(".googleusercontent.com") - || host.ends_with(".fife.usercontent.google.com")) - { - return; - } - let is_video = expected_kind == "video"; - let stripped_path = strip_fife_path_options(parsed.path()); - let use_proxy_first = host == "flow.google.com" || stripped_path.starts_with("/asb/"); - - if !use_proxy_first { - let mut orig_parsed = parsed.clone(); - let suffixes: &[&str] = if is_video { - &["=mm,22,15", "=dv", "=d"] - } else { - &["=d", "=s0"] - }; - for suffix in suffixes { - orig_parsed.set_path(&format!("{}{}", stripped_path, suffix)); - push_unique_url(out, orig_parsed.as_str()); - } - } - - let mut flow_parsed = parsed; - if flow_parsed.set_host(Some("flow.google.com")).is_ok() { - let suffixes: &[&str] = if is_video { - &["=mm,22,15", "=mm,18,15", "=dv", "=d"] - } else { - &["=d", "=s0"] - }; - for suffix in suffixes { - flow_parsed.set_path(&format!("{}{}", stripped_path, suffix)); - push_unique_url(out, flow_parsed.as_str()); - } - } -} - -/// Gets the media URLs from Chrome within the optional browser request budget. -pub(crate) async fn eval_resolve_media_url( - engine: &ChromeEngine, - media_id: &str, - timeout_ms: Option, -) -> Option { - eval_resolve_media_url_opts(engine, media_id, timeout_ms, false).await -} - -/// Calls `resolveVideoUrl` in Chrome with optional timeout and cache bypass flags. -async fn eval_resolve_media_url_opts( - engine: &ChromeEngine, - media_id: &str, - timeout_ms: Option, - bypass_cache: bool, -) -> Option { - let val = engine - .call_flow_async( - "resolveVideoUrl", - json!([media_id, timeout_ms, bypass_cache]), - ) - .await - .ok()?; - (val.get("ok").and_then(|v| v.as_bool()) == Some(true)).then_some(val) -} - -/// Expands `eval_resolve_media_url` output and puts signed direct URLs before unsigned URLs. -async fn query_resolved_media_urls( - engine: &ChromeEngine, - media_id: &str, - fallback_kind: &str, - bypass_cache: bool, -) -> ResolvedMediaUrls { - let Some(val) = eval_resolve_media_url_opts(engine, media_id, None, bypass_cache).await else { - return ResolvedMediaUrls { - urls: Vec::new(), - media_kind: None, - pcm_audio: false, - }; - }; - let media_kind = val - .get("media_kind") - .and_then(|v| v.as_str()) - .map(str::to_string); - let pcm_audio = val - .get("pcm_audio") - .and_then(Value::as_bool) - .unwrap_or(false); - let effective_kind = if media_kind.as_deref() == Some("audio") { - "audio" - } else { - fallback_kind - }; - - let mut signed = Vec::new(); - let mut unsigned = Vec::new(); - let mut record_cand = |raw: &str| { - if is_signed_direct_url(raw) { - push_unique_url(&mut signed, raw); - } else { - push_unique_url(&mut unsigned, raw); - push_fife_candidates(&mut unsigned, raw, effective_kind); - } - }; - - if let Some(dl_url) = val.get("download_url").and_then(|v| v.as_str()) { - record_cand(dl_url); - } - if let Some(url) = val.get("url").and_then(|v| v.as_str()) { - record_cand(url); - } - if let Some(cands) = val.get("candidates").and_then(|v| v.as_array()) { - for cand in cands.iter().filter_map(|v| v.as_str()) { - record_cand(cand); - } - } - - let mut urls = signed; - for cand in unsigned { - push_unique_url(&mut urls, &cand); - } - ResolvedMediaUrls { - urls, - media_kind, - pcm_audio, - } -} - /// Selects the [`DownloadSource`] for `target` from its pre-populated URL and media ID. fn select_download_source(target: &FlowAsset, label: &str) -> Result { if target.kind == "scene" && target.requires_scene_export { @@ -479,7 +202,7 @@ fn select_download_source(target: &FlowAsset, label: &str) -> Result Result<((Option, Option, u64), String)> { let val = engine - .call_flow_async("sceneExport", json!([scene_id])) + .call_flow_async( + "sceneExport", + json!([scene_id, Value::Null, SCENE_EXPORT_TIMEOUT_MS]), + ) .await?; if val.get("ok").and_then(Value::as_bool) != Some(true) { let err = val @@ -841,13 +567,156 @@ pub(crate) async fn download_resolved_asset( .await } +/// Returns a numeric ordering rank for verified video quality labels. +fn quality_rank(label: Option<&str>) -> u8 { + match label { + Some("4k") => 4, + Some("1080p") => 3, + Some("720p") => 2, + Some("360p") => 1, + _ => 0, + } +} + +/// Parses an optional `quality` parameter string into a [`RequestedQuality`]. +fn parse_download_quality(raw: Option<&str>) -> Result { + let Some(trimmed) = raw.map(str::trim).filter(|s| !s.is_empty()) else { + return Ok(RequestedQuality::Original); + }; + match trimmed.to_ascii_lowercase().as_str() { + "original" | "default" | "primary" => Ok(RequestedQuality::Original), + "360p" => Ok(RequestedQuality::Exact("360p")), + "720p" => Ok(RequestedQuality::Exact("720p")), + "1080p" | "fhd" => Ok(RequestedQuality::Exact("1080p")), + "4k" | "2160p" | "uhd" => Ok(RequestedQuality::Exact("4k")), + "best" | "highest" | "max" => Ok(RequestedQuality::Best), + _ => anyhow::bail!( + "Unsupported download quality '{}': expected 'original', '360p', '720p', '1080p', '4k', or 'best'", + trimmed + ), + } +} + +/// Applies the requested video quality selector to `target` before download URL lookup. +fn apply_download_quality(target: &mut FlowAsset, quality: Option<&str>) -> Result<()> { + let mode = parse_download_quality(quality)?; + if mode == RequestedQuality::Original { + return Ok(()); + } + let label = if target.name.is_empty() { + target.id.clone() + } else { + target.name.clone() + }; + if !matches!(target.kind.as_str(), "video" | "scene") { + anyhow::bail!( + "Quality '{}' applies only to video assets (matched '{}' has kind '{}')", + quality.unwrap_or_default().trim(), + label, + target.kind + ); + } + match mode { + RequestedQuality::Original => Ok(()), + RequestedQuality::Exact(wanted) => { + if target.kind == "scene" && target.requires_scene_export { + anyhow::bail!( + "Scene '{}' uses multi-clip or trimmed scene export and does not expose '{}' variants; omit 'quality' or use ':' to download one clip", + label, + wanted + ); + } + let Some(chosen) = target + .variants + .iter() + .find(|v| v.quality.as_deref() == Some(wanted)) + .cloned() + else { + let mut available: Vec<&str> = Vec::new(); + for q in target.variants.iter().filter_map(|v| v.quality.as_deref()) { + if !available.contains(&q) { + available.push(q); + } + } + let avail_desc = if available.is_empty() { + "none verified".to_string() + } else { + available.join(", ") + }; + anyhow::bail!( + "Asset '{}' has no '{}' video variant (available: {})", + label, + wanted, + avail_desc + ); + }; + let changed = target.primary_media_id.as_deref() != Some(chosen.media_id.as_str()); + target.primary_media_id = Some(chosen.media_id); + if let Some(url) = chosen.url { + target.url = Some(url); + } else if changed { + target.url = None; + } + if chosen.width.is_some() { + target.width = chosen.width; + } + if chosen.height.is_some() { + target.height = chosen.height; + } + if chosen.duration.is_some() { + target.duration = chosen.duration; + } + Ok(()) + } + RequestedQuality::Best => { + if target.kind == "scene" && target.requires_scene_export { + return Ok(()); + } + let chosen = target + .variants + .iter() + .filter(|v| { + quality_rank(v.quality.as_deref()) > 0 + || (v.width.unwrap_or(0) > 0 && v.height.unwrap_or(0) > 0) + }) + .max_by_key(|v| { + let rank = quality_rank(v.quality.as_deref()); + let area = u64::from(v.width.unwrap_or(0)) * u64::from(v.height.unwrap_or(0)); + (rank, area) + }) + .cloned(); + if let Some(best) = chosen { + let changed = target.primary_media_id.as_deref() != Some(best.media_id.as_str()); + target.primary_media_id = Some(best.media_id); + if let Some(url) = best.url { + target.url = Some(url); + } else if changed { + target.url = None; + } + if best.width.is_some() { + target.width = best.width; + } + if best.height.is_some() { + target.height = best.height; + } + if best.duration.is_some() { + target.duration = best.duration; + } + } + Ok(()) + } + } +} + /// Resolves the matched Flow asset, downloads it to `/downloads`, and records it in SQLite. pub(crate) async fn download_asset( engine: &ChromeEngine, db: &FlowDb, match_str: &str, + quality: Option<&str>, ) -> Result { - let (target, project_id, project_title) = + let (mut target, project_id, project_title) = resolve_asset(engine, match_str, false, "flow_download").await?; + apply_download_quality(&mut target, quality)?; download_resolved_asset(engine, db, &target, project_id, project_title).await } diff --git a/src/download_urls.rs b/src/download_urls.rs new file mode 100644 index 0000000..77b5f49 --- /dev/null +++ b/src/download_urls.rs @@ -0,0 +1,304 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Media URL signature checks, expiration parsing, FIFE expansion, and Chrome URL lookup. + +use serde_json::{Value, json}; +use std::time::{SystemTime, UNIX_EPOCH}; +use url::Url; + +use crate::engine::ChromeEngine; + +/// Ordered URL candidates and media kind from `resolveVideoUrl`. +pub(crate) struct ResolvedMediaUrls { + /// Candidate URLs with signed direct URLs before unsigned URLs. + pub(crate) urls: Vec, + /// Media family from the `as29s` wire message when present. + pub(crate) media_kind: Option, + /// True when `as29s` case `11` returned raw 24 kHz PCM audio. + pub(crate) pcm_audio: bool, +} + +/// Returns `true` when `raw_url` carries signed GCS or Flow CDN hosts or V2/V4 query signatures. +pub(crate) fn is_signed_direct_url(raw_url: &str) -> bool { + let Ok(parsed) = Url::parse(raw_url) else { + return false; + }; + let Some(host) = parsed.host_str().map(str::to_ascii_lowercase) else { + return false; + }; + host == "storage.googleapis.com" + || host.ends_with(".storage.googleapis.com") + || host == "flow-content.google" + || host.ends_with(".flow-content.google") + || host == "labs-flow.dev" + || host.ends_with(".labs-flow.dev") + || host == "video-downloads.googleusercontent.com" + || host.ends_with(".video-downloads.googleusercontent.com") + || parsed.query_pairs().any(|(k, _)| { + matches!( + k.to_ascii_lowercase().as_str(), + "signature" + | "googleaccessid" + | "x-goog-signature" + | "x-goog-algorithm" + | "x-goog-credential" + | "x-goog-date" + | "x-goog-expires" + | "x-goog-signedheaders" + ) + }) +} + +/// Converts a proleptic Gregorian UTC date into days since `1970-01-01`. +fn civil_days_from_ymd(year: i64, month: u32, day: u32) -> i64 { + let y = year - i64::from(month <= 2); + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = (y - era * 400) as u64; + let m = u64::from(month); + let d = u64::from(day); + let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + (doe as i64) - 719_468 +} + +/// Parses a compact `YYYYMMDDTHHMMSSZ` timestamp into Unix epoch seconds. +fn parse_goog_date_secs(raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.len() != 16 { + return None; + } + let bytes = trimmed.as_bytes(); + if !matches!(bytes[8], b'T' | b't') || !matches!(bytes[15], b'Z' | b'z') { + return None; + } + let year: i64 = trimmed.get(0..4)?.parse().ok()?; + let month: u32 = trimmed.get(4..6)?.parse().ok()?; + let day: u32 = trimmed.get(6..8)?.parse().ok()?; + let hour: u64 = trimmed.get(9..11)?.parse().ok()?; + let minute: u64 = trimmed.get(11..13)?.parse().ok()?; + let second: u64 = trimmed.get(13..15)?.parse().ok()?; + if !(1..=12).contains(&month) + || !(1..=31).contains(&day) + || hour > 23 + || minute > 59 + || second > 60 + { + return None; + } + let days = civil_days_from_ymd(year, month, day); + let day_secs = u64::try_from(days).ok()?.checked_mul(86_400)?; + day_secs + .checked_add(hour * 3_600) + .and_then(|v| v.checked_add(minute * 60)) + .and_then(|v| v.checked_add(second)) +} + +/// Returns `true` when `raw_url` has a V4 or V2 GCS signature whose validity window has passed. +pub(crate) fn is_expired_signed_url(raw_url: &str) -> bool { + let Ok(parsed) = Url::parse(raw_url.trim()) else { + return false; + }; + let Ok(now_dur) = SystemTime::now().duration_since(UNIX_EPOCH) else { + return false; + }; + let now_secs = now_dur.as_secs(); + let mut goog_date: Option = None; + let mut goog_expires: Option = None; + let mut v2_expires: Option = None; + let mut has_v2_sig = false; + for (k, v) in parsed.query_pairs() { + match k.to_ascii_lowercase().as_str() { + "x-goog-date" => goog_date = Some(v.into_owned()), + "x-goog-expires" => goog_expires = Some(v.into_owned()), + "expires" => v2_expires = Some(v.into_owned()), + "signature" | "googleaccessid" => has_v2_sig = true, + _ => {} + } + } + if let (Some(date_str), Some(exp_str)) = (goog_date, goog_expires) { + let Some(issued_secs) = parse_goog_date_secs(&date_str) else { + return true; + }; + let Ok(expires_secs) = exp_str.trim().parse::() else { + return true; + }; + return now_secs >= issued_secs.saturating_add(expires_secs); + } + if has_v2_sig && let Some(v2_str) = v2_expires { + let Ok(exp_secs) = v2_str.trim().parse::() else { + return true; + }; + return now_secs >= exp_secs; + } + false +} + +/// Appends `raw` to `out` when it uses an allowed scheme and is not already present. +pub(crate) fn push_unique_url(out: &mut Vec, raw: &str) { + let trimmed = raw.trim(); + let lower = trimmed.to_ascii_lowercase(); + if !(lower.starts_with("http://") + || lower.starts_with("https://") + || lower.starts_with("blob:") + || lower.starts_with("data:")) + { + return; + } + if !out.iter().any(|existing| existing == trimmed) { + out.push(trimmed.to_string()); + } +} + +/// Removes trailing `=...` FIFE resize or format suffixes from the final path segment. +fn strip_fife_path_options(path: &str) -> String { + match path.rsplit_once('/') { + Some((dir, leaf)) => { + let clean_leaf = match leaf.rfind('=') { + Some(idx) => &leaf[..idx], + None => leaf, + }; + format!("{}/{}", dir, clean_leaf) + } + None => match path.rfind('=') { + Some(idx) => path[..idx].to_string(), + None => path.to_string(), + }, + } +} + +/// Expands unsigned image or video FIFE URLs into prioritized original and download variants. +pub(crate) fn push_fife_candidates(out: &mut Vec, raw_url: &str, expected_kind: &str) { + if expected_kind == "audio" || is_signed_direct_url(raw_url) { + return; + } + let Ok(parsed) = Url::parse(raw_url) else { + return; + }; + let Some(host) = parsed.host_str().map(str::to_ascii_lowercase) else { + return; + }; + if !(host == "flow.google.com" + || host.ends_with(".googleusercontent.com") + || host.ends_with(".fife.usercontent.google.com")) + { + return; + } + let is_video = expected_kind == "video"; + let stripped_path = strip_fife_path_options(parsed.path()); + let use_proxy_first = host == "flow.google.com" || stripped_path.starts_with("/asb/"); + + if !use_proxy_first { + let mut orig_parsed = parsed.clone(); + let suffixes: &[&str] = if is_video { + &["=mm,22,15", "=dv", "=d"] + } else { + &["=d", "=s0"] + }; + for suffix in suffixes { + orig_parsed.set_path(&format!("{}{}", stripped_path, suffix)); + push_unique_url(out, orig_parsed.as_str()); + } + } + + let mut flow_parsed = parsed; + if flow_parsed.set_host(Some("flow.google.com")).is_ok() { + let suffixes: &[&str] = if is_video { + &["=mm,22,15", "=mm,18,15", "=dv", "=d"] + } else { + &["=d", "=s0"] + }; + for suffix in suffixes { + flow_parsed.set_path(&format!("{}{}", stripped_path, suffix)); + push_unique_url(out, flow_parsed.as_str()); + } + } +} + +/// Gets the media URLs from Chrome within the optional browser request time limit. +pub(crate) async fn eval_resolve_media_url( + engine: &ChromeEngine, + media_id: &str, + timeout_ms: Option, +) -> Option { + eval_resolve_media_url_opts(engine, media_id, timeout_ms, false).await +} + +/// Calls `resolveVideoUrl` in Chrome with optional time limit and cache bypass flags. +async fn eval_resolve_media_url_opts( + engine: &ChromeEngine, + media_id: &str, + timeout_ms: Option, + bypass_cache: bool, +) -> Option { + let val = engine + .call_flow_async( + "resolveVideoUrl", + json!([media_id, timeout_ms, bypass_cache]), + ) + .await + .ok()?; + (val.get("ok").and_then(|v| v.as_bool()) == Some(true)).then_some(val) +} + +/// Expands `eval_resolve_media_url` output and puts signed direct URLs before unsigned URLs. +pub(crate) async fn query_resolved_media_urls( + engine: &ChromeEngine, + media_id: &str, + fallback_kind: &str, + bypass_cache: bool, +) -> ResolvedMediaUrls { + let Some(val) = eval_resolve_media_url_opts(engine, media_id, None, bypass_cache).await else { + return ResolvedMediaUrls { + urls: Vec::new(), + media_kind: None, + pcm_audio: false, + }; + }; + let media_kind = val + .get("media_kind") + .and_then(|v| v.as_str()) + .map(str::to_string); + let pcm_audio = val + .get("pcm_audio") + .and_then(Value::as_bool) + .unwrap_or(false); + let effective_kind = if media_kind.as_deref() == Some("audio") { + "audio" + } else { + fallback_kind + }; + + let mut signed = Vec::new(); + let mut unsigned = Vec::new(); + let mut record_cand = |raw: &str| { + if is_signed_direct_url(raw) { + push_unique_url(&mut signed, raw); + } else { + push_unique_url(&mut unsigned, raw); + push_fife_candidates(&mut unsigned, raw, effective_kind); + } + }; + + if let Some(dl_url) = val.get("download_url").and_then(|v| v.as_str()) { + record_cand(dl_url); + } + if let Some(url) = val.get("url").and_then(|v| v.as_str()) { + record_cand(url); + } + if let Some(cands) = val.get("candidates").and_then(|v| v.as_array()) { + for cand in cands.iter().filter_map(|v| v.as_str()) { + record_cand(cand); + } + } + + let mut urls = signed; + for cand in unsigned { + push_unique_url(&mut urls, &cand); + } + ResolvedMediaUrls { + urls, + media_kind, + pcm_audio, + } +} diff --git a/src/main.rs b/src/main.rs index d180c44..525c287 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ mod agent; mod agent_settings; +mod asset_matching; mod assets; mod auth; mod cdp; @@ -17,6 +18,7 @@ mod config; mod cookies; mod db; mod download; +mod download_urls; mod engine; mod generation; mod http; diff --git a/src/mcp.rs b/src/mcp.rs index 2a0eef9..66bf327 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -24,7 +24,7 @@ use tokio::time::Duration; use crate::agent::AgentParams; use crate::assets::{AssetsParams, DownloadParams, RenameParams, TrashParams}; use crate::auth::LoginParams; -use crate::characters::{CharacterEditParams, CharacterParams, VoicesParams}; +use crate::characters::{CharacterEditParams, CharacterParams}; use crate::collections::CollectionsParams; use crate::db::{DOWNLOAD_ASSET_RESOURCE_PREFIX, DOWNLOAD_RESOURCE_PREFIX, DownloadsParams}; use crate::generation::{EditParams, GenerateParams}; @@ -32,7 +32,7 @@ use crate::project::{NewProjectParams, ProjectsParams, StatusParams}; use crate::queue::{JobIdParams, WaitParams}; use crate::scenes::{ScenesParams, VideoParams}; use crate::service::{self, FlowService, ResourceReadError}; -use crate::voices::VoicePreviewParams; +use crate::voices::{VoicePreviewParams, VoicesParams}; /// Inline wait limit (`45_000` ms) before slow tools return a pending task handle. const PATIENCE_MS: u64 = 45_000; @@ -206,7 +206,7 @@ impl FlowMcpServer { /// Downloads a media asset from the active Google Flow project. #[tool( - description = "Download an image, video, audio, or character asset from the active Google Flow project." + description = "Download an image, video, audio, character, scene, or : scene clip from the active Google Flow project, with optional video quality selection." )] async fn flow_download( &self, diff --git a/src/media_files.rs b/src/media_files.rs index 7733e3d..7e3cb73 100644 --- a/src/media_files.rs +++ b/src/media_files.rs @@ -316,6 +316,37 @@ pub(crate) fn validate_content_type_header(ct: Option<&str>, expected_kind: &str Ok(()) } +/// Returns `true` when `hdr` starts with an `ID3` tag or a valid 4-byte MPEG Layer II/III header. +fn has_valid_mp3_header(hdr: &[u8]) -> bool { + if hdr.starts_with(b"ID3") { + return true; + } + if hdr.len() < 4 || hdr[0] != 0xFF || (hdr[1] & 0xE0) != 0xE0 { + return false; + } + let version_bits = (hdr[1] >> 3) & 0x03; + let layer_bits = (hdr[1] >> 1) & 0x03; + let bitrate_index = (hdr[2] >> 4) & 0x0F; + let sample_rate_index = (hdr[2] >> 2) & 0x03; + version_bits != 0x01 + && matches!(layer_bits, 0x01 | 0x02) + && bitrate_index != 0 + && bitrate_index != 0x0F + && sample_rate_index != 0x03 +} + +/// Returns `true` when `hdr` starts with a valid 7-byte ADTS AAC frame header. +fn has_valid_adts_header(hdr: &[u8]) -> bool { + if hdr.len() < 7 || hdr[0] != 0xFF || (hdr[1] & 0xF6) != 0xF0 { + return false; + } + let sample_rate_index = (hdr[2] >> 2) & 0x0F; + let frame_len = ((usize::from(hdr[3] & 0x03)) << 11) + | (usize::from(hdr[4]) << 3) + | usize::from(hdr[5] >> 5); + sample_rate_index < 13 && frame_len >= 7 +} + /// Checks leading file magic bytes to verify media type and infer generic MIME headers. pub(crate) async fn validate_downloaded_file( path: &Path, @@ -334,11 +365,12 @@ pub(crate) async fn validate_downloaded_file( } let hdr = &buf[..total]; - let start = hdr + let after_bom = hdr.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(hdr); + let start = after_bom .iter() .position(|b| !b.is_ascii_whitespace()) - .unwrap_or(hdr.len()); - let trimmed_lower: Vec = hdr[start..] + .unwrap_or(after_bom.len()); + let trimmed_lower: Vec = after_bom[start..] .iter() .take(16) .map(|b| b.to_ascii_lowercase()) @@ -347,11 +379,14 @@ pub(crate) async fn validate_downloaded_file( || trimmed_lower.starts_with(b"= 12 && &hdr[0..4] == b"FORM" && matches!(&hdr[8..12], b"AIFF" | b"AIFC"); - let is_mp3 = !is_jpeg - && (hdr.starts_with(b"ID3") - || (hdr.len() >= 2 - && hdr[0] == 0xFF - && (hdr[1] & 0xE0) == 0xE0 - && (hdr[1] & 0x06) != 0)); - let is_aac = !is_jpeg && hdr.len() >= 2 && hdr[0] == 0xFF && (hdr[1] & 0xF6) == 0xF0; + let is_mp3 = !is_jpeg && has_valid_mp3_header(hdr); + let is_aac = !is_jpeg && has_valid_adts_header(hdr); let is_m4a = hdr.len() >= 12 && &hdr[4..8] == b"ftyp" && matches!(&hdr[8..12], b"M4A " | b"M4B " | b"M4P "); diff --git a/src/service.rs b/src/service.rs index 4b8223b..3f40374 100644 --- a/src/service.rs +++ b/src/service.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use crate::agent::{AgentChat, AgentParams}; use crate::assets::{self, AssetAction, AssetsParams, DownloadParams, RenameEntry}; use crate::auth::{self, LoginParams}; -use crate::characters::{self, CharacterEditParams, CharacterParams, VoicesParams}; +use crate::characters::{self, CharacterEditParams, CharacterParams}; use crate::collections::{self, CollectionsParams}; use crate::config; use crate::db::{ @@ -28,7 +28,7 @@ use crate::queue::{JobQueue, JobResult, JobRunner, JobView, SceneParams, WaitPar use crate::scenes::{self, ScenesParams, VideoParams}; use crate::tile_menu::PageHold; use crate::upload::{local_upload_paths, upload_project_files}; -use crate::voices::{self, VoicePreviewParams}; +use crate::voices::{self, VoicePreviewParams, VoicesParams}; /// Maximum downloaded file size served directly through MCP `resources/read` (`64 MiB`). const MAX_RESOURCE_READ_BYTES: u64 = 64 * 1024 * 1024; @@ -255,7 +255,7 @@ impl FlowService { /// Lists available Google Flow character voices. pub(crate) async fn voices(&self, req: VoicesParams) -> Result { - characters::list_voices(&self.engine, &self.db, req.character.as_deref()).await + voices::list_voices(&self.engine, &self.db, req.character.as_deref()).await } /// Plays a character voice preview and downloads the audio. @@ -406,7 +406,7 @@ impl FlowService { /// Downloads the asset matching `req.match` into `/downloads` and records it in SQLite. pub(crate) async fn download(&self, req: DownloadParams) -> Result { - download::download_asset(&self.engine, &self.db, &req.r#match).await + download::download_asset(&self.engine, &self.db, &req.r#match, req.quality.as_deref()).await } /// Resolves one download record by row `id` or latest `asset_id` for inspection or chunk reads. diff --git a/src/voices.rs b/src/voices.rs index f70cebe..a99cebf 100644 --- a/src/voices.rs +++ b/src/voices.rs @@ -9,9 +9,10 @@ use schemars::JsonSchema; use serde::Deserialize; use serde_json::{Value, json}; -use crate::assets::{FlowAsset, list_assets_with_project, match_asset}; +use crate::assets::{FlowAsset, list_assets_with_project, match_asset, trash_asset}; use crate::characters::{exit_character_editor, open_character_editor}; use crate::config::downloads_dir; +use crate::db::FlowDb; use crate::engine::{ChromeEngine, checked_runtime_result}; use crate::platform::{create_private_dir_all, write_private_file_atomic}; use crate::project::{ensure_flow_store, ensure_project_workspace_root, project_id_from_url}; @@ -20,6 +21,13 @@ use crate::queue::SceneParams; /// Largest length of the Sample dialogue text that Google Flow accepts. const MAX_SAMPLE_CHARS: usize = 120; +/// Parameters for `flow_voices`. +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub(crate) struct VoicesParams { + /// Optional character ID or name whose editor opens the voice picker. + pub(crate) character: Option, +} + /// Parameters for `flow_voice_preview`. #[derive(Debug, Clone, Deserialize, JsonSchema)] pub(crate) struct VoicePreviewParams { @@ -165,7 +173,7 @@ pub(crate) async fn delete_portrait(engine: &ChromeEngine) -> Result<()> { } /// Scrolls the whole voice dialog list of the open character and returns all voices, or None on failure. -pub(crate) async fn list_all_voices(engine: &ChromeEngine) -> Option { +async fn list_all_voices(engine: &ChromeEngine) -> Option { let res = engine .call_flow_async("characterExtraOp", json!([{ "action": "list_all_voices" }])) .await @@ -176,6 +184,106 @@ pub(crate) async fn list_all_voices(engine: &ChromeEngine) -> Option { res.get("voices").cloned() } +/// Lists available Flow character voices from the character editor voice picker. +pub(crate) async fn list_voices( + engine: &ChromeEngine, + db: &FlowDb, + character: Option<&str>, +) -> Result { + ensure_flow_store(engine).await?; + let initial_url = engine.current_url().await.unwrap_or_default(); + let mut project_id = project_id_from_url(&initial_url); + let mut temp_char_id: Option = None; + + if !initial_url.contains("/character/") { + let snap = list_assets_with_project(engine).await?; + if project_id.is_none() { + project_id = snap.project_id.clone(); + } + let pid = project_id + .as_deref() + .ok_or_else(|| anyhow::anyhow!("Missing project ID for character route"))?; + let chars: Vec = snap + .assets + .into_iter() + .filter(|a| a.kind == "character") + .collect(); + let target_cid = if let Some(q) = character.map(str::trim).filter(|s| !s.is_empty()) { + match_asset(&chars, q, false).map(|c| c.id.clone()) + } else { + chars.first().map(|c| c.id.clone()) + }; + + let cid = if let Some(existing_cid) = target_cid { + existing_cid + } else { + let created = engine + .call_flow_async( + "characterOp", + json!([{ + "action": "create", + "name": "__tmp_voice_probe__", + }]), + ) + .await?; + if created.get("ok").and_then(|v| v.as_bool()) != Some(true) { + anyhow::bail!( + "Failed to create temporary character for voice lookup: {}", + created + .get("error") + .and_then(|v| v.as_str()) + .unwrap_or("unknown") + ); + } + let tmp_cid = created + .get("id") + .and_then(|v| v.as_str()) + .map(str::to_string) + .ok_or_else(|| { + anyhow::anyhow!("Temporary character creation returned no character ID") + })?; + temp_char_id = Some(tmp_cid.clone()); + tmp_cid + }; + + open_character_editor(engine, &initial_url, pid, &cid).await?; + } + + let full_list = list_all_voices(engine).await; + let voices_res = match full_list { + Some(voices) => Ok(json!({ "ok": true, "voices": voices })), + None => { + engine + .call_flow_async("characterVoiceOp", json!([{ "action": "list_voices" }])) + .await + } + }; + + exit_character_editor(engine, project_id.as_deref()).await; + if let Some(tmp_id) = temp_char_id { + let _ = trash_asset(engine, db, &tmp_id).await; + } + + let res = voices_res?; + if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { + anyhow::bail!( + "Failed to list Flow character voices: {}", + res.get("error") + .and_then(|v| v.as_str()) + .unwrap_or("unknown") + ); + } + let count = res + .get("voices") + .and_then(|v| v.as_array()) + .map(|a| a.len()) + .unwrap_or(0); + Ok(json!({ + "count": count, + "voices": res.get("voices").cloned().unwrap_or_else(|| json!([])), + })) +} + /// Opens a character, plays its voice preview (or auditions `voice` without saving), saves the audio under `/downloads`, and returns the file path. pub(crate) async fn preview_voice( engine: &ChromeEngine, diff --git a/ts/custom_voices.ts b/ts/custom_voices.ts new file mode 100644 index 0000000..07ae819 --- /dev/null +++ b/ts/custom_voices.ts @@ -0,0 +1,445 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Extract saved custom voices from PROJECT_TILES and map look-less character voices. + +import { readOwn } from "./angular"; +import { asHttpOrDataUrl, isExpiredSignedUrl, normalizeFlowMediaUrl } from "./dom"; +import { snapshotFormat } from "./frontend_builds"; +import { runtimeState } from "./state"; +import type { CustomVoiceItem, FifeEnv, FlowTile, SnapshotAssetItem } from "./types"; + +/** Reads a 1-based field from a dense or sparse serialized JSPB array. */ +function voiceProtoField(msg: unknown, field: number): unknown { + if (!Array.isArray(msg) || field < 1) return undefined; + const tail: unknown = msg[msg.length - 1]; + if (tail && typeof tail === "object" && !Array.isArray(tail)) { + const mapped = readOwn(tail, String(field)); + if (mapped !== undefined) return mapped; + } + return msg[field - 1]; +} + +/** Iterates values from a `Map`, array, or plain record. */ +function mapValues(source: unknown): unknown[] { + if (source instanceof Map) return Array.from(source.values()); + if (Array.isArray(source)) return source; + if (source && typeof source === "object") return Object.values(source); + return []; +} + +/** Builds a workflow and tile display-name lookup map from `lr` and `rowsField`. */ +function buildVoiceNameMap(data: unknown, rowsField: string): Map { + const names = new Map(); + const register = (key: unknown, title: unknown): void => { + if (typeof key !== "string" || typeof title !== "string") return; + const cleanKey = key.trim(); + const cleanTitle = title.trim(); + if (!cleanKey || !cleanTitle) return; + names.set(cleanKey, cleanTitle); + names.set(cleanKey.replace(/^(?:media|workflows)\//i, ""), cleanTitle); + }; + + const rows = readOwn(data, rowsField); + if (Array.isArray(rows)) { + for (const row of rows) { + const displayName = readOwn(row, "displayName"); + register(readOwn(row, "id"), displayName); + register(readOwn(row, "workflowId"), displayName); + register(readOwn(row, "primaryMediaId"), displayName); + } + } + + const lr = readOwn(data, "lr"); + const lrEntries: Array<[unknown, unknown]> = + lr instanceof Map + ? Array.from(lr.entries()) + : lr && typeof lr === "object" && !Array.isArray(lr) + ? Object.entries(lr) + : []; + for (const [wfKey, wfVal] of lrEntries) { + let wfId: unknown = wfKey; + let wfTitle: unknown = readOwn(wfVal, "displayName") ?? readOwn(wfVal, "name"); + const getNameFn = readOwn(wfVal, "getName"); + if (typeof getNameFn === "function") { + try { + wfId = getNameFn.call(wfVal) ?? wfId; + } catch { + // Keep map key fallback. + } + } + const getMetaFn = readOwn(wfVal, "getMetadata"); + if (!wfTitle && typeof getMetaFn === "function") { + try { + const meta: unknown = getMetaFn.call(wfVal); + const qdFn = readOwn(meta, "Qd"); + if (typeof qdFn === "function") { + wfTitle = qdFn.call(meta); + } + } catch { + // Fall through to serialized JSON check. + } + } + const toJsonFn = readOwn(wfVal, "toJSON"); + if (!wfTitle && typeof toJsonFn === "function") { + try { + const rawWf: unknown = toJsonFn.call(wfVal); + wfId = voiceProtoField(rawWf, 1) ?? wfId; + const rawMeta = voiceProtoField(rawWf, 4) ?? voiceProtoField(rawWf, 3); + wfTitle = voiceProtoField(rawMeta, 1); + } catch { + // Ignore malformed workflow entry. + } + } + register(wfId, wfTitle); + } + return names; +} + +/** Extracts saved custom voices from `cj` and `lr` on settled `PROJECT_TILES` query data. */ +export function readCustomVoicesFromQueryData( + data: unknown, + rowsField: string, +): CustomVoiceItem[] { + if (!data || typeof data !== "object") return []; + const cj = readOwn(data, "cj"); + const candidates = mapValues(cj); + if (candidates.length === 0) return []; + + const nameMap = buildVoiceNameMap(data, rowsField); + const frontEnd = readOwn(window, "default_AiSandboxAngularFrontend"); + const hUbFn = readOwn(frontEnd, "hUb"); + const fvFn = readOwn(frontEnd, "fv"); + const brOneof = readOwn(frontEnd, "Br"); + + const out: CustomVoiceItem[] = []; + const seen = new Set(); + const lookupTitle = (wfId: string | null, mediaId: string): string | null => { + if (wfId) { + const hit = nameMap.get(wfId) ?? nameMap.get(wfId.replace(/^workflows\//i, "")); + if (hit) return hit; + } + return nameMap.get(mediaId) ?? nameMap.get(mediaId.replace(/^media\//i, "")) ?? null; + }; + + for (const item of candidates) { + if (!item || typeof item !== "object") continue; + + if ( + typeof hUbFn === "function" && + typeof fvFn === "function" && + Array.isArray(brOneof) + ) { + try { + const isAudio = Boolean( + (fvFn as (msg: unknown, field: number, oneof: unknown[]) => unknown).call( + frontEnd, + item, + 11, + brOneof, + ), + ); + if (!isAudio) continue; + const mapped = ( + hUbFn as (msg: unknown, names: Map) => Record | undefined + ).call(frontEnd, item, nameMap); + if (!mapped || mapped.Rv === true || mapped.Db === true) continue; + const rawId = String(mapped.id ?? mapped.workflowId ?? mapped.mediaId ?? "").trim(); + if (!rawId || /^voices\//i.test(rawId)) continue; + const mediaId = String(mapped.mediaId ?? rawId) + .trim() + .replace(/^(?:media|workflows)\//i, ""); + if (!mediaId || seen.has(mediaId)) continue; + seen.add(mediaId); + const wfId = + typeof mapped.workflowId === "string" && mapped.workflowId.trim() + ? mapped.workflowId.trim() + : null; + const assetId = rawId.replace(/^(?:media|workflows)\//i, "") || mediaId; + const prompt = + typeof mapped.description === "string" && mapped.description.trim() + ? mapped.description.trim() + : typeof mapped.f7 === "string" && mapped.f7.trim() + ? mapped.f7.trim() + : null; + const rawUrl = typeof mapped.NU === "string" ? mapped.NU.trim() : ""; + const created = + mapped.rm instanceof Date && mapped.rm.getTime() > 0 + ? mapped.rm.toISOString() + : null; + out.push({ + id: assetId, + name: + (typeof mapped.title === "string" && mapped.title.trim()) || + lookupTitle(wfId, mediaId) || + "Custom voice", + mediaId, + workflowId: wfId, + prompt, + url: /^https?:\/\//i.test(rawUrl) ? rawUrl : null, + createdAt: created, + }); + continue; + } catch { + // Fall through to structural JSPB and plain-object inspection. + } + } + + const toJsonFn = readOwn(item, "toJSON"); + const serialized: unknown = + typeof toJsonFn === "function" + ? (() => { + try { + return toJsonFn.call(item); + } catch { + return null; + } + })() + : Array.isArray(item) + ? item + : null; + + if (Array.isArray(serialized)) { + const audioBranch = voiceProtoField(serialized, 11); + if (!audioBranch || typeof audioBranch !== "object") continue; + const audioInner = Array.isArray(audioBranch) + ? (voiceProtoField(audioBranch, 1) ?? audioBranch) + : (readOwn(audioBranch, "1") ?? audioBranch); + if (voiceProtoField(audioInner, 3) === true) continue; + const rawName = voiceProtoField(serialized, 1); + if (typeof rawName !== "string" || !rawName.trim() || /^voices\//i.test(rawName.trim())) { + continue; + } + const mediaId = rawName.trim().replace(/^media\//i, ""); + if (!mediaId || seen.has(mediaId)) continue; + const meta = + voiceProtoField(serialized, 4) ?? + voiceProtoField(serialized, 5) ?? + voiceProtoField(serialized, 6); + if (voiceProtoField(meta, 4) === true) continue; + seen.add(mediaId); + const wfRaw = voiceProtoField(serialized, 3); + const wfId = typeof wfRaw === "string" && wfRaw.trim() ? wfRaw.trim() : null; + const metaTitle = voiceProtoField(meta, 2); + const audioName = voiceProtoField(audioInner, 1); + const title = + (typeof metaTitle === "string" && metaTitle.trim()) || + (typeof audioName === "string" && audioName.trim()) || + lookupTitle(wfId, mediaId) || + "Custom voice"; + const desc = + voiceProtoField(audioInner, 8) ?? + voiceProtoField(audioInner, 2) ?? + voiceProtoField(audioInner, 5); + const urlCand = voiceProtoField(audioInner, 4) ?? voiceProtoField(audioInner, 6); + out.push({ + id: mediaId, + name: title, + mediaId, + workflowId: wfId, + prompt: typeof desc === "string" && desc.trim() ? desc.trim() : null, + url: + typeof urlCand === "string" && /^https?:\/\//i.test(urlCand.trim()) + ? urlCand.trim() + : null, + createdAt: null, + }); + continue; + } + + if (readOwn(item, "Rv") === true || readOwn(item, "Db") === true || readOwn(item, "trashed") === true) { + continue; + } + const kindHint = String(readOwn(item, "type") ?? readOwn(item, "kind") ?? "").toUpperCase(); + const hasAudioField = + kindHint === "VOICE" || + kindHint === "AUDIO" || + readOwn(item, "audio") != null || + typeof readOwn(item, "NU") === "string"; + if (!hasAudioField) continue; + const rawId = String(readOwn(item, "mediaId") ?? readOwn(item, "id") ?? "").trim(); + if (!rawId || /^voices\//i.test(rawId)) continue; + const mediaId = rawId.replace(/^media\//i, ""); + if (!mediaId || seen.has(mediaId)) continue; + seen.add(mediaId); + const wfRaw = readOwn(item, "workflowId"); + const wfId = typeof wfRaw === "string" && wfRaw.trim() ? wfRaw.trim() : null; + const rawTitle = readOwn(item, "title") ?? readOwn(item, "displayName") ?? readOwn(item, "name"); + const rawPrompt = readOwn(item, "description") ?? readOwn(item, "prompt") ?? readOwn(item, "f7"); + const rawUrl = readOwn(item, "NU") ?? readOwn(item, "url"); + const rawCreated = readOwn(item, "rm") ?? readOwn(item, "createdAt") ?? readOwn(item, "createTime"); + out.push({ + id: mediaId, + name: + (typeof rawTitle === "string" && rawTitle.trim()) || + lookupTitle(wfId, mediaId) || + "Custom voice", + mediaId, + workflowId: wfId, + prompt: typeof rawPrompt === "string" && rawPrompt.trim() ? rawPrompt.trim() : null, + url: + typeof rawUrl === "string" && /^https?:\/\//i.test(rawUrl.trim()) + ? rawUrl.trim() + : null, + createdAt: + rawCreated instanceof Date + ? rawCreated.toISOString() + : typeof rawCreated === "string" && rawCreated.trim() + ? rawCreated.trim() + : null, + }); + } + + return out; +} + +/** Extracts the assigned custom or preset voice ID from a character tile when present. */ +export function characterAssignedVoiceId(t: FlowTile): string | null { + const format = snapshotFormat()?.character; + const entity = readOwn(t, format?.entity ?? "Rc"); + const serialize = readOwn(entity, "toJSON"); + if (typeof serialize === "function") { + try { + const root: unknown = serialize.call(entity); + const info = voiceProtoField( + voiceProtoField(root, format?.entityInfoField ?? 4), + format?.characterInfoField ?? 3, + ); + const refs = voiceProtoField(info, format?.audioReferencesField ?? 2); + if (Array.isArray(refs) && refs.length > 0) { + const first: unknown = refs[0]; + const custom = voiceProtoField(first, format?.customVoiceField ?? 1); + if (typeof custom === "string" && custom.trim()) { + return custom.trim().replace(/^media\//i, ""); + } + const preset = voiceProtoField(first, format?.presetVoiceField ?? 2); + if (typeof preset === "string" && preset.trim()) { + return preset.trim(); + } + } + } catch { + // Fall through to plain tile voice fields. + } + } + for (const cand of [t.voiceId, t.Vo, t.voice]) { + if (typeof cand === "string" && cand.trim()) { + return cand.trim().replace(/^media\//i, ""); + } + if (cand && typeof cand === "object" && !Array.isArray(cand)) { + const nested = + readOwn(cand, "mediaId") ?? + readOwn(cand, "voiceId") ?? + readOwn(cand, "id"); + if (typeof nested === "string" && nested.trim()) { + return nested.trim().replace(/^media\//i, ""); + } + } + } + return null; +} + +/** Resolves a look-less character's assigned voice against `customVoices`. */ +export function resolveLooklessCharacterVoice( + tile: FlowTile, + lookUrl: string | null, + lookPrimaryMediaId: string | null, + customVoices: CustomVoiceItem[], +): { + url: string | null; + primaryMediaId: string | null; + isVoice: boolean; + pcmAudio: boolean; +} { + const nonExpired = (raw: unknown): string | null => { + const direct = asHttpOrDataUrl(raw); + return direct && !isExpiredSignedUrl(direct) ? direct : null; + }; + if (lookUrl || lookPrimaryMediaId) { + return { + url: nonExpired(lookUrl), + primaryMediaId: lookPrimaryMediaId, + isVoice: false, + pcmAudio: false, + }; + } + const rawRef = characterAssignedVoiceId(tile); + if (!rawRef) { + return { url: null, primaryMediaId: null, isVoice: false, pcmAudio: false }; + } + const cleanRef = rawRef.replace(/^(?:media|workflows)\//i, ""); + const matched = customVoices.find( + (v) => + v.id === rawRef || + v.id === cleanRef || + v.mediaId === cleanRef || + (v.workflowId !== null && + (v.workflowId === rawRef || + v.workflowId.replace(/^workflows\//i, "") === cleanRef)), + ); + return { + url: nonExpired(matched?.url), + primaryMediaId: matched ? matched.mediaId : rawRef, + isVoice: true, + pcmAudio: Boolean(matched), + }; +} + +/** Appends saved custom voices that do not collide with existing tile or workflow IDs. */ +export function appendCustomVoiceAssets( + customVoices: CustomVoiceItem[], + byId: Map>, + rawList: Array>, + env: FifeEnv, +): void { + const nonExpired = (raw: unknown): string | null => { + const direct = asHttpOrDataUrl(raw); + return direct && !isExpiredSignedUrl(direct) ? direct : null; + }; + const isSignedUrlStr = (url: string | null): url is string => { + if (url === null) return false; + try { + return env.isSignedCdnHost(new URL(url)); + } catch { + return false; + } + }; + + for (const voice of customVoices) { + if (!voice.id || byId.has(voice.id)) continue; + if (voice.workflowId && byId.has(voice.workflowId)) continue; + const cachedVoice = runtimeState.mediaInfoCache.get(voice.mediaId); + const directVoiceUrl = nonExpired(voice.url); + const cachedVoiceUrl = nonExpired(cachedVoice?.url); + const rawVoiceUrl = isSignedUrlStr(directVoiceUrl) + ? directVoiceUrl + : isSignedUrlStr(cachedVoiceUrl) + ? cachedVoiceUrl + : directVoiceUrl || cachedVoiceUrl || null; + const voiceMediaIds = voice.mediaId ? [voice.mediaId] : []; + const voiceEntry: Omit = { + id: voice.id, + name: voice.name, + kind: "audio", + prompt: voice.prompt, + url: rawVoiceUrl ? normalizeFlowMediaUrl(rawVoiceUrl, "audio", env) : null, + collection_id: null, + primary_media_id: voice.mediaId, + personality_notes: null, + voice: voice.name, + trim_start_seconds: null, + trim_end_seconds: null, + media_status: "success", + media_error: null, + width: null, + height: null, + duration: null, + created_at: voice.createdAt, + media_ids: voiceMediaIds, + workflow_id: voice.workflowId, + pcm_audio: true, + media_kind: "audio", + }; + rawList.push(voiceEntry); + byId.set(voice.id, voiceEntry); + } +} diff --git a/ts/dom.ts b/ts/dom.ts index 55266d1..94bc8c2 100644 --- a/ts/dom.ts +++ b/ts/dom.ts @@ -4,7 +4,6 @@ // Shared DOM, event, input, and FIFE URL helpers for Flow browser modules. import { snapshotFormat } from "./frontend_builds"; -import { selectBestVideoVariant } from "./media_variants"; import type { CharacterLookEntry, FifeEnv, FlowMediaPayload, FlowTile } from "./types"; /** Reads an own data property from `o` without invoking prototype getters. */ @@ -316,66 +315,10 @@ export function characterLooksOf( return null; } -/** Reads a 1-based field from a dense or sparse serialized JSPB array. */ -function serializedProtoField(message: unknown, field: number): unknown { - if (!Array.isArray(message) || field < 1) return undefined; - const tail: unknown = message[message.length - 1]; - if (tail && typeof tail === "object" && !Array.isArray(tail)) { - const mapped = readMediaField(tail, String(field)); - if (mapped !== undefined) return mapped; - } - return message[field - 1]; -} - -/** Extracts the assigned custom or preset voice ID from a character tile when present. */ -function characterAssignedVoiceId(t: FlowTile): string | null { - const format = snapshotFormat()?.character; - const entity = readMediaField(t, format?.entity ?? "Rc"); - const serialize = readMediaField(entity, "toJSON"); - if (typeof serialize === "function") { - try { - const root: unknown = serialize.call(entity); - const info = serializedProtoField( - serializedProtoField(root, format?.entityInfoField ?? 4), - format?.characterInfoField ?? 3, - ); - const refs = serializedProtoField(info, format?.audioReferencesField ?? 2); - if (Array.isArray(refs) && refs.length > 0) { - const first: unknown = refs[0]; - const custom = serializedProtoField(first, format?.customVoiceField ?? 1); - if (typeof custom === "string" && custom.trim()) { - return custom.trim().replace(/^media\//i, ""); - } - const preset = serializedProtoField(first, format?.presetVoiceField ?? 2); - if (typeof preset === "string" && preset.trim()) { - return preset.trim(); - } - } - } catch { - // Fall through to plain tile voice fields. - } - } - for (const cand of [t.voiceId, t.Vo, t.voice]) { - if (typeof cand === "string" && cand.trim()) { - return cand.trim().replace(/^media\//i, ""); - } - if (cand && typeof cand === "object" && !Array.isArray(cand)) { - const nested = - readMediaField(cand, "mediaId") ?? - readMediaField(cand, "voiceId") ?? - readMediaField(cand, "id"); - if (typeof nested === "string" && nested.trim()) { - return nested.trim().replace(/^media\//i, ""); - } - } - } - return null; -} - -/** Extracts the preferred look image URL and primary media ID (or voice ID on look-less characters) from character tile `t`. */ +/** Extracts the preferred look image URL and primary media ID from character tile `t`. */ export function characterLookMedia( t: FlowTile | null | undefined, -): { url: string | null; primaryMediaId: string | null; isVoice?: boolean } { +): { url: string | null; primaryMediaId: string | null } { if (!t || typeof t !== "object") return { url: null, primaryMediaId: null }; const charFmt = snapshotFormat()?.character; const previewRaw = (charFmt ? readMediaField(t, charFmt.previewMediaId) : undefined) ?? t.Kd; @@ -416,17 +359,9 @@ export function characterLookMedia( } } } - const lookUrl = preferredId ? preferredUrl : fallbackUrl; - const lookPrimaryId = preferredId || firstPrimaryId; - if (!lookUrl && !lookPrimaryId && String(t.type ?? "").toUpperCase() === "CHARACTER") { - const voiceId = characterAssignedVoiceId(t); - if (voiceId) { - return { url: null, primaryMediaId: voiceId, isVoice: true }; - } - } return { - url: lookUrl, - primaryMediaId: lookPrimaryId, + url: preferredId ? preferredUrl : fallbackUrl, + primaryMediaId: preferredId || firstPrimaryId, }; } @@ -694,11 +629,9 @@ export function pickTileUrl(tile: FlowTile | null | undefined): string | null { const kind = String(t.type ?? "").toUpperCase() === "VIDEO" ? "video" : "image"; const nonExpired = (cand: string | null): string | null => cand && !isExpiredSignedUrl(cand) ? cand : null; - const variantChoice = kind === "video" ? selectBestVideoVariant(t) : null; const videoUrl = kind === "video" - ? variantChoice?.url || - nonExpired(readMediaUrl(t.Fb, true)) || + ? nonExpired(readMediaUrl(t.Fb, true)) || nonExpired(readMediaUrl(t, true)) || nonExpired(readMediaUrl(t.fb, true)) : null; diff --git a/ts/fetch_media.ts b/ts/fetch_media.ts index 782c923..88c4116 100644 --- a/ts/fetch_media.ts +++ b/ts/fetch_media.ts @@ -26,9 +26,90 @@ function hasAsciiAt(bytes: Uint8Array, ascii: string, offset = 0): boolean { return true; } +/** MPEG-1 Layer III bitrate table in kbps indexed by the 4-bit header index. */ +const MPEG1_L3_BITRATES = [ + 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0, +]; + +/** MPEG-1 Layer II bitrate table in kbps indexed by the 4-bit header index. */ +const MPEG1_L2_BITRATES = [ + 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0, +]; + +/** MPEG-2 and MPEG-2.5 Layer II/III bitrate table in kbps indexed by the 4-bit header index. */ +const MPEG2_L23_BITRATES = [ + 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0, +]; + +/** Computes the exact byte length of an MPEG Layer II/III audio frame at `offset`, or 0 if invalid. */ +function parseMpegFrameLength(bytes: Uint8Array, offset: number): number { + if (offset + 4 > bytes.byteLength) return 0; + const b0 = bytes[offset]; + const b1 = bytes[offset + 1]; + const b2 = bytes[offset + 2]; + if (b0 !== 0xff || (b1 & 0xe0) !== 0xe0) return 0; + const versionBits = (b1 >> 3) & 0x03; + const layerBits = (b1 >> 1) & 0x03; + if (versionBits === 1 || (layerBits !== 1 && layerBits !== 2)) return 0; + const bitrateIdx = (b2 >> 4) & 0x0f; + const srIdx = (b2 >> 2) & 0x03; + if (bitrateIdx === 0 || bitrateIdx === 15 || srIdx === 3) return 0; + + const sampleRate = + versionBits === 3 + ? [44100, 48000, 32000][srIdx] + : versionBits === 2 + ? [22050, 24000, 16000][srIdx] + : [11025, 12000, 8000][srIdx]; + const bitrateKbps = + versionBits === 3 + ? layerBits === 1 + ? MPEG1_L3_BITRATES[bitrateIdx] + : MPEG1_L2_BITRATES[bitrateIdx] + : MPEG2_L23_BITRATES[bitrateIdx]; + if (!sampleRate || !bitrateKbps) return 0; + const padding = (b2 >> 1) & 0x01; + const coeff = layerBits === 1 && versionBits !== 3 ? 72000 : 144000; + return Math.floor((coeff * bitrateKbps) / sampleRate) + padding; +} + +/** Returns true when `bytes` carry two consecutive MPEG Layer II/III or ADTS AAC audio frames. */ +function hasFramedMpegOrAdtsAudio(bytes: Uint8Array): boolean { + const mpegFrameLen = parseMpegFrameLength(bytes, 0); + if ( + mpegFrameLen >= 24 && + bytes.byteLength >= mpegFrameLen + 4 && + parseMpegFrameLength(bytes, mpegFrameLen) >= 24 && + (bytes[mpegFrameLen + 1] & 0x1e) === (bytes[1] & 0x1e) && + (bytes[mpegFrameLen + 2] & 0x0c) === (bytes[2] & 0x0c) + ) { + return true; + } + + if (bytes.byteLength >= 14 && bytes[0] === 0xff && (bytes[1] & 0xf6) === 0xf0) { + const srIdx = (bytes[2] >> 2) & 0x0f; + const adtsLen = + ((bytes[3] & 0x03) << 11) | (bytes[4] << 3) | ((bytes[5] >> 5) & 0x07); + if ( + srIdx < 13 && + adtsLen >= 7 && + bytes.byteLength >= adtsLen + 7 && + bytes[adtsLen] === 0xff && + (bytes[adtsLen + 1] & 0xf6) === (bytes[1] & 0xf6) && + (bytes[adtsLen + 2] & 0xfc) === (bytes[2] & 0xfc) + ) { + return true; + } + } + return false; +} + /** Returns true when `bytes` already begin with a known audio, image, or video container header. */ function hasKnownMediaContainer(bytes: Uint8Array): boolean { - if (hasAsciiAt(bytes, "RIFF") && (hasAsciiAt(bytes, "WAVE", 8) || hasAsciiAt(bytes, "WEBP", 8) || hasAsciiAt(bytes, "AVI ", 8))) { + if ( + hasAsciiAt(bytes, "RIFF") && + (hasAsciiAt(bytes, "WAVE", 8) || hasAsciiAt(bytes, "WEBP", 8) || hasAsciiAt(bytes, "AVI ", 8)) + ) { return true; } if (hasAsciiAt(bytes, "fLaC") || hasAsciiAt(bytes, "OggS") || hasAsciiAt(bytes, "ID3")) { @@ -58,21 +139,27 @@ function hasKnownMediaContainer(bytes: Uint8Array): boolean { ) { return true; } - if (bytes.byteLength >= 2 && bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0) { - return true; - } - return false; + return hasFramedMpegOrAdtsAudio(bytes); } -/** Returns true when leading non-whitespace bytes match HTML, XML, playlist, or XSSI text. */ +/** Returns true when leading non-whitespace bytes match JSON, HTML, XML, playlist, or XSSI text. */ function looksLikeMarkupPayload(bytes: Uint8Array): boolean { - let start = 0; + let start = + bytes.byteLength >= 3 && + bytes[0] === 0xef && + bytes[1] === 0xbb && + bytes[2] === 0xbf + ? 3 + : 0; while ( start < bytes.byteLength && (bytes[start] === 0x20 || bytes[start] === 0x09 || bytes[start] === 0x0a || bytes[start] === 0x0d) ) { start += 1; } + if (start < bytes.byteLength && (bytes[start] === 0x7b || bytes[start] === 0x5b)) { + return true; + } const head = Array.from(bytes.subarray(start, Math.min(bytes.byteLength, start + 16))) .map((b) => String.fromCharCode(b)) .join("") @@ -81,6 +168,7 @@ function looksLikeMarkupPayload(bytes: Uint8Array): boolean { head.startsWith(" 0 - ? media.width - : typeof media.tc?.width === "number" && media.tc.width > 0 - ? media.tc.width - : typeof media.xc?.width === "number" && media.xc.width > 0 - ? media.xc.width - : null; - const height = - typeof media.height === "number" && media.height > 0 - ? media.height - : typeof media.tc?.height === "number" && media.tc.height > 0 - ? media.tc.height - : typeof media.xc?.height === "number" && media.xc.height > 0 - ? media.xc.height - : null; - return { width, height }; + if (!media || typeof media !== "object") return { width: null, height: null }; + const mappedKey = snapshotFormat()?.media.dimensions; + const mapped = mappedKey + ? (readOwn(media, mappedKey) as { width?: unknown; height?: unknown } | undefined) + : undefined; + for (const cand of [media, mapped, media.tc, media.xc]) { + if (!cand || typeof cand !== "object") continue; + const w = readOwn(cand, "width"); + const h = readOwn(cand, "height"); + if (typeof w === "number" && w > 0 && typeof h === "number" && h > 0) { + return { width: w, height: h }; + } + } + return { width: null, height: null }; +} + +/** Reads pixel dimensions from a normalized media payload on verified builds or explicit fields. */ +function payloadDimensions( + rawMedia: FlowMediaPayload | null | undefined, +): { width: number | null; height: number | null } { + const explicit = explicitDimensions(rawMedia); + if (explicit.width !== null && explicit.height !== null) { + return explicit; + } + if (!rawMedia || !snapshotFormat()?.media.resolutions) { + return { width: null, height: null }; + } + const normalized = legacyMedia(rawMedia); + const w = normalized?.tc?.width; + const h = normalized?.tc?.height; + return typeof w === "number" && w > 0 && typeof h === "number" && h > 0 + ? { width: w, height: h } + : { width: null, height: null }; } /** Reads the duration in seconds from a normalized media payload. */ function payloadDuration(media: FlowMediaPayload | null | undefined): number | null { if (!media) return null; - if (typeof media.durationSeconds === "number") return media.durationSeconds; - if (typeof media.duration === "number") return media.duration; - if (typeof media.Lf === "number") return media.Lf; - if (typeof media.xf === "number") return media.xf; + const normalized = legacyMedia(media); + if (typeof normalized.durationSeconds === "number") return normalized.durationSeconds; + if (typeof normalized.duration === "number") return normalized.duration; + if (typeof normalized.Lf === "number") return normalized.Lf; + if (typeof normalized.xf === "number") return normalized.xf; return null; } -/** Returns a resolution priority rank (`3` = 4K, `2` = 1080p, `1` = base or lower). */ -export function variantResolutionRank(variant: FlowMediaPayload | null | undefined): number { - if (!variant || typeof variant !== "object") return 0; - const normalized = legacyMedia(variant); - const rawRes = readOwn(variant, "resolution") ?? normalized.resolution; - if (rawRes === 3) return 3; - if (rawRes === 2) return 2; - if (typeof rawRes === "string") { - const lower = rawRes.trim().toLowerCase(); - if (lower === "4k" || lower === "2160p") return 3; - if (lower === "1080p") return 2; +/** Parses an explicit string resolution label into a canonical quality label. */ +function parseQualityLabel(raw: unknown): VideoQualityLabel | null { + if (typeof raw !== "string") return null; + const lower = raw.trim().toLowerCase(); + if (lower === "4k" || lower === "2160p") return "4k"; + if (lower === "1080p") return "1080p"; + if (lower === "720p") return "720p"; + if (lower === "360p") return "360p"; + return null; +} + +/** Classifies the video quality of `variant` using verified build codes, string labels, or pixel dimensions. */ +export function classifyVideoQuality( + variant: FlowMediaPayload | null | undefined, +): VideoQualityLabel | null { + if (!variant || typeof variant !== "object") return null; + const rawRes = readOwn(variant, "resolution") ?? variant.resolution; + const stringLabel = parseQualityLabel(rawRes); + if (stringLabel) return stringLabel; + + if (typeof rawRes === "number") { + const mediaFmt = snapshotFormat()?.media; + const codes = mediaFmt?.resolutions; + if (codes) { + if (rawRes === codes.p4k) return "4k"; + if (rawRes === codes.p1080) return "1080p"; + if (rawRes === codes.p720) return "720p"; + if (rawRes === codes.p360) return "360p"; + if (mediaFmt?.resolutionLabelFn) { + const ns = readOwn(window, "default_AiSandboxAngularFrontend"); + const labelFn = readOwn(ns, mediaFmt.resolutionLabelFn); + if (typeof labelFn === "function") { + try { + const mapped = parseQualityLabel( + (labelFn as (code: number) => unknown).call(ns, rawRes), + ); + if (mapped && mapped !== "720p") return mapped; + } catch { + // Fall through to pixel dimension check. + } + } + } + } } - const { width, height } = payloadDimensions(normalized); + + const { width, height } = explicitDimensions(variant); if (width !== null && height !== null) { const shortEdge = Math.min(width, height); - if (shortEdge > 1200) return 3; - if (shortEdge > 800) return 2; + if (shortEdge >= 1800) return "4k"; + if (shortEdge >= 960) return "1080p"; + if (shortEdge >= 540) return "720p"; + if (shortEdge > 0) return "360p"; } - return 1; + return null; } /** Reads the first non-expired video or media URL from `source`. */ @@ -119,8 +174,10 @@ function nonExpiredVariantUrl(source: unknown): string | null { return null; } -/** Selects the highest ready variant in `tile.yn` (`4K`, then `1080p`, then base). */ -export function selectBestVideoVariant(tile: FlowTile | null | undefined): SelectedVideoVariant { +/** Reads the tile's own primary video media without overriding it with `tile.yn` upscales. */ +export function selectPrimaryVideoMedia( + tile: FlowTile | null | undefined, +): PrimaryVideoMedia { const t = legacyTile(tile); if (!t) { return { @@ -130,45 +187,25 @@ export function selectBestVideoVariant(tile: FlowTile | null | undefined): Selec width: null, height: null, duration: null, - fromUpscale: false, - }; - } - - const upsampled = Array.isArray(t.yn) ? t.yn : []; - let chosenUpscale: FlowMediaPayload | null = null; - let chosenRank = 1; - for (const item of upsampled) { - if (!isReadyMediaVariant(item)) continue; - const rank = variantResolutionRank(item); - if (rank >= 2 && rank >= chosenRank) { - chosenUpscale = legacyMedia(item); - chosenRank = rank; - } - } - - if (chosenUpscale) { - const variantId = - cleanVariantMediaId(readOwn(chosenUpscale, "id")) ?? - cleanVariantMediaId(chosenUpscale.mediaId); - const { width, height } = payloadDimensions(chosenUpscale); - return { - media: chosenUpscale, - primaryMediaId: variantId, - url: nonExpiredVariantUrl(chosenUpscale), - width, - height, - duration: payloadDuration(chosenUpscale), - fromUpscale: true, }; } - - const baseMedia = t.Fb ?? t.fb ?? null; + const rawContainer = + (snapshotFormat()?.media.container + ? (readOwn(tile, snapshotFormat()!.media.container) as FlowMediaPayload | undefined) + : undefined) ?? + tile?.Kb ?? + tile?.Eb ?? + t.Fb ?? + t.fb ?? + null; + const baseMedia = t.Fb ?? t.fb ?? legacyMedia(rawContainer); const baseId = cleanVariantMediaId(t.primaryMediaId) ?? + cleanVariantMediaId(rawContainer?.id) ?? cleanVariantMediaId(baseMedia?.id) ?? cleanVariantMediaId(baseMedia?.mediaId) ?? cleanVariantMediaId(t.mediaId); - const baseDims = payloadDimensions(baseMedia); + const baseDims = payloadDimensions(rawContainer ?? baseMedia); const width = baseDims.width ?? (typeof t.width === "number" && t.width > 0 @@ -184,7 +221,7 @@ export function selectBestVideoVariant(tile: FlowTile | null | undefined): Selec ? t.tc.height : null); const duration = - payloadDuration(baseMedia) ?? + payloadDuration(rawContainer ?? baseMedia) ?? (typeof t.durationSeconds === "number" ? t.durationSeconds : typeof t.duration === "number" @@ -193,6 +230,7 @@ export function selectBestVideoVariant(tile: FlowTile | null | undefined): Selec ? t.Lf : null); const baseUrl = + nonExpiredVariantUrl(rawContainer) ?? nonExpiredVariantUrl(t.Fb) ?? nonExpiredVariantUrl(t) ?? nonExpiredVariantUrl(t.fb); @@ -204,10 +242,74 @@ export function selectBestVideoVariant(tile: FlowTile | null | undefined): Selec width, height, duration, - fromUpscale: false, }; } +/** Collects ready base and `tile.yn` video resolution variants for explicit quality selection. */ +export function collectReadyVideoVariants( + tile: FlowTile | null | undefined, + normalizeUrl?: (url: string) => string, +): VideoVariantEntry[] { + if (!tile || typeof tile !== "object") return []; + const t = legacyTile(tile); + const byMediaId = new Map(); + const recordVariant = ( + rawItem: FlowMediaPayload | null | undefined, + fallbackId: string | null, + fallbackSource?: unknown, + ): void => { + if (!rawItem || !isReadyMediaVariant(rawItem)) return; + const mediaId = + cleanVariantMediaId(readOwn(rawItem, "id")) ?? + cleanVariantMediaId(rawItem.mediaId) ?? + fallbackId; + if (!mediaId) return; + const quality = classifyVideoQuality(rawItem); + const rawUrl = + nonExpiredVariantUrl(rawItem) ?? + (fallbackSource ? nonExpiredVariantUrl(fallbackSource) : null); + const url = rawUrl ? (normalizeUrl ? normalizeUrl(rawUrl) : rawUrl) : null; + const { width, height } = payloadDimensions(rawItem); + const duration = payloadDuration(rawItem); + const prev = byMediaId.get(mediaId); + if (prev) { + prev.quality ??= quality; + prev.url ??= url; + prev.width ??= width; + prev.height ??= height; + prev.duration ??= duration; + return; + } + byMediaId.set(mediaId, { + media_id: mediaId, + quality, + url, + width, + height, + duration, + }); + }; + + const containerKey = snapshotFormat()?.media.container; + const rawBase = + (containerKey + ? (readOwn(tile, containerKey) as FlowMediaPayload | undefined) + : undefined) ?? + tile.Kb ?? + tile.Eb ?? + t?.Fb ?? + t?.fb ?? + null; + recordVariant(rawBase, cleanVariantMediaId(tile.primaryMediaId), t); + + if (Array.isArray(tile.yn)) { + for (const item of tile.yn) { + recordVariant(item, null); + } + } + return Array.from(byMediaId.values()); +} + /** Collects all unique primary, history, and `tile.yn` media IDs from `tile`. */ export function collectTileMediaIds( tile: FlowTile | null | undefined, diff --git a/ts/project_store.ts b/ts/project_store.ts index 2875d9b..3530bca 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -4,12 +4,12 @@ // Bind, validate, read, and mutate the active project store from verified build formats. import { isNgLViewMap, readOwn } from "./angular"; +import { readCustomVoicesFromQueryData } from "./custom_voices"; import { delay } from "./dom"; import { activeProjectStoreFormat, readBuildLabel, withMutationAliases } from "./frontend_builds"; import type { ProjectStoreFormat } from "./frontend_builds"; import { clearStore, runtimeState } from "./state"; import type { - CustomVoiceItem, FlowStoreHandle, FlowTile, NgLView, @@ -163,288 +163,6 @@ function readStoreQueryData(store: ProjectStore): unknown { return typeof readData === "function" ? readData.call(signalQuery) : readData; } -/** Reads a 1-based field from a dense or sparse serialized JSPB array. */ -function voiceProtoField(msg: unknown, field: number): unknown { - if (!Array.isArray(msg) || field < 1) return undefined; - const tail: unknown = msg[msg.length - 1]; - if (tail && typeof tail === "object" && !Array.isArray(tail)) { - const mapped = readOwn(tail, String(field)); - if (mapped !== undefined) return mapped; - } - return msg[field - 1]; -} - -/** Iterates values from a `Map`, array, or plain record. */ -function mapValues(source: unknown): unknown[] { - if (source instanceof Map) return Array.from(source.values()); - if (Array.isArray(source)) return source; - if (source && typeof source === "object") return Object.values(source); - return []; -} - -/** Builds a workflow and tile display-name lookup map from `lr` and `yb`. */ -function buildVoiceNameMap(data: unknown, rowsField: string): Map { - const names = new Map(); - const register = (key: unknown, title: unknown): void => { - if (typeof key !== "string" || typeof title !== "string") return; - const cleanKey = key.trim(); - const cleanTitle = title.trim(); - if (!cleanKey || !cleanTitle) return; - names.set(cleanKey, cleanTitle); - names.set(cleanKey.replace(/^(?:media|workflows)\//i, ""), cleanTitle); - }; - - const rows = readOwn(data, rowsField); - if (Array.isArray(rows)) { - for (const row of rows) { - const displayName = readOwn(row, "displayName"); - register(readOwn(row, "id"), displayName); - register(readOwn(row, "workflowId"), displayName); - register(readOwn(row, "primaryMediaId"), displayName); - } - } - - const lr = readOwn(data, "lr"); - const lrEntries: Array<[unknown, unknown]> = - lr instanceof Map - ? Array.from(lr.entries()) - : lr && typeof lr === "object" && !Array.isArray(lr) - ? Object.entries(lr) - : []; - for (const [wfKey, wfVal] of lrEntries) { - let wfId: unknown = wfKey; - let wfTitle: unknown = readOwn(wfVal, "displayName") ?? readOwn(wfVal, "name"); - const getNameFn = readOwn(wfVal, "getName"); - if (typeof getNameFn === "function") { - try { - wfId = getNameFn.call(wfVal) ?? wfId; - } catch { - // Keep map key fallback. - } - } - const getMetaFn = readOwn(wfVal, "getMetadata"); - if (!wfTitle && typeof getMetaFn === "function") { - try { - const meta: unknown = getMetaFn.call(wfVal); - const qdFn = readOwn(meta, "Qd"); - if (typeof qdFn === "function") { - wfTitle = qdFn.call(meta); - } - } catch { - // Fall through to serialized JSON check. - } - } - const toJsonFn = readOwn(wfVal, "toJSON"); - if (!wfTitle && typeof toJsonFn === "function") { - try { - const rawWf: unknown = toJsonFn.call(wfVal); - wfId = voiceProtoField(rawWf, 1) ?? wfId; - const rawMeta = voiceProtoField(rawWf, 4) ?? voiceProtoField(rawWf, 3); - wfTitle = voiceProtoField(rawMeta, 1); - } catch { - // Ignore malformed workflow entry. - } - } - register(wfId, wfTitle); - } - return names; -} - -/** Extracts saved custom voices from `cj` and `lr` on `store` without changing `getTileMap()`. */ -function readCustomVoices(store: ProjectStore): CustomVoiceItem[] { - const data = readStoreQueryData(store); - if (!data || typeof data !== "object") return []; - const cj = readOwn(data, "cj"); - const candidates = mapValues(cj); - if (candidates.length === 0) return []; - - const nameMap = buildVoiceNameMap(data, store.format.rows); - const frontEnd = readOwn(window, "default_AiSandboxAngularFrontend"); - const hUbFn = readOwn(frontEnd, "hUb"); - const fvFn = readOwn(frontEnd, "fv"); - const brOneof = readOwn(frontEnd, "Br"); - - const out: CustomVoiceItem[] = []; - const seen = new Set(); - const lookupTitle = (wfId: string | null, mediaId: string): string | null => { - if (wfId) { - const hit = nameMap.get(wfId) ?? nameMap.get(wfId.replace(/^workflows\//i, "")); - if (hit) return hit; - } - return nameMap.get(mediaId) ?? nameMap.get(mediaId.replace(/^media\//i, "")) ?? null; - }; - - for (const item of candidates) { - if (!item || typeof item !== "object") continue; - - if ( - typeof hUbFn === "function" && - typeof fvFn === "function" && - Array.isArray(brOneof) - ) { - try { - const isAudio = Boolean( - (fvFn as (msg: unknown, field: number, oneof: unknown[]) => unknown).call( - frontEnd, - item, - 11, - brOneof, - ), - ); - if (!isAudio) continue; - const mapped = ( - hUbFn as (msg: unknown, names: Map) => Record | undefined - ).call(frontEnd, item, nameMap); - if (!mapped || mapped.Rv === true || mapped.Db === true) continue; - const rawId = String(mapped.id ?? mapped.workflowId ?? mapped.mediaId ?? "").trim(); - if (!rawId || /^voices\//i.test(rawId)) continue; - const mediaId = String(mapped.mediaId ?? rawId) - .trim() - .replace(/^(?:media|workflows)\//i, ""); - if (!mediaId || seen.has(mediaId)) continue; - seen.add(mediaId); - const wfId = - typeof mapped.workflowId === "string" && mapped.workflowId.trim() - ? mapped.workflowId.trim() - : null; - const assetId = rawId.replace(/^(?:media|workflows)\//i, "") || mediaId; - const prompt = - typeof mapped.description === "string" && mapped.description.trim() - ? mapped.description.trim() - : typeof mapped.f7 === "string" && mapped.f7.trim() - ? mapped.f7.trim() - : null; - const rawUrl = typeof mapped.NU === "string" ? mapped.NU.trim() : ""; - const created = - mapped.rm instanceof Date && mapped.rm.getTime() > 0 - ? mapped.rm.toISOString() - : null; - out.push({ - id: assetId, - name: - (typeof mapped.title === "string" && mapped.title.trim()) || - lookupTitle(wfId, mediaId) || - "Custom voice", - mediaId, - workflowId: wfId, - prompt, - url: /^https?:\/\//i.test(rawUrl) ? rawUrl : null, - createdAt: created, - }); - continue; - } catch { - // Fall through to structural JSPB and plain-object inspection. - } - } - - const toJsonFn = readOwn(item, "toJSON"); - const serialized: unknown = - typeof toJsonFn === "function" - ? (() => { - try { - return toJsonFn.call(item); - } catch { - return null; - } - })() - : Array.isArray(item) - ? item - : null; - - if (Array.isArray(serialized)) { - const audioBranch = voiceProtoField(serialized, 11); - if (!audioBranch || typeof audioBranch !== "object") continue; - const audioInner = Array.isArray(audioBranch) - ? (voiceProtoField(audioBranch, 1) ?? audioBranch) - : (readOwn(audioBranch, "1") ?? audioBranch); - if (voiceProtoField(audioInner, 3) === true) continue; - const rawName = voiceProtoField(serialized, 1); - if (typeof rawName !== "string" || !rawName.trim() || /^voices\//i.test(rawName.trim())) { - continue; - } - const mediaId = rawName.trim().replace(/^media\//i, ""); - if (!mediaId || seen.has(mediaId)) continue; - const meta = - voiceProtoField(serialized, 4) ?? - voiceProtoField(serialized, 5) ?? - voiceProtoField(serialized, 6); - if (voiceProtoField(meta, 4) === true) continue; - seen.add(mediaId); - const wfRaw = voiceProtoField(serialized, 3); - const wfId = typeof wfRaw === "string" && wfRaw.trim() ? wfRaw.trim() : null; - const metaTitle = voiceProtoField(meta, 2); - const audioName = voiceProtoField(audioInner, 1); - const title = - (typeof metaTitle === "string" && metaTitle.trim()) || - (typeof audioName === "string" && audioName.trim()) || - lookupTitle(wfId, mediaId) || - "Custom voice"; - const desc = - voiceProtoField(audioInner, 8) ?? - voiceProtoField(audioInner, 2) ?? - voiceProtoField(audioInner, 5); - const urlCand = voiceProtoField(audioInner, 4) ?? voiceProtoField(audioInner, 6); - out.push({ - id: mediaId, - name: title, - mediaId, - workflowId: wfId, - prompt: typeof desc === "string" && desc.trim() ? desc.trim() : null, - url: - typeof urlCand === "string" && /^https?:\/\//i.test(urlCand.trim()) - ? urlCand.trim() - : null, - createdAt: null, - }); - continue; - } - - if (readOwn(item, "Rv") === true || readOwn(item, "Db") === true || readOwn(item, "trashed") === true) { - continue; - } - const kindHint = String(readOwn(item, "type") ?? readOwn(item, "kind") ?? "").toUpperCase(); - const hasAudioField = - kindHint === "VOICE" || - kindHint === "AUDIO" || - readOwn(item, "audio") != null || - typeof readOwn(item, "NU") === "string"; - if (!hasAudioField) continue; - const rawId = String(readOwn(item, "mediaId") ?? readOwn(item, "id") ?? "").trim(); - if (!rawId || /^voices\//i.test(rawId)) continue; - const mediaId = rawId.replace(/^media\//i, ""); - if (!mediaId || seen.has(mediaId)) continue; - seen.add(mediaId); - const wfRaw = readOwn(item, "workflowId"); - const wfId = typeof wfRaw === "string" && wfRaw.trim() ? wfRaw.trim() : null; - const rawTitle = readOwn(item, "title") ?? readOwn(item, "displayName") ?? readOwn(item, "name"); - const rawPrompt = readOwn(item, "description") ?? readOwn(item, "prompt") ?? readOwn(item, "f7"); - const rawUrl = readOwn(item, "NU") ?? readOwn(item, "url"); - const rawCreated = readOwn(item, "rm") ?? readOwn(item, "createdAt") ?? readOwn(item, "createTime"); - out.push({ - id: mediaId, - name: - (typeof rawTitle === "string" && rawTitle.trim()) || - lookupTitle(wfId, mediaId) || - "Custom voice", - mediaId, - workflowId: wfId, - prompt: typeof rawPrompt === "string" && rawPrompt.trim() ? rawPrompt.trim() : null, - url: - typeof rawUrl === "string" && /^https?:\/\//i.test(rawUrl.trim()) - ? rawUrl.trim() - : null, - createdAt: - rawCreated instanceof Date - ? rawCreated.toISOString() - : typeof rawCreated === "string" && rawCreated.trim() - ? rawCreated.trim() - : null, - }); - } - - return out; -} - /** Reads the cached rows for the active project when the query settles. */ export function readProjectStore(store: ProjectStore): Map | null { if (!isCurrent(store) || isProjectStorePending(store)) return null; @@ -595,7 +313,8 @@ export function installProjectStore(store: ProjectStore, views?: Map isCurrent(store), getTileMap: () => readProjectStore(store), - getCustomVoices: () => readCustomVoices(store), + getCustomVoices: () => + readCustomVoicesFromQueryData(readStoreQueryData(store), store.format.rows), isReady: () => isCurrent(store) && !isProjectStorePending(store), mutate: (payload) => mutateStore(store, payload), rename: (id, displayName) => diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 2187077..ccf7fb6 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -5,14 +5,19 @@ import { readOwn } from "./angular"; import { characterPersonalityNotes, characterVoice } from "./character_bio"; +import { + appendCustomVoiceAssets, + resolveLooklessCharacterVoice, +} from "./custom_voices"; import { activeProjectStoreFormat, snapshotFormat } from "./frontend_builds"; import { cleanVariantMediaId, + collectReadyVideoVariants, collectTileMediaIds, - selectBestVideoVariant, + selectPrimaryVideoMedia, } from "./media_variants"; import { currentProjectStore, projectInRoute } from "./project_store"; -import { isSceneClipTrimmed, sceneContents } from "./scene_tiles"; +import { inspectSceneTileSnapshot, sceneContents } from "./scene_tiles"; import { asHttpOrDataUrl, characterLookMedia, @@ -248,9 +253,10 @@ export function readStoreTiles( const cols = new Map(); const counts = new Map(); const byId = new Map>(); - const sceneTiles: Array<[FlowTile, ReturnType]> = []; + const sceneTiles: FlowTile[] = []; const rawList: Omit[] = []; const env = getFifeEnv(); + const normalizeVideo = (u: string): string => normalizeFlowMediaUrl(u, "video", env); const collectionType = snapshotFormat()?.tileTypes.collection ?? "COLLECTION"; const nonExpiredUrl = (raw: unknown): string | null => { const direct = asHttpOrDataUrl(raw); @@ -324,115 +330,39 @@ export function readStoreTiles( : ttype === "CHARACTER" ? "character" : "image"; - let scenePrimaryMediaId: string | null = null; - let sceneRequiresExport = false; - let sceneSingleUrl: string | null = null; - let sceneWidth: number | null = null; - let sceneHeight: number | null = null; - let sceneDuration: number | null = null; - if (baseKind === "scene") { - const parsedScene = sceneContents(t); - sceneTiles.push([t, parsedScene]); - const { clips, history } = parsedScene; - if (clips.length === 1) { - const c0 = clips[0]; - const wfId = c0?.workflowId ? String(c0.workflowId) : null; - const hist = wfId ? history.get(wfId) : undefined; - const clipMid = cleanVariantMediaId(c0?.primaryMediaId); - const rawClipMedia = Array.isArray(hist) - ? hist.find((x) => x && cleanVariantMediaId(x.id) === clipMid) || hist[0] || null - : null; - const m0 = legacyMedia(rawClipMedia); - if (isSceneClipTrimmed(c0, m0)) { - sceneRequiresExport = true; - } else { - const wfTile = wfId ? tileMap.get(wfId) : undefined; - const wfVariant = wfTile ? selectBestVideoVariant(wfTile) : null; - scenePrimaryMediaId = - clipMid ?? - cleanVariantMediaId(m0?.id) ?? - wfVariant?.primaryMediaId ?? - null; - const m0Status = String(m0?.Zc ?? c0?.Zc ?? "").toLowerCase(); - const m0NotReady = - m0Status === "pending" || - m0Status === "scheduled" || - m0Status === "failed" || - m0Status === "canceled" || - Boolean(m0?.nf || c0?.nf); - if (!m0NotReady) { - sceneSingleUrl = - nonExpiredUrl(readMediaUrl(m0, true)) || - nonExpiredUrl(readMediaUrl(c0, true)) || - nonExpiredUrl(readMediaUrl(m0)) || - nonExpiredUrl(readMediaUrl(c0)) || - (wfVariant && wfVariant.primaryMediaId === scenePrimaryMediaId - ? wfVariant.url - : null); - } - sceneWidth = - typeof m0?.width === "number" - ? m0.width - : typeof m0?.tc?.width === "number" - ? m0.tc.width - : wfVariant?.width ?? null; - sceneHeight = - typeof m0?.height === "number" - ? m0.height - : typeof m0?.tc?.height === "number" - ? m0.tc.height - : wfVariant?.height ?? null; - sceneDuration = - typeof c0?.nc === "number" - ? c0.nc - : typeof c0?.rc === "number" - ? c0.rc - : typeof m0?.Lf === "number" - ? m0.Lf - : wfVariant?.duration ?? null; - } - } else if (clips.length > 1) { - sceneRequiresExport = true; - } - } + const sceneInfo = + baseKind === "scene" + ? (sceneTiles.push(t), inspectSceneTileSnapshot(t, tileMap, normalizeVideo)) + : null; - const charMedia = + const charLook = baseKind === "character" ? characterLookMedia(t) : { url: null, primaryMediaId: null }; - const rawCharVoiceRef = charMedia.isVoice ? charMedia.primaryMediaId : null; - const cleanCharVoiceRef = rawCharVoiceRef - ? rawCharVoiceRef.replace(/^(?:media|workflows)\//i, "") - : null; - const matchedCharVoice = cleanCharVoiceRef - ? customVoices.find( - (v) => - v.id === rawCharVoiceRef || - v.id === cleanCharVoiceRef || - v.mediaId === cleanCharVoiceRef || - (v.workflowId !== null && - (v.workflowId === rawCharVoiceRef || - v.workflowId.replace(/^workflows\//i, "") === cleanCharVoiceRef)), - ) - : undefined; - const charFallbackUrl = - nonExpiredUrl(charMedia.url) ?? nonExpiredUrl(matchedCharVoice?.url); - const charLookPrimaryMediaId = matchedCharVoice - ? matchedCharVoice.mediaId - : charMedia.primaryMediaId; - - const videoVariant = baseKind === "video" ? selectBestVideoVariant(t) : null; + const charResolved = + baseKind === "character" + ? resolveLooklessCharacterVoice( + t, + charLook.url, + charLook.primaryMediaId, + customVoices, + ) + : { url: null, primaryMediaId: null, isVoice: false, pcmAudio: false }; + + const primaryVideo = baseKind === "video" ? selectPrimaryVideoMedia(t) : null; + const videoVariants = + baseKind === "video" + ? collectReadyVideoVariants(t, normalizeVideo) + : sceneInfo?.variants ?? []; const videoMediaUrl = baseKind === "video" - ? videoVariant?.fromUpscale - ? videoVariant.url - : videoVariant?.url || - nonExpiredUrl(readMediaUrl(t.Fb, true)) || - nonExpiredUrl(readMediaUrl(t, true)) || - nonExpiredUrl(readMediaUrl(t.fb, true)) + ? primaryVideo?.url || + nonExpiredUrl(readMediaUrl(t.Fb, true)) || + nonExpiredUrl(readMediaUrl(t, true)) || + nonExpiredUrl(readMediaUrl(t.fb, true)) : null; - const activeMedia = videoVariant?.fromUpscale ? videoVariant.media : (t.Fb ?? t.fb ?? t); + const activeMedia = baseKind === "video" ? (primaryVideo?.media ?? t.Fb ?? t.fb ?? t) : (t.Fb ?? t.fb ?? t); const mediaStatus = String( activeMedia?.Zc ?? t.Fb?.Zc ?? t.fb?.Zc ?? t.Zc ?? "", ).toLowerCase(); @@ -448,10 +378,10 @@ export function readStoreTiles( const primaryMediaId = baseKind === "scene" - ? scenePrimaryMediaId + ? (sceneInfo?.primaryMediaId ?? null) : baseKind === "video" - ? videoVariant?.primaryMediaId ?? null - : charLookPrimaryMediaId || + ? (primaryVideo?.primaryMediaId ?? null) + : charResolved.primaryMediaId || cleanVariantMediaId(t.primaryMediaId) || cleanVariantMediaId(t.Fb?.id) || cleanVariantMediaId(t.Fb?.mediaId) || @@ -470,24 +400,22 @@ export function readStoreTiles( const tileMediaUrl = baseKind === "scene" - ? sceneSingleUrl - : baseKind === "video" && videoVariant?.fromUpscale - ? videoMediaUrl - : baseKind === "character" && charLookPrimaryMediaId - ? charFallbackUrl - : videoMediaUrl || - nonExpiredUrl(readMediaUrl(t.Fb)) || - nonExpiredUrl(readMediaUrl(t)) || - nonExpiredUrl(readMediaUrl(t.fb)) || - charFallbackUrl || - null; + ? (sceneInfo?.singleUrl ?? null) + : baseKind === "character" && charResolved.primaryMediaId + ? charResolved.url + : videoMediaUrl || + nonExpiredUrl(readMediaUrl(t.Fb)) || + nonExpiredUrl(readMediaUrl(t)) || + nonExpiredUrl(readMediaUrl(t.fb)) || + charResolved.url || + null; const rawMediaUrl = isSignedUrlStr(tileMediaUrl) ? tileMediaUrl : isSignedUrlStr(cachedMediaUrl) ? cachedMediaUrl : tileMediaUrl || cachedMediaUrl || null; const mediaUrl = - mediaNotReady || (baseKind === "scene" && sceneRequiresExport) + mediaNotReady || (baseKind === "scene" && Boolean(sceneInfo?.requiresSceneExport)) ? null : rawMediaUrl; @@ -519,7 +447,7 @@ export function readStoreTiles( primaryMediaId ? String(primaryMediaId) : null, ); const underlyingMediaKind = - charMedia.isVoice === true ? "audio" : (cachedEntry?.media_kind ?? null); + charResolved.isVoice ? "audio" : (cachedEntry?.media_kind ?? null); const topEntry: Omit = { id: tid, @@ -543,9 +471,9 @@ export function readStoreTiles( media_error: mediaError, width: baseKind === "video" - ? (videoVariant?.width ?? null) + ? (primaryVideo?.width ?? null) : baseKind === "scene" - ? sceneWidth + ? (sceneInfo?.width ?? null) : typeof t.width === "number" ? t.width : typeof t.Fb?.width === "number" @@ -557,9 +485,9 @@ export function readStoreTiles( : null, height: baseKind === "video" - ? (videoVariant?.height ?? null) + ? (primaryVideo?.height ?? null) : baseKind === "scene" - ? sceneHeight + ? (sceneInfo?.height ?? null) : typeof t.height === "number" ? t.height : typeof t.Fb?.height === "number" @@ -571,9 +499,9 @@ export function readStoreTiles( : null, duration: baseKind === "video" - ? (videoVariant?.duration ?? null) + ? (primaryVideo?.duration ?? null) : baseKind === "scene" - ? sceneDuration + ? (sceneInfo?.duration ?? null) : typeof t.durationSeconds === "number" ? t.durationSeconds : typeof t.duration === "number" @@ -596,17 +524,23 @@ export function readStoreTiles( ? String(t.createTime) : null, media_ids: tileMediaIds, - ...(baseKind === "scene" ? { requires_scene_export: sceneRequiresExport } : {}), - ...(cachedEntry?.pcm_audio || Boolean(matchedCharVoice) ? { pcm_audio: true } : {}), + ...(videoVariants.length > 0 ? { variants: videoVariants } : {}), + ...(sceneInfo + ? { + requires_scene_export: sceneInfo.requiresSceneExport, + ...(sceneInfo.sceneClips.length > 0 ? { scene_clips: sceneInfo.sceneClips } : {}), + } + : {}), + ...(cachedEntry?.pcm_audio || charResolved.pcmAudio ? { pcm_audio: true } : {}), ...(underlyingMediaKind ? { media_kind: underlyingMediaKind } : {}), }; rawList.push(topEntry); byId.set(tid, topEntry); } - for (const [st, parsedScene] of sceneTiles) { + for (const st of sceneTiles) { const sceneCid = collectionIdOf(st, isCollectionId); - const { clips, history } = parsedScene; + const { clips, history } = sceneContents(st); const candidates: Array< [string, SceneClipItem | null, FlowMediaPayload | null] > = []; @@ -761,44 +695,7 @@ export function readStoreTiles( } } - for (const voice of customVoices) { - if (!voice.id || byId.has(voice.id)) continue; - if (voice.workflowId && byId.has(voice.workflowId)) continue; - const cachedVoice = runtimeState.mediaInfoCache.get(voice.mediaId); - const directVoiceUrl = nonExpiredUrl(voice.url); - const cachedVoiceUrl = nonExpiredUrl(cachedVoice?.url); - const rawVoiceUrl = isSignedUrlStr(directVoiceUrl) - ? directVoiceUrl - : isSignedUrlStr(cachedVoiceUrl) - ? cachedVoiceUrl - : directVoiceUrl || cachedVoiceUrl || null; - const voiceMediaIds = voice.mediaId ? [voice.mediaId] : []; - const voiceEntry: Omit = { - id: voice.id, - name: voice.name, - kind: "audio", - prompt: voice.prompt, - url: rawVoiceUrl ? normalizeFlowMediaUrl(rawVoiceUrl, "audio", env) : null, - collection_id: null, - primary_media_id: voice.mediaId, - personality_notes: null, - voice: voice.name, - trim_start_seconds: null, - trim_end_seconds: null, - media_status: "success", - media_error: null, - width: null, - height: null, - duration: null, - created_at: voice.createdAt, - media_ids: voiceMediaIds, - workflow_id: voice.workflowId, - pcm_audio: true, - media_kind: "audio", - }; - rawList.push(voiceEntry); - byId.set(voice.id, voiceEntry); - } + appendCustomVoiceAssets(customVoices, byId, rawList, env); const assets: SnapshotAssetItem[] = rawList.map((a) => ({ ...a, diff --git a/ts/scene_export.ts b/ts/scene_export.ts index f96d603..d8a3fcd 100644 --- a/ts/scene_export.ts +++ b/ts/scene_export.ts @@ -14,11 +14,17 @@ import { runtimeState } from "./state"; import type { FlowMediaPayload, SceneClipItem, SceneExportResult } from "./types"; /** Maximum number of `IxdSwd` status polls per scene export job. */ -const MAX_SCENE_EXPORT_POLLS = 40; +const MAX_SCENE_EXPORT_POLLS = 25; /** Default poll interval in milliseconds matching Flow `vHb`. */ const DEFAULT_POLL_DELAY_MS = 3000; +/** Hard wall-clock budget in milliseconds, kept 30 seconds below the 120-second Rust CDP timeout. */ +const SCENE_EXPORT_BUDGET_MS = 90_000; + +/** Sentinel returned when an awaited step exceeds the scene export deadline. */ +const DEADLINE_EXCEEDED = Symbol("scene_export_deadline"); + /** Time in milliseconds to retain an unconsumed exported `blob:` URL. */ const EXPORT_BLOB_TTL_MS = 120_000; @@ -324,27 +330,62 @@ function buildClipMessage( return symbols.freezeMsg(withEnd); } +/** Races `work` against `deadlineMs` (`performance.now()` clock) and clears its timer on settle. */ +async function raceDeadline( + work: Promise, + deadlineMs: number, +): Promise { + const remaining = deadlineMs - performance.now(); + if (remaining <= 0) return DEADLINE_EXCEEDED; + let timer: ReturnType | undefined; + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve(DEADLINE_EXCEEDED), remaining); + }); + try { + return await Promise.race([work, timeout]); + } finally { + clearTimeout(timer); + } +} + /** Exports a multi-clip or trimmed scene through `GjQLTd` and `IxdSwd` on `KD`. */ export async function sceneExport( sceneId: string, pollDelayMs?: number, + timeoutMs?: number, ): Promise { + const trimmedId = String(sceneId || "").trim(); + if (!trimmedId) { + return { ok: false, error: "missing_scene_id" }; + } + if (trimmedId.includes(":")) { + return { ok: false, error: "scene_clip_id_not_scene" }; + } + + const budgetMs = + typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 + ? Math.min(SCENE_EXPORT_BUDGET_MS, Math.max(1000, timeoutMs)) + : SCENE_EXPORT_BUDGET_MS; + const deadlineMs = performance.now() + budgetMs; + const format = sceneExportFormat(readBuildLabel()); if (!format) { return { ok: false, error: "unsupported_front_end" }; } - const symbols = await bindSceneExportSymbols(format); + const symbolsRes = await raceDeadline(bindSceneExportSymbols(format), deadlineMs); + if (symbolsRes === DEADLINE_EXCEEDED) { + return { ok: false, error: "scene_export_timeout" }; + } + const symbols = symbolsRes; if (!symbols) { return { ok: false, error: "unsupported_front_end" }; } - const trimmedId = String(sceneId || "").trim(); - if (!trimmedId) { - return { ok: false, error: "missing_scene_id" }; - } - if (!runtimeState.store || !runtimeState.store.isCurrent() || !runtimeState.store.isReady()) { - await discoverStore(); + const boundRes = await raceDeadline(discoverStore(), deadlineMs); + if (boundRes === DEADLINE_EXCEEDED) { + return { ok: false, error: "scene_export_timeout" }; + } } const tileMap = runtimeState.store?.getTileMap?.(); if (!(tileMap instanceof Map)) { @@ -383,7 +424,10 @@ export async function sceneExport( let dataClient = locateDataClient(format, symbols); if (!dataClient) { - await discoverStore(); + const retryStore = await raceDeadline(discoverStore(), deadlineMs); + if (retryStore === DEADLINE_EXCEEDED) { + return { ok: false, error: "scene_export_timeout" }; + } dataClient = locateDataClient(format, symbols); } if (!dataClient) { @@ -422,7 +466,13 @@ export async function sceneExport( format.startClipsField, clipMessages, ); - const startResp = await dataClient.fetch(startDescriptor.Eb(symbols.cloneMsg(startReq))); + const startResp = await raceDeadline( + dataClient.fetch(startDescriptor.Eb(symbols.cloneMsg(startReq))), + deadlineMs, + ); + if (startResp === DEADLINE_EXCEEDED) { + return { ok: false, error: "scene_export_timeout" }; + } const operationToken = symbols.getSubmessage( startResp, OpTokenCtor, @@ -438,8 +488,15 @@ export async function sceneExport( : DEFAULT_POLL_DELAY_MS; for (let attempt = 0; attempt < MAX_SCENE_EXPORT_POLLS; attempt += 1) { + if (performance.now() >= deadlineMs) { + return { ok: false, error: "scene_export_timeout" }; + } if (waitMs > 0) { - await delay(attempt === 0 ? Math.min(1000, waitMs) : waitMs); + const stepWait = attempt === 0 ? Math.min(1000, waitMs) : waitMs; + const waited = await raceDeadline(delay(stepWait), deadlineMs); + if (waited === DEADLINE_EXCEEDED || performance.now() >= deadlineMs) { + return { ok: false, error: "scene_export_timeout" }; + } } const pollReq = symbols.setSubmessage( new symbols.PollRequest(), @@ -447,7 +504,13 @@ export async function sceneExport( format.pollOperationField, operationToken, ); - const pollResp = await dataClient.fetch(pollDescriptor.Eb(symbols.cloneMsg(pollReq))); + const pollResp = await raceDeadline( + dataClient.fetch(pollDescriptor.Eb(symbols.cloneMsg(pollReq))), + deadlineMs, + ); + if (pollResp === DEADLINE_EXCEEDED) { + return { ok: false, error: "scene_export_timeout" }; + } const statusFn = readOwn(pollResp, format.pollStatusMethod); const status = typeof statusFn === "function" ? statusFn.call(pollResp) : undefined; diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index 24bb600..a6c6ef6 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -4,8 +4,40 @@ // Read clips and workflow history from the native scene tile. import { readOwn } from "./angular"; +import { asHttpOrDataUrl, isExpiredSignedUrl, legacyMedia, readMediaUrl } from "./dom"; import { frontendBuild, readBuildLabel } from "./frontend_builds"; -import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; +import { + cleanVariantMediaId, + collectReadyVideoVariants, + selectPrimaryVideoMedia, +} from "./media_variants"; +import type { + FlowMediaPayload, + FlowTile, + SceneClipItem, + SceneClipMediaEntry, + VideoVariantEntry, +} from "./types"; + +/** Normalized scene download and clip metadata read from a `SCENE` tile. */ +export interface SceneSnapshotInspection { + /** Direct media ID for a single untrimmed clip scene, or null when export is required. */ + primaryMediaId: string | null; + /** True when the scene has multiple clips or non-destructive clip trims. */ + requiresSceneExport: boolean; + /** Non-expired direct URL for a single untrimmed clip scene when present. */ + singleUrl: string | null; + /** Rendered width in pixels for a single untrimmed clip scene when known. */ + width: number | null; + /** Rendered height in pixels for a single untrimmed clip scene when known. */ + height: number | null; + /** Duration in seconds for a single untrimmed clip scene when known. */ + duration: number | null; + /** Ready video variants on the underlying clip tile for a 1-clip untrimmed scene. */ + variants: VideoVariantEntry[]; + /** Active timeline clip workflow-to-media mappings for `:` selectors. */ + sceneClips: SceneClipMediaEntry[]; +} /** Returns the clip list and history of a scene in the active build. */ export function sceneContents(tile: FlowTile) { @@ -57,3 +89,142 @@ export function isSceneClipTrimmed( const end = Math.min(endRaw, dur); return end > start && (start > 0 || end < dur - 0.01); } + +/** Inspects a `SCENE` tile for 1-clip direct download, multi-clip export, and `:` clip mappings. */ +export function inspectSceneTileSnapshot( + tile: FlowTile, + tileMap: Map, + normalizeVideoUrl: (url: string) => string, +): SceneSnapshotInspection { + const nonExpired = (raw: unknown): string | null => { + const direct = asHttpOrDataUrl(raw); + return direct && !isExpiredSignedUrl(direct) ? direct : null; + }; + const { clips, history } = sceneContents(tile); + const seenWf = new Set(); + const sceneClips: SceneClipMediaEntry[] = []; + + for (const clip of clips) { + const wfId = clip?.workflowId != null ? String(clip.workflowId).trim() : ""; + if (!wfId || seenWf.has(wfId)) continue; + seenWf.add(wfId); + const hist = history.get(wfId); + const clipMid = cleanVariantMediaId(clip?.primaryMediaId); + const rawClipMedia = Array.isArray(hist) + ? hist.find((x) => x && cleanVariantMediaId(x.id) === clipMid) ?? hist[0] ?? null + : null; + const mObj = legacyMedia(rawClipMedia); + const wfTile = tileMap.get(wfId); + const wfPrimary = wfTile ? selectPrimaryVideoMedia(wfTile) : null; + const primaryId = + clipMid ?? + cleanVariantMediaId(mObj?.id) ?? + wfPrimary?.primaryMediaId ?? + null; + const status = String(mObj?.Zc ?? clip?.Zc ?? clip?.od ?? "").toLowerCase(); + const notReady = + status === "pending" || + status === "scheduled" || + status === "failed" || + status === "canceled" || + Boolean(mObj?.nf || clip?.nf || clip?.Bf); + const rawUrl = notReady + ? null + : nonExpired(readMediaUrl(mObj, true)) || + nonExpired(readMediaUrl(clip, true)) || + nonExpired(readMediaUrl(mObj)) || + nonExpired(readMediaUrl(clip)) || + (wfPrimary && wfPrimary.primaryMediaId === primaryId ? wfPrimary.url : null); + sceneClips.push({ + workflow_id: wfId, + primary_media_id: primaryId, + url: rawUrl ? normalizeVideoUrl(rawUrl) : null, + }); + } + + if (clips.length === 1) { + const c0 = clips[0]; + const wfId = c0?.workflowId != null ? String(c0.workflowId).trim() : ""; + const hist = wfId ? history.get(wfId) : undefined; + const clipMid = cleanVariantMediaId(c0?.primaryMediaId); + const rawClipMedia = Array.isArray(hist) + ? hist.find((x) => x && cleanVariantMediaId(x.id) === clipMid) ?? hist[0] ?? null + : null; + const m0 = legacyMedia(rawClipMedia); + if (isSceneClipTrimmed(c0, m0)) { + return { + primaryMediaId: null, + requiresSceneExport: true, + singleUrl: null, + width: null, + height: null, + duration: null, + variants: [], + sceneClips, + }; + } + const wfTile = wfId ? tileMap.get(wfId) : undefined; + const wfPrimary = wfTile ? selectPrimaryVideoMedia(wfTile) : null; + const primaryMediaId = + clipMid ?? + cleanVariantMediaId(m0?.id) ?? + wfPrimary?.primaryMediaId ?? + null; + const m0Status = String(m0?.Zc ?? c0?.Zc ?? c0?.od ?? "").toLowerCase(); + const m0NotReady = + m0Status === "pending" || + m0Status === "scheduled" || + m0Status === "failed" || + m0Status === "canceled" || + Boolean(m0?.nf || c0?.nf || c0?.Bf); + const singleUrl = m0NotReady + ? null + : nonExpired(readMediaUrl(m0, true)) || + nonExpired(readMediaUrl(c0, true)) || + nonExpired(readMediaUrl(m0)) || + nonExpired(readMediaUrl(c0)) || + (wfPrimary && wfPrimary.primaryMediaId === primaryMediaId ? wfPrimary.url : null); + const width = + typeof m0?.width === "number" + ? m0.width + : typeof m0?.tc?.width === "number" + ? m0.tc.width + : wfPrimary?.width ?? null; + const height = + typeof m0?.height === "number" + ? m0.height + : typeof m0?.tc?.height === "number" + ? m0.tc.height + : wfPrimary?.height ?? null; + const duration = + typeof c0?.nc === "number" + ? c0.nc + : typeof c0?.rc === "number" + ? c0.rc + : typeof m0?.Lf === "number" + ? m0.Lf + : wfPrimary?.duration ?? null; + const variants = wfTile ? collectReadyVideoVariants(wfTile, normalizeVideoUrl) : []; + return { + primaryMediaId, + requiresSceneExport: false, + singleUrl, + width, + height, + duration, + variants, + sceneClips, + }; + } + + return { + primaryMediaId: null, + requiresSceneExport: clips.length > 1, + singleUrl: null, + width: null, + height: null, + duration: null, + variants: [], + sceneClips, + }; +} diff --git a/ts/types.ts b/ts/types.ts index 1405bb6..990a4c0 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -542,6 +542,35 @@ export interface DiscoverStoreResult { error?: string; } +/** Canonical video quality label for `flow_download`. */ +export type VideoQualityLabel = "360p" | "720p" | "1080p" | "4k"; + +/** Ready video resolution variant recorded on a video or 1-clip scene tile. */ +export interface VideoVariantEntry { + /** Normalized primary media ID for `as29s` resolution. */ + media_id: string; + /** Verified video quality label when known. */ + quality: VideoQualityLabel | null; + /** Non-expired direct media URL when present on the tile. */ + url: string | null; + /** Rendered width in pixels when known. */ + width: number | null; + /** Rendered height in pixels when known. */ + height: number | null; + /** Video duration in seconds when known. */ + duration: number | null; +} + +/** Active clip workflow mapping on a `SCENE` tile for `:` selectors. */ +export interface SceneClipMediaEntry { + /** Clip workflow identifier inside the scene. */ + workflow_id: string; + /** Clip primary media identifier when present. */ + primary_media_id: string | null; + /** Non-expired direct clip URL when present on the scene. */ + url: string | null; +} + /** Asset entry normalized for `readStoreSnapshot`. */ export interface SnapshotAssetItem { /** Tile or clip workflow identifier. */ @@ -590,6 +619,10 @@ export interface SnapshotAssetItem { pcm_audio?: boolean; /** Underlying media family override when a tile downloads audio. */ media_kind?: "video" | "image" | "audio" | null; + /** Ready video resolution variants available on a video or 1-clip scene tile. */ + variants?: VideoVariantEntry[]; + /** Active timeline clip mappings on a scene tile for `:` selectors. */ + scene_clips?: SceneClipMediaEntry[]; } /** Collection summary returned inside `StoreSnapshotResult`. */ @@ -884,7 +917,11 @@ export interface FlowMcpRuntime { framePcmWav?: boolean, ) => Promise; /** Exports a multi-clip or trimmed scene via Angular `KD` RPCs and returns a `blob:` URL. */ - sceneExport: (sceneId: string, pollDelayMs?: number) => Promise; + sceneExport: ( + sceneId: string, + pollDelayMs?: number, + timeoutMs?: number, + ) => Promise; /** Resolves stream and download URLs for a primary media identifier via `as29s`. */ resolveVideoUrl: ( primaryMediaId: string,