diff --git a/docs/en/tools-reference.md b/docs/en/tools-reference.md index d8d6f6a..faeb050 100644 --- a/docs/en/tools-reference.md +++ b/docs/en/tools-reference.md @@ -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, audio, scene, or character look or voice) 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`. | 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 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..5b41366 100644 --- a/docs/ja/tools-reference.md +++ b/docs/ja/tools-reference.md @@ -387,11 +387,11 @@ Flow シーンタイムラインの一覧表示、作成、クリップ追加、 ### `flow_download` -一致するプロジェクトのメディアアセット(画像、動画、音声、またはキャラクター外見)を `/downloads` へダウンロードし、`flow-mcp.db` に登録します。最大 `45` 秒まで待機し(タイムアウト時は `pending: true`)、`{"file", "resource_uri", "record"}` を返します。クライアントが MCP `2025-06-18` 以降に対応している場合は、`resource_link` も返します。 +一致するプロジェクトのメディアアセット(画像、動画、音声、シーン、またはキャラクターの外見と音声)を `/downloads` へダウンロードし、`flow-mcp.db` に登録します。最大 `45` 秒まで待機し(タイムアウト時は `pending: true`)、`{"file", "resource_uri", "record"}` を返します。クライアントが MCP `2025-06-18` 以降に対応している場合は、`resource_link` も返します。 | パラメータ | 型 | 必須 | 説明 | | :--- | :--- | :--- | :--- | -| `match` | `string` | はい | プロジェクトアセットに一致する正確なアセット ID、完全一致名、または大文字小文字を区別しない部分文字列。 | +| `match` | `string` | はい | プロジェクトアセットに一致する正確なアセットまたはバリアント ID、完全一致名、または大文字小文字を区別しない部分文字列。 | ### `flow_downloads` diff --git a/docs/zh-CN/tools-reference.md b/docs/zh-CN/tools-reference.md index 748749e..b75c3df 100644 --- a/docs/zh-CN/tools-reference.md +++ b/docs/zh-CN/tools-reference.md @@ -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`。 +将匹配的项目媒体资产(图像、视频、音频、场景或角色外观与音色)下载至 `/downloads` 并索引到 `flow-mcp.db`。最多等待 `45` 秒(超时返回 `pending: true`),并返回 `{"file", "resource_uri", "record"}`。如果客户端支持 MCP `2025-06-18` 或更高版本,还会返回 `resource_link`。 | 参数 | 类型 | 必填 | 说明 | | :--- | :--- | :--- | :--- | -| `match` | `string` | 是 | 匹配项目资产的精确资产 ID、精确名称或忽略大小写子串。 | +| `match` | `string` | 是 | 匹配项目资产的精确资产或变体 ID、精确名称或忽略大小写子串。 | ### `flow_downloads` diff --git a/src/assets.rs b/src/assets.rs index c3c8975..226e6cb 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -60,6 +60,15 @@ pub(crate) struct FlowAsset { /// Primary media ID for video trim and edit operations. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) primary_media_id: Option, + /// Internal list of media variant and history IDs associated with this tile. + #[serde(default, skip_serializing)] + pub(crate) variant_ids: Vec, + /// Internal media family hint cached from `as29s` resolution. + #[serde(default, skip_serializing)] + pub(crate) media_kind_hint: Option, + /// Internal flag set when `as29s` case `11` returned raw 24 kHz PCM bytes. + #[serde(default, skip_serializing)] + pub(crate) pcm_audio: bool, /// Character personality notes or introduction text. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) personality_notes: Option, @@ -83,6 +92,40 @@ pub(crate) struct FlowAsset { pub(crate) created_at: Option, } +impl FlowAsset { + /// Builds an image [`FlowAsset`] for a freshly generated look or preview media item. + pub(crate) fn new_image( + id: String, + name: String, + url: Option, + primary_media_id: Option, + ) -> Self { + Self { + id, + name, + kind: "image".to_string(), + prompt: None, + url, + collection_id: None, + collection_name: None, + width: None, + height: None, + duration: None, + primary_media_id, + variant_ids: Vec::new(), + media_kind_hint: None, + pcm_audio: false, + personality_notes: None, + voice: None, + trim_start_seconds: None, + trim_end_seconds: None, + media_status: None, + media_error: None, + created_at: None, + } + } +} + /// Snapshot of active project metadata and asset tiles. #[derive(Debug, Clone)] pub(crate) struct ProjectAssetsSnapshot { @@ -168,7 +211,7 @@ async fn populate_missing_media_urls( for (index, asset) in assets.iter().enumerate() { if !matches!( asset.kind.as_str(), - "video" | "image" | "character" | "audio" + "video" | "image" | "character" | "audio" | "scene" ) || asset.url.is_some() || asset.media_error.is_some() || matches!( @@ -195,31 +238,42 @@ 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(|v| v.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 let Some(ref mk) = media_kind { + assets[index].media_kind_hint = Some(mk.clone()); + } + if pcm_audio { + assets[index].pcm_audio = true; + } if assets[index].kind == "image" && media_kind.as_deref() == Some("audio") { assets[index].kind = "audio".to_string(); } @@ -268,8 +322,80 @@ async fn read_project_assets(engine: &ChromeEngine) -> Result &str { + let trimmed = value.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 + } +} + +/// Returns `true` when `candidate` equals `query` either verbatim or without resource prefix. +fn media_id_matches(candidate: &str, query: &str) -> bool { + let clean_cand = strip_media_prefix(candidate); + let clean_query = strip_media_prefix(query); + !clean_cand.is_empty() && (candidate.trim() == query || clean_cand == clean_query) +} + +/// Finds a variant ID on `asset` that matches `raw` verbatim or without resource prefix. +fn find_exact_variant_id<'a>(asset: &'a FlowAsset, raw: &str) -> Option<&'a str> { + asset + .variant_ids + .iter() + .map(String::as_str) + .find(|v| media_id_matches(v, raw)) +} + +/// Pins `target.primary_media_id` and clears stale `target.url` when `match_str` targets a specific variant ID. +fn pin_matched_variant(target: &mut FlowAsset, match_str: &str) { + let raw = match_str.trim(); + if raw.is_empty() || media_id_matches(&target.id, raw) || target.name.eq_ignore_ascii_case(raw) + { + return; + } + let matched_variant = find_exact_variant_id(target, raw).or_else(|| { + let lower = raw.to_lowercase(); + let non_variant_hit = target.name.to_lowercase().contains(&lower) + || target.id.to_lowercase().contains(&lower) + || target + .primary_media_id + .as_deref() + .is_some_and(|pm| pm.to_lowercase().contains(&lower)); + if non_variant_hit { + None + } else { + target + .variant_ids + .iter() + .map(String::as_str) + .find(|v| v.to_lowercase().contains(&lower)) + } + }); + let Some(chosen) = matched_variant else { + return; + }; + let clean_chosen = strip_media_prefix(chosen).to_string(); + if clean_chosen.is_empty() { + return; + } + let same_primary = target + .primary_media_id + .as_deref() + .is_some_and(|pm| media_id_matches(pm, &clean_chosen)); + if !same_primary { + target.url = None; + target.media_kind_hint = None; + target.pcm_audio = false; + } + target.primary_media_id = Some(clean_chosen); +} + +/// Selects the best-matching asset by exact ID, primary or variant media ID, exact name, +/// name substring, ID substring, or optional prompt substring. pub(crate) fn match_asset<'a>( assets: &'a [FlowAsset], match_str: &str, @@ -283,14 +409,36 @@ pub(crate) fn match_asset<'a>( assets .iter() - .find(|a| a.id == raw) + .find(|a| a.id == raw || media_id_matches(&a.id, raw)) + .or_else(|| { + assets.iter().find(|a| { + a.primary_media_id + .as_deref() + .is_some_and(|pm| media_id_matches(pm, raw)) + }) + }) + .or_else(|| { + assets + .iter() + .find(|a| find_exact_variant_id(a, raw).is_some()) + }) .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(|| { + assets.iter().find(|a| { + a.id.to_lowercase().contains(&lower) + || a.primary_media_id + .as_deref() + .is_some_and(|pm| pm.to_lowercase().contains(&lower)) + || a.variant_ids + .iter() + .any(|v| v.to_lowercase().contains(&lower)) + }) + }) .or_else(|| { if include_prompt { assets.iter().find(|a| { @@ -314,7 +462,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 +470,7 @@ pub(crate) async fn resolve_asset( match_str, context_label ) })?; + pin_matched_variant(&mut target, match_str); Ok((target, snap.project_id, snap.project_title)) } @@ -356,7 +505,11 @@ pub(crate) async fn list_assets( } if let Some(q) = &q_lower { 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.primary_media_id + .as_deref() + .is_some_and(|pm| pm.to_lowercase().contains(q)) + || a.variant_ids.iter().any(|v| v.to_lowercase().contains(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..3fc4e80 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::new_image( + media_id.clone().unwrap_or_else(|| char_id.clone()), + 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..a1dda48 100644 --- a/src/download.rs +++ b/src/download.rs @@ -9,19 +9,29 @@ use serde_json::{Value, json}; use std::path::Path; use std::sync::OnceLock; use tokio::io::{AsyncWriteExt, BufWriter}; -use tokio::time::Duration; +use tokio::time::{Duration, Instant}; use url::Url; use crate::assets::{FlowAsset, resolve_asset}; use crate::config::downloads_dir; use crate::db::{DownloadRecord, FlowDb, NewDownloadRecord}; -use crate::engine::{ChromeEngine, DEFAULT_CHROME_UA}; +use crate::engine::{ChromeEngine, DEFAULT_CHROME_UA, checked_runtime_result}; use crate::media_files::{ - MEDIA_KIND_MISMATCH_TAG, disambiguate_dest, natural_asset_filename, resolve_stored_path, + MEDIA_KIND_MISMATCH_TAG, disambiguate_dest, is_expired_signed_url, is_signed_direct_url, + is_signed_url_auth_failure, natural_asset_filename, resolve_stored_path, validate_content_type_header, validate_downloaded_file, }; use crate::platform::create_private_dir_all; +/// Maximum time to poll a multi-clip or trimmed scene export inside `flow_download`. +const SCENE_EXPORT_BUDGET: Duration = Duration::from_secs(38); + +/// Delay between `IxdSwd` poll requests while a scene export runs. +const SCENE_EXPORT_POLL_INTERVAL: Duration = Duration::from_millis(1_500); + +/// Per-RPC timeout passed to `window.__flowMcp.exportScene` in milliseconds. +const SCENE_EXPORT_RPC_TIMEOUT_MS: u64 = 10_000; + /// Source location for the media bytes of one [`FlowAsset`]. #[derive(Debug, Clone)] enum DownloadSource { @@ -41,6 +51,11 @@ enum DownloadSource { }, /// Unsigned media URL when the asset has no media ID. UnsignedUrl(String), + /// Multi-clip or trimmed scene tile exported to MP4 via `GjQLTd` and `IxdSwd`. + ExportScene { + /// Scene tile identifier in the active project store. + scene_id: String, + }, } /// Ordered URL candidates and media kind from `resolveVideoUrl`. @@ -49,6 +64,8 @@ struct ResolvedMediaUrls { urls: Vec, /// Media family from the `as29s` wire message when present. media_kind: Option, + /// True when `as29s` case `11` flagged raw 24 kHz PCM audio bytes. + pcm_audio: bool, } /// Returns the shared HTTP client for streaming media downloads. @@ -69,6 +86,7 @@ async fn stream_http_to_temp( engine: &ChromeEngine, media_url: &str, expected_kind: &str, + pcm_audio: bool, temp_path: &Path, ) -> Result<(Option, Option, u64)> { let signed_url = is_signed_direct_url(media_url); @@ -119,8 +137,13 @@ async fn stream_http_to_temp( if size_bytes == 0 { anyhow::bail!("Media URL returned empty body"); } - let validated_ct = validate_downloaded_file(temp_path, raw_ct, expected_kind).await?; - Ok((validated_ct, disp, size_bytes)) + let (effective_ct, framed_size) = if pcm_audio && expected_kind == "audio" { + crate::pcm_wav::frame_raw_pcm_file(temp_path, raw_ct).await? + } else { + (raw_ct, size_bytes) + }; + let validated_ct = validate_downloaded_file(temp_path, effective_ct, expected_kind).await?; + Ok((validated_ct, disp, framed_size)) } /// Fetches a media URL inside the active Chrome page and writes bytes to `temp_path`. @@ -128,6 +151,7 @@ async fn fetch_via_browser_to_temp( engine: &ChromeEngine, media_url: &str, expected_kind: &str, + pcm_audio: bool, temp_path: &Path, ) -> Result<(Option, Option, u64)> { let val = engine @@ -154,39 +178,13 @@ async fn fetch_via_browser_to_temp( .map(str::to_string); let size_bytes = bytes.len() as u64; tokio::fs::write(temp_path, &bytes).await?; - let validated_ct = validate_downloaded_file(temp_path, raw_ct, expected_kind).await?; - 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; + let (effective_ct, framed_size) = if pcm_audio && expected_kind == "audio" { + crate::pcm_wav::frame_raw_pcm_file(temp_path, raw_ct).await? + } else { + (raw_ct, size_bytes) }; - 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" - ) - }) + let validated_ct = validate_downloaded_file(temp_path, effective_ct, expected_kind).await?; + Ok((validated_ct, disp, framed_size)) } /// Appends `raw` to `out` when it uses an allowed scheme and is not already present. @@ -307,12 +305,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(|v| v.as_bool()) + .unwrap_or(false); let effective_kind = if media_kind.as_deref() == Some("audio") { "audio" } else { @@ -322,6 +325,9 @@ async fn query_resolved_media_urls( let mut signed = Vec::new(); let mut unsigned = Vec::new(); let mut record_cand = |raw: &str| { + if is_expired_signed_url(raw) { + return; + } if is_signed_direct_url(raw) { push_unique_url(&mut signed, raw); } else { @@ -346,7 +352,11 @@ 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. @@ -355,7 +365,7 @@ fn select_download_source(target: &FlowAsset, label: &str) -> Result Result Ok(DownloadSource::UnsignedUrl(url)), + (None, None) if target.kind == "scene" && !target.id.trim().is_empty() => { + Ok(DownloadSource::ExportScene { + scene_id: target.id.trim().to_string(), + }) + } (None, None) => anyhow::bail!("Asset '{}' has no media URL or media ID", label), } } @@ -390,24 +405,38 @@ async fn try_download_candidates( engine: &ChromeEngine, candidates: &[String], expected_kind: &str, + pcm_audio: bool, temp_path: &Path, ) -> Result<((Option, Option, u64), String)> { let mut attempts = Vec::new(); for cand_url in candidates { let lower = cand_url.to_ascii_lowercase(); let is_http = lower.starts_with("http://") || lower.starts_with("https://"); + if is_http && is_expired_signed_url(cand_url) { + attempts.push(format!("{} (expired signed URL)", cand_url)); + continue; + } if is_http && is_signed_direct_url(cand_url) { let _ = tokio::fs::remove_file(temp_path).await; - match stream_http_to_temp(engine, cand_url, expected_kind, temp_path).await { + match stream_http_to_temp(engine, cand_url, expected_kind, pcm_audio, 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) + || is_signed_url_auth_failure(&http_err) + { 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, + pcm_audio, + temp_path, + ) + .await { Ok(res) => return Ok((res, cand_url.clone())), Err(browser_err) => { @@ -422,7 +451,9 @@ 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, pcm_audio, temp_path) + .await + { Ok(res) => return Ok((res, cand_url.clone())), Err(browser_err) => { let _ = tokio::fs::remove_file(temp_path).await; @@ -430,7 +461,9 @@ async fn try_download_candidates( attempts.push(format!("{} (browser: {})", cand_url, browser_err)); continue; } - match stream_http_to_temp(engine, cand_url, expected_kind, temp_path).await { + match stream_http_to_temp(engine, cand_url, expected_kind, pcm_audio, temp_path) + .await + { Ok(res) => return Ok((res, cand_url.clone())), Err(http_err) => { let _ = tokio::fs::remove_file(temp_path).await; @@ -444,7 +477,9 @@ 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, pcm_audio, temp_path) + .await + { Ok(res) => return Ok((res, cand_url.clone())), Err(browser_err) => { let _ = tokio::fs::remove_file(temp_path).await; @@ -456,6 +491,96 @@ async fn try_download_candidates( anyhow::bail!("{}", attempts.join(" | ")) } +/// Exports a multi-clip or trimmed scene via `GjQLTd` and `IxdSwd` and writes the MP4 to `temp_path`. +async fn export_scene_to_temp( + engine: &ChromeEngine, + scene_id: &str, + temp_path: &Path, +) -> Result<((Option, Option, u64), String)> { + let deadline = Instant::now() + SCENE_EXPORT_BUDGET; + let start_raw = engine + .call_flow_async( + "exportScene", + json!([{ + "action": "start", + "scene_id": scene_id, + "timeout_ms": SCENE_EXPORT_RPC_TIMEOUT_MS, + }]), + ) + .await?; + let mut step = checked_runtime_result(start_raw)?; + let mut export_id = step + .get("export_id") + .and_then(|v| v.as_str()) + .map(str::to_string); + + loop { + if step.get("status").and_then(|v| v.as_str()) == Some("ready") { + let blob_url = step + .get("blob_url") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .context("Scene export returned ready status without a blob URL")? + .to_string(); + let fetch_res = + fetch_via_browser_to_temp(engine, &blob_url, "video", false, temp_path).await; + let _ = engine + .call_flow_async( + "exportScene", + json!([{ + "action": "release", + "export_id": export_id, + "blob_url": blob_url, + }]), + ) + .await; + let meta = fetch_res?; + return Ok((meta, blob_url)); + } + + let Some(ref active_id) = export_id else { + anyhow::bail!("Scene export did not return an export handle"); + }; + let now = Instant::now(); + if now >= deadline { + let _ = engine + .call_flow_async( + "exportScene", + json!([{ "action": "release", "export_id": active_id }]), + ) + .await; + anyhow::bail!( + "Scene export timed out after {}s", + SCENE_EXPORT_BUDGET.as_secs() + ); + } + let sleep_dur = SCENE_EXPORT_POLL_INTERVAL.min(deadline.saturating_duration_since(now)); + tokio::time::sleep(sleep_dur).await; + + let rpc_ms = u64::try_from( + deadline + .saturating_duration_since(Instant::now()) + .as_millis(), + ) + .unwrap_or(1_000) + .clamp(1_000, SCENE_EXPORT_RPC_TIMEOUT_MS); + let poll_raw = engine + .call_flow_async( + "exportScene", + json!([{ + "action": "poll", + "export_id": active_id, + "timeout_ms": rpc_ms, + }]), + ) + .await?; + step = checked_runtime_result(poll_raw)?; + if let Some(next_id) = step.get("export_id").and_then(|v| v.as_str()) { + export_id = Some(next_id.to_string()); + } + } +} + /// Downloads a resolved [`FlowAsset`] into `/downloads` and indexes it in SQLite. pub(crate) async fn download_resolved_asset( engine: &ChromeEngine, @@ -477,39 +602,59 @@ 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 matches!(target.kind.as_str(), "image" | "character") + && target.media_kind_hint.as_deref() == Some("audio") + { + "audio".to_string() + } else { + target.kind.clone() + }; + let mut pcm_audio = target.pcm_audio; + let download_res = match source { 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 prev_kind = effective_kind.clone(); + let prev_pcm = pcm_audio; let resolved = query_resolved_media_urls(engine, &media_id, &effective_kind, true) .await; - if effective_kind == "image" + 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 retry_same_url = effective_kind != prev_kind || pcm_audio != prev_pcm; let mut extra = Vec::new(); for cand in resolved.urls { - if cand != url { + if retry_same_url || cand != url { 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 +668,67 @@ 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 { + push_fife_candidates(&mut candidates, raw_fallback, &effective_kind); + push_unique_url(&mut candidates, raw_fallback); } - if candidates.is_empty() { + let cached_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 cached_attempt { + Ok(res) => Ok(res), + Err(first_err) => { + let fresh = + query_resolved_media_urls(engine, &media_id, &effective_kind, true).await; + if matches!(effective_kind.as_str(), "image" | "character") + && fresh.media_kind.as_deref() == Some("audio") + { + effective_kind = "audio".to_string(); + } + pcm_audio |= fresh.pcm_audio; + let mut fresh_candidates = fresh.urls; + if let Some(ref raw_fallback) = fallback_url { + push_fife_candidates(&mut fresh_candidates, raw_fallback, &effective_kind); + push_unique_url(&mut fresh_candidates, raw_fallback); + } + if fresh_candidates.is_empty() { + Err(first_err) + } else { + try_download_candidates( + engine, + &fresh_candidates, + &effective_kind, + pcm_audio, + &temp_path, + ) + .await + .map_err(|retry_err| anyhow::anyhow!("{} | {}", first_err, retry_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 + } + DownloadSource::ExportScene { scene_id } => { + export_scene_to_temp(engine, &scene_id, &temp_path).await } }; diff --git a/src/main.rs b/src/main.rs index d180c44..c158365 100644 --- a/src/main.rs +++ b/src/main.rs @@ -23,6 +23,7 @@ mod http; mod instance; mod mcp; mod media_files; +mod pcm_wav; mod platform; mod project; mod project_route; diff --git a/src/mcp.rs b/src/mcp.rs index 2a0eef9..b32630c 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -204,9 +204,9 @@ impl FlowMcpServer { Self::format_result(self.service.trash(&req.r#match).await) } - /// Downloads a media asset from the active Google Flow project. + /// Downloads a media asset or scene 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, scene, or character asset from the active Google Flow project." )] async fn flow_download( &self, diff --git a/src/media_files.rs b/src/media_files.rs index f3b34fb..91eb33d 100644 --- a/src/media_files.rs +++ b/src/media_files.rs @@ -7,6 +7,7 @@ use anyhow::{Context, Result}; use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; use serde_json::{Value, json}; use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; use tokio::io::{AsyncReadExt, AsyncSeekExt}; use url::Url; @@ -23,6 +24,142 @@ const DEFAULT_CHUNK_BYTES: usize = 1_048_576; /// Maximum chunk size (`4 MiB`) allowed by `flow_downloads` `read_chunk`. const MAX_CHUNK_BYTES: usize = 4_194_304; +/// Clock-skew safety margin subtracted from signed URL deadlines in seconds. +const SIGNED_URL_SKEW_SECS: u64 = 5; + +/// Returns `true` when `raw_url` carries signed GCS/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" + ) + }) +} + +/// Parses an `X-Goog-Date` basic UTC timestamp (`YYYYMMDDTHHMMSSZ`) into Unix epoch seconds. +fn parse_goog_date_epoch_secs(raw: &str) -> Option { + let b = raw.trim().as_bytes(); + if b.len() != 16 || !matches!(b[8], b'T' | b't') || !matches!(b[15], b'Z' | b'z') { + return None; + } + let s = std::str::from_utf8(b).ok()?; + let year: i64 = s[0..4].parse().ok()?; + let month: u64 = s[4..6].parse().ok()?; + let day: u64 = s[6..8].parse().ok()?; + let hour: u64 = s[9..11].parse().ok()?; + let minute: u64 = s[11..13].parse().ok()?; + let second: u64 = s[13..15].parse().ok()?; + if !(1..=12).contains(&month) + || !(1..=31).contains(&day) + || hour > 23 + || minute > 59 + || second > 60 + { + return None; + } + 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 mp = if month > 2 { month - 3 } else { month + 9 }; + let doy = (153 * mp + 2) / 5 + day - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + (doe as i64) - 719_468; + if days < 0 { + return None; + } + Some((days as u64) * 86_400 + hour * 3_600 + minute * 60 + second) +} + +/// Returns `true` when `raw_url` carries an expired GCS V4 (`X-Goog-Date` + `X-Goog-Expires`) or V2 (`Expires`) signature. +pub(crate) fn is_expired_signed_url(raw_url: &str) -> bool { + let Ok(parsed) = Url::parse(raw_url.trim()) else { + return false; + }; + if !matches!(parsed.scheme(), "http" | "https") { + return false; + } + let now_secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + + 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(ref gd) = goog_date { + let Some(issued_secs) = parse_goog_date_epoch_secs(gd) else { + return true; + }; + if let Some(ref ge) = goog_expires { + let Ok(ttl_secs) = ge.trim().parse::() else { + return true; + }; + if ttl_secs == 0 { + return true; + } + return now_secs.saturating_add(SIGNED_URL_SKEW_SECS) + >= issued_secs.saturating_add(ttl_secs); + } + } + + if has_v2_sig && let Some(ref exp_str) = v2_expires { + let Ok(raw_exp) = exp_str.trim().parse::() else { + return true; + }; + if raw_exp == 0 { + return true; + } + let exp_secs = if raw_exp > 100_000_000_000 { + raw_exp / 1_000 + } else { + raw_exp + }; + return now_secs.saturating_add(SIGNED_URL_SKEW_SECS) >= exp_secs; + } + + false +} + +/// Returns `true` when `err` represents an HTTP 400 or 403 signature rejection on a signed URL. +pub(crate) fn is_signed_url_auth_failure(err: &anyhow::Error) -> bool { + err.downcast_ref::() + .and_then(reqwest::Error::status) + .is_some_and(|status| matches!(status.as_u16(), 400 | 403)) +} + /// Decodes one hexadecimal ASCII byte into its 4-bit integer value. fn hex_nibble(b: u8) -> Option { match b { @@ -175,6 +312,36 @@ fn default_extension_for_asset(expected_kind: &str, content_type: Option<&str>) }) } +/// Returns `true` when `ext` is a recognized image, video, or audio file extension. +fn is_allowed_media_extension(ext: &str) -> bool { + matches!( + ext.to_ascii_lowercase().as_str(), + "mp4" + | "webm" + | "mov" + | "avi" + | "mkv" + | "m4v" + | "png" + | "jpg" + | "jpeg" + | "webp" + | "gif" + | "avif" + | "heic" + | "heif" + | "wav" + | "mp3" + | "m4a" + | "aac" + | "ogg" + | "opus" + | "flac" + | "aif" + | "aiff" + ) +} + /// Resolves the natural download file name from HTTP headers, URL path, or `.`. pub(crate) fn natural_asset_filename( target: &FlowAsset, @@ -187,13 +354,18 @@ 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; } + let stem = Path::new(&name) + .file_stem() + .and_then(|s| s.to_str()) + .filter(|s| !s.is_empty()) + .unwrap_or(&name); return format!( "{}.{}", - name, + stem, default_extension_for_asset(expected_kind, content_type) ); } @@ -204,7 +376,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/src/pcm_wav.rs b/src/pcm_wav.rs new file mode 100644 index 0000000..7a1cb6f --- /dev/null +++ b/src/pcm_wav.rs @@ -0,0 +1,135 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Host RIFF WAVE framing for raw 24 kHz 16-bit mono PCM audio streams. + +use anyhow::{Result, bail}; +use std::path::Path; + +/// Output sample rate in hertz for Google Flow case `11` PCM audio. +const PCM_SAMPLE_RATE: u32 = 24_000; + +/// Channel count for Google Flow case `11` mono PCM audio. +const PCM_CHANNELS: u16 = 1; + +/// Sample width in bits for signed 16-bit little-endian PCM audio. +const PCM_BITS_PER_SAMPLE: u16 = 16; + +/// Bytes per sample frame across all channels. +const PCM_BLOCK_ALIGN: u16 = PCM_CHANNELS * (PCM_BITS_PER_SAMPLE / 8); + +/// Average byte rate per second (`sample_rate * block_align`). +const PCM_BYTE_RATE: u32 = PCM_SAMPLE_RATE * (PCM_BLOCK_ALIGN as u32); + +/// Fixed byte length of a standard canonical RIFF WAVE header. +const WAV_HEADER_LEN: usize = 44; + +/// Returns `true` when `bytes` begins with HTML, XML, playlist, XSSI, or JSON error text. +fn is_text_or_playlist_prefix(bytes: &[u8]) -> bool { + let start = bytes + .iter() + .position(|b| !b.is_ascii_whitespace()) + .unwrap_or(bytes.len()); + let trimmed = &bytes[start..]; + let lower: Vec = trimmed + .iter() + .take(16) + .map(|b| b.to_ascii_lowercase()) + .collect(); + if lower.starts_with(b"(trimmed).is_ok() + { + return true; + } + false +} + +/// Returns `true` when `hdr` starts with a recognized image, audio, or video container header. +fn is_known_media_container(hdr: &[u8]) -> bool { + let is_jpeg = hdr.starts_with(&[0xFF, 0xD8, 0xFF]); + let is_png = hdr.starts_with(b"\x89PNG\r\n\x1a\n"); + let is_gif = hdr.starts_with(b"GIF87a") || hdr.starts_with(b"GIF89a"); + let is_riff = hdr.len() >= 12 + && &hdr[0..4] == b"RIFF" + && matches!(&hdr[8..12], b"WAVE" | b"WEBP" | b"AVI "); + let is_iso_bmff = hdr.len() >= 8 + && matches!( + &hdr[4..8], + b"ftyp" | b"styp" | b"moov" | b"mdat" | b"wide" | b"free" | b"skip" + ); + let is_flac = hdr.starts_with(b"fLaC"); + let is_ogg = hdr.starts_with(b"OggS"); + let is_aiff = + hdr.len() >= 12 && &hdr[0..4] == b"FORM" && matches!(&hdr[8..12], b"AIFF" | b"AIFC"); + let is_id3 = hdr.starts_with(b"ID3"); + let is_webm = hdr.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]); + is_jpeg + || is_png + || is_gif + || is_riff + || is_iso_bmff + || is_flac + || is_ogg + || is_aiff + || is_id3 + || is_webm +} + +/// Builds a 44-byte canonical RIFF WAVE header for `pcm_byte_len` bytes of 24 kHz 16-bit mono PCM. +fn build_riff_wave_header(pcm_byte_len: u32) -> [u8; WAV_HEADER_LEN] { + let riff_size = 36u32.saturating_add(pcm_byte_len); + let mut hdr = [0u8; WAV_HEADER_LEN]; + hdr[0..4].copy_from_slice(b"RIFF"); + hdr[4..8].copy_from_slice(&riff_size.to_le_bytes()); + hdr[8..12].copy_from_slice(b"WAVE"); + hdr[12..16].copy_from_slice(b"fmt "); + hdr[16..20].copy_from_slice(&16u32.to_le_bytes()); + hdr[20..22].copy_from_slice(&1u16.to_le_bytes()); + hdr[22..24].copy_from_slice(&PCM_CHANNELS.to_le_bytes()); + hdr[24..28].copy_from_slice(&PCM_SAMPLE_RATE.to_le_bytes()); + hdr[28..32].copy_from_slice(&PCM_BYTE_RATE.to_le_bytes()); + hdr[32..34].copy_from_slice(&PCM_BLOCK_ALIGN.to_le_bytes()); + hdr[34..36].copy_from_slice(&PCM_BITS_PER_SAMPLE.to_le_bytes()); + hdr[36..40].copy_from_slice(b"data"); + hdr[40..44].copy_from_slice(&pcm_byte_len.to_le_bytes()); + hdr +} + +/// Frames raw non-text PCM bytes at `path` into a 24 kHz 16-bit mono RIFF WAVE file when needed. +pub(crate) async fn frame_raw_pcm_file( + path: &Path, + ct: Option, +) -> Result<(Option, u64)> { + let bytes = tokio::fs::read(path).await?; + if bytes.is_empty() { + bail!("Media URL returned empty body"); + } + if is_text_or_playlist_prefix(&bytes) || is_known_media_container(&bytes) { + return Ok((ct, bytes.len() as u64)); + } + + let pcm_len = bytes.len() & !1usize; + if pcm_len == 0 { + bail!("PCM audio stream contains fewer than 2 bytes"); + } + let data_len = u32::try_from(pcm_len) + .map_err(|_| anyhow::anyhow!("PCM audio stream exceeds the 4 GiB WAV limit"))?; + let header = build_riff_wave_header(data_len); + + let mut framed = Vec::with_capacity(WAV_HEADER_LEN.saturating_add(pcm_len)); + framed.extend_from_slice(&header); + framed.extend_from_slice(&bytes[..pcm_len]); + tokio::fs::write(path, &framed).await?; + Ok((Some("audio/wav".to_string()), framed.len() as u64)) +} diff --git a/ts/dom.ts b/ts/dom.ts index c2e9607..c3dfa38 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 { cleanMediaIdKey, isExpiredSignedUrl, pickUpsampledTileUrl } from "./media_variants"; import type { CharacterLookEntry, FifeEnv, FlowMediaPayload, FlowTile } from "./types"; /** Reads an own data property from `o` without invoking prototype getters. */ @@ -66,7 +67,7 @@ export function isNonAssetTileType(type: unknown): boolean { const VIDEO_SHORT_EDGE: Readonly> = { 1: 720, 2: 1080, 3: 2160, 4: 360 }; /** Calculates video pixel dimensions from a Flow resolution code and an aspect ratio, or returns null. */ -function videoDimensions( +export function videoDimensions( resolution: unknown, aspectRatio: unknown, ): { width: number; height: number } | null { @@ -242,6 +243,77 @@ export function characterLooksOf( return null; } +/** Reads a 1-based protobuf field from a dense or sparse serialized JSPB array. */ +function charProtoField(message: unknown, field: number): unknown { + if (!Array.isArray(message) || field < 1) return undefined; + const sparse = message.at(-1); + if (sparse && typeof sparse === "object" && !Array.isArray(sparse)) { + if (field - 1 < message.length - 1 && message[field - 1] != null) { + return message[field - 1]; + } + return readMediaField(sparse, String(field)); + } + return message[field - 1]; +} + +/** Extracts an identifier string from a voice value or nested voice descriptor. */ +function pickVoiceIdentifier(raw: unknown): string | null { + if (raw == null) return null; + if (typeof raw === "string") { + const s = raw.trim(); + return s ? (s.startsWith("voices/") ? s : cleanMediaIdKey(s) || s) : null; + } + if (Array.isArray(raw)) { + return raw.length > 0 ? pickVoiceIdentifier(raw[0]) : null; + } + if (typeof raw === "object") { + for (const key of ["mediaId", "voiceId", "id", "workflowId", "Th"]) { + const candidate = pickVoiceIdentifier(readMediaField(raw, key)); + if (candidate) return candidate; + } + } + return null; +} + +/** Reads the assigned voice identifier from character tile `t` when no look media exists. */ +function fallbackCharacterVoiceId(t: FlowTile): string | null { + const mappedVoiceMedia = pickVoiceIdentifier(t.voiceMediaId); + if (mappedVoiceMedia) return mappedVoiceMedia; + + const charFmt = snapshotFormat()?.character; + const entity = readMediaField(t, charFmt?.entity ?? "Rc"); + if (entity && typeof entity === "object") { + try { + const toJson = (entity as { toJSON?: unknown }).toJSON; + const root = typeof toJson === "function" ? toJson.call(entity) : readMediaField(entity, "qf"); + const info = charProtoField( + charProtoField(root, charFmt?.entityInfoField ?? 4), + charFmt?.characterInfoField ?? 3, + ); + const refs = charProtoField(info, charFmt?.audioReferencesField ?? 2); + if (Array.isArray(refs) && refs.length > 0) { + const custom = pickVoiceIdentifier( + charProtoField(refs[0], charFmt?.customVoiceField ?? 1), + ); + if (custom) return custom; + const preset = pickVoiceIdentifier( + charProtoField(refs[0], charFmt?.presetVoiceField ?? 2), + ); + if (preset) return preset; + } + } catch { + // Fall through to plain field inspection. + } + } + + return ( + pickVoiceIdentifier(t.voiceId) ?? + pickVoiceIdentifier(t.Vo) ?? + pickVoiceIdentifier(t.voice) ?? + pickVoiceIdentifier(t.audioReferences) + ); +} + /** Extracts the preferred look image URL and primary media ID from character tile `t`. */ export function characterLookMedia( t: FlowTile | null | undefined, @@ -286,9 +358,14 @@ export function characterLookMedia( } } } + const lookUrl = preferredId ? preferredUrl : fallbackUrl; + const lookPrimaryId = preferredId || firstPrimaryId; + if (!lookUrl && !lookPrimaryId) { + return { url: null, primaryMediaId: fallbackCharacterVoiceId(t) }; + } return { - url: preferredId ? preferredUrl : fallbackUrl, - primaryMediaId: preferredId || firstPrimaryId, + url: lookUrl, + primaryMediaId: lookPrimaryId, }; } @@ -553,16 +630,23 @@ export function normalizeFlowMediaUrl( export function pickTileUrl(tile: FlowTile | null | undefined): string | null { const t = legacyTile(tile); if (!t) return null; + const nonExpired = (u: string | null): string | null => + u && !isExpiredSignedUrl(u) ? u : null; const kind = String(t.type ?? "").toUpperCase() === "VIDEO" ? "video" : "image"; + const upsampledUrl = kind === "video" ? pickUpsampledTileUrl(tile) : null; const videoUrl = kind === "video" - ? readMediaUrl(t.Fb, true) || readMediaUrl(t, true) || readMediaUrl(t.fb, true) + ? upsampledUrl || + 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/index.ts b/ts/index.ts index f28568a..b0a3352 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 { exportScene } from "./scene_export"; import { sceneOp } from "./scene_ops"; import { setupGeneration } from "./setup_generation"; import { submitGeneration } from "./submit_generation"; @@ -77,6 +78,7 @@ if (!window.__flowMcp) { openEditAsset, submitGeneration, sceneOp, + exportScene, videoOp, characterOp, characterBioOp, diff --git a/ts/media_variants.ts b/ts/media_variants.ts new file mode 100644 index 0000000..e01fb08 --- /dev/null +++ b/ts/media_variants.ts @@ -0,0 +1,542 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Video upscale variant selection, signed URL expiry checks, and variant ID indexing. + +import { readOwn } from "./angular"; +import { + characterLooksOf, + findMediaContainer, + legacyMedia, + legacyTile, + readMediaUrl, + videoDimensions, +} from "./dom"; +import { runtimeState } from "./state"; +import type { + CachedMediaInfo, + FlowMediaPayload, + FlowTile, + SceneClipItem, +} from "./types"; + +/** Cache time-to-live for `as29s` media lookups in milliseconds (10 minutes). */ +export const MEDIA_INFO_TTL_MS = 10 * 60 * 1000; + +/** Clock-skew margin subtracted from signed URL expiry deadlines in milliseconds. */ +const SIGNED_URL_SKEW_MS = 5 * 1000; + +/** Priority score for each Flow video resolution code (`3` = 4K, `2` = 1080p, `1` = 720p, `4` = 360p). */ +const RESOLUTION_PRIORITY: Readonly> = { + 3: 40, + 2: 30, + 1: 20, + 4: 10, +}; + +/** Selected video variant metadata from a project tile. */ +export interface SelectedVideoVariant { + /** Normalized media payload for the selected variant when present. */ + media: FlowMediaPayload | null; + /** Primary media ID of the selected variant when known. */ + primaryMediaId: string | null; + /** Non-expired inline media URL on the selected variant when available. */ + url: string | null; + /** Pixel width of the selected variant when known. */ + width: number | null; + /** Pixel height of the selected variant when known. */ + height: number | null; + /** True when the selected variant comes from `tile.yn` upscales rather than the base container. */ + fromUpsample: boolean; +} + +/** Strips resource collection prefixes (`media/` or `workflows/`) from an ID value. */ +export function cleanMediaIdKey(value: unknown): string { + if (typeof value === "string") { + return value.trim().replace(/^(?:media|workflows)\//i, ""); + } + if (typeof value === "number" && Number.isFinite(value)) { + return String(value); + } + return ""; +} + +/** Parses an `X-Goog-Date` ISO-8601 basic UTC timestamp (`YYYYMMDDTHHMMSSZ`) into epoch milliseconds. */ +function parseGoogDateMs(raw: string): number | null { + const trimmed = raw.trim(); + const basic = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/i.exec(trimmed); + if (basic) { + const year = Number(basic[1]); + const month = Number(basic[2]); + const day = Number(basic[3]); + const hour = Number(basic[4]); + const minute = Number(basic[5]); + const second = Number(basic[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 parsed = Date.parse(trimmed); + return Number.isFinite(parsed) ? parsed : null; +} + +/** Returns true when `rawUrl` carries an expired GCS V4 (`X-Goog-Date` + `X-Goog-Expires`) or V2 (`Expires`) signature. */ +export function isExpiredSignedUrl( + rawUrl: string | null | undefined, + nowMs = Date.now(), +): boolean { + if (!rawUrl || typeof rawUrl !== "string") return false; + let parsed: URL; + try { + parsed = new URL(rawUrl.trim()); + } catch { + return false; + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + 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) { + const issuedMs = parseGoogDateMs(googDate); + if (issuedMs === null) return true; + if (googExpires !== null) { + const ttlSec = Number(googExpires.trim()); + if (!Number.isFinite(ttlSec) || ttlSec <= 0) return true; + return nowMs + SIGNED_URL_SKEW_MS >= issuedMs + ttlSec * 1000; + } + } + + if (v2Expires !== null && hasV2Sig) { + const rawExp = Number(v2Expires.trim()); + if (!Number.isFinite(rawExp) || rawExp <= 0) return true; + const expMs = rawExp > 1e11 ? rawExp : rawExp * 1000; + return nowMs + SIGNED_URL_SKEW_MS >= expMs; + } + + return false; +} + +/** Returns `rawUrl` when it is a non-empty, non-expired URL string, or null otherwise. */ +export function nonExpiredMediaUrl( + rawUrl: string | null | undefined, + nowMs = Date.now(), +): string | null { + if (!rawUrl || typeof rawUrl !== "string") return null; + return isExpiredSignedUrl(rawUrl, nowMs) ? null : rawUrl; +} + +/** Reads a fresh, non-expired entry from `runtimeState.mediaInfoCache` and evicts stale records. */ +export function getFreshCachedMedia( + rawKey: string | null | undefined, + nowMs = Date.now(), +): CachedMediaInfo | undefined { + if (!rawKey) return undefined; + const exactKey = String(rawKey).trim(); + if (!exactKey) return undefined; + const cleanKey = cleanMediaIdKey(exactKey); + const matchedKey = runtimeState.mediaInfoCache.has(exactKey) + ? exactKey + : cleanKey && runtimeState.mediaInfoCache.has(cleanKey) + ? cleanKey + : null; + if (!matchedKey) return undefined; + + const entry = runtimeState.mediaInfoCache.get(matchedKey); + if (!entry) return undefined; + + if ( + typeof entry.cached_at === "number" && + (!Number.isFinite(entry.cached_at) || nowMs - entry.cached_at >= MEDIA_INFO_TTL_MS) + ) { + runtimeState.mediaInfoCache.delete(matchedKey); + return undefined; + } + + const validCandidates = Array.isArray(entry.candidates) + ? entry.candidates.filter( + (c) => typeof c === "string" && c.length > 0 && !isExpiredSignedUrl(c, nowMs), + ) + : []; + if ( + !entry.url || + isExpiredSignedUrl(entry.url, nowMs) || + (entry.download_url && isExpiredSignedUrl(entry.download_url, nowMs)) || + validCandidates.length === 0 + ) { + runtimeState.mediaInfoCache.delete(matchedKey); + return undefined; + } + + return { + ...entry, + download_url: entry.download_url || entry.url, + candidates: validCandidates, + }; +} + +/** Returns true when `variant` represents a finished, non-failed media item. */ +export function isReadyMediaVariant( + variant: FlowMediaPayload | null | undefined, +): boolean { + if (!variant || typeof variant !== "object") return false; + const uploaded = readOwn(variant, "vp"); + if (uploaded === false) return false; + const normalized = legacyMedia(variant); + const status = normalized?.Zc?.toLowerCase(); + if (normalized?.nf != null && normalized.nf !== "") return false; + if ( + status === "pending" || + status === "scheduled" || + status === "failed" || + status === "canceled" + ) { + return false; + } + const source = readOwn(variant, "source"); + if (source === "GENERATED") { + return status === "success"; + } + return status === undefined || status === "success"; +} + +/** Infers a Flow video resolution code from explicit code, dimensions, or upsample ID suffix. */ +function inferResolutionCode(variant: FlowMediaPayload): number { + if (typeof variant.resolution === "number" && RESOLUTION_PRIORITY[variant.resolution]) { + return variant.resolution; + } + const norm = legacyMedia(variant); + const w = typeof variant.width === "number" ? variant.width : norm?.tc?.width; + const h = typeof variant.height === "number" ? variant.height : norm?.tc?.height; + if (typeof w === "number" && w > 0 && typeof h === "number" && h > 0) { + const shortEdge = Math.min(w, h); + if (shortEdge >= 2000) return 3; + if (shortEdge >= 1000) return 2; + if (shortEdge >= 700) return 1; + return 4; + } + const rawId = String(variant.id ?? variant.mediaId ?? "").toLowerCase(); + if (rawId.includes("4k") || rawId.includes("2160")) return 3; + if (rawId.includes("1080")) return 2; + return 1; +} + +/** Resolves pixel width and height for `variant` using `fallbackAspectRatio` when needed. */ +function resolveVariantDimensions( + variant: FlowMediaPayload, + resCode: number, + fallbackAspectRatio: number, +): { width: number | null; height: number | null } { + const aspect = + typeof variant.aspectRatio === "number" && variant.aspectRatio > 0 + ? variant.aspectRatio + : fallbackAspectRatio; + const computed = videoDimensions(resCode, aspect); + const norm = legacyMedia(variant); + const explicitW = + typeof variant.width === "number" && variant.width > 0 + ? variant.width + : typeof norm?.tc?.width === "number" && norm.tc.width > 0 + ? norm.tc.width + : null; + const explicitH = + typeof variant.height === "number" && variant.height > 0 + ? variant.height + : typeof norm?.tc?.height === "number" && norm.tc.height > 0 + ? norm.tc.height + : null; + + if (explicitW !== null && explicitH !== null) { + const explicitCode = inferResolutionCode({ width: explicitW, height: explicitH }); + if (!computed || explicitCode === resCode || typeof variant.resolution !== "number") { + return { width: explicitW, height: explicitH }; + } + } + if (computed) { + return { width: computed.width, height: computed.height }; + } + return { width: explicitW, height: explicitH }; +} + +/** Reads the upsampled variant array `yn` from `tile` when present. */ +function readUpsampledVariants(tile: FlowTile | null | undefined): FlowMediaPayload[] { + if (!tile || typeof tile !== "object") return []; + const yn = readOwn(tile, "yn"); + return Array.isArray(yn) ? (yn as FlowMediaPayload[]) : []; +} + +/** Selects the highest-resolution ready video variant (`4K` > `1080p` > `720p`) from `tile`. */ +export function selectBestVideoVariant( + rawTile: FlowTile | null | undefined, + nowMs = Date.now(), +): SelectedVideoVariant { + const t = legacyTile(rawTile); + if (!t) { + return { + media: null, + primaryMediaId: null, + url: null, + width: null, + height: null, + fromUpsample: false, + }; + } + + const baseMedia = t.Fb ?? findMediaContainer(t)?.[1] ?? null; + const baseW = + typeof t.width === "number" && t.width > 0 + ? t.width + : typeof baseMedia?.width === "number" && baseMedia.width > 0 + ? baseMedia.width + : typeof baseMedia?.tc?.width === "number" && baseMedia.tc.width > 0 + ? baseMedia.tc.width + : null; + const baseH = + typeof t.height === "number" && t.height > 0 + ? t.height + : typeof baseMedia?.height === "number" && baseMedia.height > 0 + ? baseMedia.height + : typeof baseMedia?.tc?.height === "number" && baseMedia.tc.height > 0 + ? baseMedia.tc.height + : null; + const fallbackAspect = + typeof t.aspectRatio === "number" && t.aspectRatio > 0 + ? t.aspectRatio + : typeof baseMedia?.aspectRatio === "number" && baseMedia.aspectRatio > 0 + ? baseMedia.aspectRatio + : baseW !== null && baseH !== null + ? baseW / baseH + : 16 / 9; + + let bestUpsample: { + media: FlowMediaPayload; + priority: number; + resCode: number; + url: string | null; + } | null = null; + + for (const item of readUpsampledVariants(rawTile ?? t)) { + if (!isReadyMediaVariant(item)) continue; + const resCode = inferResolutionCode(item); + const priority = RESOLUTION_PRIORITY[resCode] ?? 0; + const itemUrl = nonExpiredMediaUrl( + readMediaUrl(item, true) || readMediaUrl(item), + nowMs, + ); + if ( + !bestUpsample || + priority > bestUpsample.priority || + (priority === bestUpsample.priority && itemUrl !== null && bestUpsample.url === null) + ) { + bestUpsample = { media: item, priority, resCode, url: itemUrl }; + } + } + + const baseCode = baseMedia ? inferResolutionCode(baseMedia) : 1; + const basePriority = + baseMedia && isReadyMediaVariant(baseMedia) ? (RESOLUTION_PRIORITY[baseCode] ?? 20) : 0; + + if (bestUpsample && bestUpsample.priority >= basePriority && bestUpsample.priority > 20) { + const norm = legacyMedia({ + ...bestUpsample.media, + aspectRatio: bestUpsample.media.aspectRatio ?? fallbackAspect, + }); + const dims = resolveVariantDimensions(bestUpsample.media, bestUpsample.resCode, fallbackAspect); + const idRaw = bestUpsample.media.id ?? bestUpsample.media.mediaId ?? null; + const mediaId = idRaw != null && String(idRaw).trim() ? String(idRaw).trim() : null; + return { + media: norm ?? bestUpsample.media, + primaryMediaId: mediaId, + url: bestUpsample.url, + width: dims.width, + height: dims.height, + fromUpsample: true, + }; + } + + if (bestUpsample && (!baseMedia || !isReadyMediaVariant(baseMedia))) { + const norm = legacyMedia({ + ...bestUpsample.media, + aspectRatio: bestUpsample.media.aspectRatio ?? fallbackAspect, + }); + const dims = resolveVariantDimensions(bestUpsample.media, bestUpsample.resCode, fallbackAspect); + const idRaw = bestUpsample.media.id ?? bestUpsample.media.mediaId ?? null; + const mediaId = idRaw != null && String(idRaw).trim() ? String(idRaw).trim() : null; + return { + media: norm ?? bestUpsample.media, + primaryMediaId: mediaId, + url: bestUpsample.url, + width: dims.width, + height: dims.height, + fromUpsample: true, + }; + } + + const baseIdRaw = + t.primaryMediaId ?? baseMedia?.id ?? baseMedia?.mediaId ?? t.fb?.mediaId ?? t.mediaId ?? null; + const baseId = baseIdRaw != null && String(baseIdRaw).trim() ? String(baseIdRaw).trim() : null; + const baseUrl = nonExpiredMediaUrl( + readMediaUrl(baseMedia, true) || + readMediaUrl(t, true) || + readMediaUrl(t.fb, true) || + readMediaUrl(baseMedia) || + readMediaUrl(t) || + readMediaUrl(t.fb), + nowMs, + ); + const baseDims = baseMedia + ? resolveVariantDimensions(baseMedia, baseCode, fallbackAspect) + : { width: baseW, height: baseH }; + return { + media: baseMedia, + primaryMediaId: baseId, + url: baseUrl, + width: baseDims.width ?? baseW, + height: baseDims.height ?? baseH, + fromUpsample: false, + }; +} + +/** Returns the highest-resolution non-expired inline URL among ready `tile.yn` variants, or null. */ +export function pickUpsampledTileUrl( + rawTile: FlowTile | null | undefined, + nowMs = Date.now(), +): string | null { + let bestUrl: string | null = null; + let bestPriority = -1; + for (const item of readUpsampledVariants(rawTile)) { + if (!isReadyMediaVariant(item)) continue; + const url = nonExpiredMediaUrl(readMediaUrl(item, true) || readMediaUrl(item), nowMs); + if (!url) continue; + const priority = RESOLUTION_PRIORITY[inferResolutionCode(item)] ?? 0; + if (priority > bestPriority) { + bestPriority = priority; + bestUrl = url; + } + } + return bestUrl; +} + +/** Collects unique media and variant IDs from `primaryMediaId`, `yn`, `history`, and character looks. */ +export function collectTileVariantIds(rawTile: FlowTile | null | undefined): string[] { + if (!rawTile || typeof rawTile !== "object") return []; + const out: string[] = []; + const seen = new Set(); + const addId = (val: unknown): void => { + if (val == null) return; + const raw = String(val).trim(); + if (!raw) return; + if (!seen.has(raw)) { + seen.add(raw); + out.push(raw); + } + const clean = cleanMediaIdKey(raw); + if (clean && !seen.has(clean)) { + seen.add(clean); + out.push(clean); + } + }; + + addId(rawTile.primaryMediaId); + const container = findMediaContainer(rawTile)?.[1]; + addId(container?.id); + addId(container?.mediaId); + addId(rawTile.Fb?.id); + addId(rawTile.Kb?.id); + + for (const item of readUpsampledVariants(rawTile)) { + addId(item?.id); + addId(item?.mediaId); + } + const history = readOwn(rawTile, "history"); + if (Array.isArray(history)) { + for (const item of history) { + if (item && typeof item === "object") { + addId(readOwn(item, "id")); + addId(readOwn(item, "mediaId")); + } + } + } + const looks = characterLooksOf(rawTile); + if (looks) { + for (const entry of looks.values()) { + addId(entry?.primaryMediaId); + addId(entry?.id); + if (Array.isArray(entry?.history)) { + for (const h of entry.history) { + addId(h?.id); + } + } + } + } + return out; +} + +/** Returns trim start, trim end, full duration, and whether `clip` trims its source media. */ +export function sceneClipTrimState(clip: SceneClipItem | null | undefined): { + startSec: number; + endSec: number; + durationSec: number; + trimmed: boolean; +} { + const rawFull = + 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 + : 8; + const rawStart = + typeof clip?.Ji === "number" && Number.isFinite(clip.Ji) + ? clip.Ji + : typeof clip?.Mh === "number" && Number.isFinite(clip.Mh) + ? clip.Mh + : 0; + const startSec = Math.max(0, rawStart); + 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 + : rawFull; + const endSec = Math.min(rawEnd, rawFull); + const trimmed = + endSec > startSec && (startSec > 0 || endSec < rawFull - 0.01); + return { + startSec, + endSec: endSec > startSec ? endSec : rawFull, + durationSec: rawFull, + trimmed, + }; +} + +/** Returns the sole clip when `clips` represents a single-clip untrimmed scene with a primary media ID. */ +export function sceneSingleUntrimmedClip(clips: SceneClipItem[]): SceneClipItem | null { + if (!Array.isArray(clips) || clips.length !== 1) return null; + const first = clips[0]; + if (!first) return null; + const mediaId = cleanMediaIdKey(first.primaryMediaId); + if (!mediaId) return null; + const { trimmed } = sceneClipTrimState(first); + return trimmed ? null : first; +} diff --git a/ts/project_store.ts b/ts/project_store.ts index a161906..deb878b 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -144,19 +144,334 @@ function tileMap(data: unknown, field: string): Map | null { return indexTileRows(readOwn(data, field)); } +/** Returns true when `val` is a plain JSPB sparse field map rather than a Closure message. */ +function isSparsePivot(val: unknown): boolean { + return ( + val !== null && + typeof val === "object" && + !Array.isArray(val) && + Object.getPrototypeOf(val) === Object.prototype && + toSerializedJspb(val) === null + ); +} + +/** Reads a 1-based field from a dense or sparse serialized JSPB message or Closure instance. */ +function protoField(rawMsg: unknown, fieldNumber: number): unknown { + if (fieldNumber < 1 || !rawMsg || typeof rawMsg !== "object") return undefined; + const msg = toSerializedJspb(rawMsg) ?? rawMsg; + if (!Array.isArray(msg)) { + return readOwn(msg, String(fieldNumber)); + } + if (msg.length === 0) return undefined; + const denseIdx = fieldNumber - 1; + const lastIdx = msg.length - 1; + const tail = msg[lastIdx]; + if (isSparsePivot(tail)) { + if (denseIdx < lastIdx && msg[denseIdx] != null) { + return msg[denseIdx]; + } + return readOwn(tail, String(fieldNumber)); + } + return denseIdx <= lastIdx ? msg[denseIdx] : undefined; +} + +/** Extracts a serialized JSPB array from a Closure message instance or array. */ +function toSerializedJspb(value: unknown): unknown[] | null { + if (Array.isArray(value)) return value; + if (!value || typeof value !== "object") return null; + try { + const toJson = (value as { toJSON?: unknown }).toJSON; + if (typeof toJson === "function") { + const res: unknown = toJson.call(value); + if (Array.isArray(res)) return res; + } + } catch { + // Fall through to internal array field inspection. + } + const qf = readOwn(value, "qf"); + return Array.isArray(qf) ? qf : null; +} + +/** Trims a string value and returns null when empty or non-string. */ +function trimmedStr(value: unknown): string | null { + if (typeof value !== "string") return null; + const s = value.trim(); + return s ? s : null; +} + +/** Strips `media/` or `workflows/` prefixes from a resource identifier. */ +function stripResourcePrefix(raw: string): string { + return raw.trim().replace(/^(?:media|workflows)\//i, ""); +} + +/** Converts a protobuf `Timestamp` `[seconds, nanos]` tuple into a `Date`. */ +function parseProtoDate(value: unknown): Date | undefined { + if (value instanceof Date) return value; + const arr = toSerializedJspb(value); + if (!arr) return undefined; + const sec = Number(protoField(arr, 1) ?? 0); + const nanos = Number(protoField(arr, 2) ?? 0); + if (!Number.isFinite(sec) || sec <= 0) return undefined; + const ms = sec * 1000 + (Number.isFinite(nanos) ? Math.floor(nanos / 1e6) : 0); + return Number.isFinite(ms) ? new Date(ms) : undefined; +} + +/** Extracts a workflow display title from an entry in the `lr` map. */ +function readWorkflowTitle(entry: unknown): string | null { + const direct = trimmedStr(entry); + if (direct) return direct; + if (!entry || typeof entry !== "object") return null; + const jspb = toSerializedJspb(entry); + if (jspb) { + const meta = protoField(jspb, 4); + const title = trimmedStr(protoField(meta, 1)) ?? trimmedStr(protoField(jspb, 2)); + if (title) return title; + } + const metaObj = readOwn(entry, "metadata"); + return ( + trimmedStr(readOwn(entry, "displayName")) ?? + trimmedStr(readOwn(entry, "title")) ?? + trimmedStr(readOwn(entry, "name")) ?? + trimmedStr(readOwn(metaObj, "displayName")) ?? + trimmedStr(readOwn(metaObj, "name")) + ); +} + +/** Builds a lookup map of workflow/voice IDs to titles from `lr`. */ +function indexWorkflowTitles(lrRaw: unknown): Map { + const titles = new Map(); + const recordEntry = (rawKey: unknown, rawVal: unknown): void => { + const title = readWorkflowTitle(rawVal); + if (!title) return; + const jspb = toSerializedJspb(rawVal); + const idFromVal = + trimmedStr(jspb ? protoField(jspb, 1) : undefined) ?? + trimmedStr(readOwn(rawVal, "id")) ?? + trimmedStr(readOwn(rawVal, "name")); + for (const candidate of [trimmedStr(rawKey), idFromVal]) { + if (!candidate) continue; + titles.set(candidate, title); + const clean = stripResourcePrefix(candidate); + if (clean) titles.set(clean, title); + } + }; + + if (lrRaw instanceof Map) { + for (const [k, v] of lrRaw.entries()) recordEntry(k, v); + } else if (Array.isArray(lrRaw)) { + for (const v of lrRaw) recordEntry(undefined, v); + } else if (lrRaw && typeof lrRaw === "object") { + for (const [k, v] of Object.entries(lrRaw as Record)) { + recordEntry(k, v); + } + } + return titles; +} + +/** Reads the assigned voice reference string from a character tile when present. */ +function readCharacterVoiceRef(tile: FlowTile): string | null { + const entity = readOwn(tile, "Rc"); + const jspb = toSerializedJspb(entity); + if (jspb) { + const charInfo = protoField(protoField(jspb, 4), 3); + const refs = protoField(charInfo, 2); + if (Array.isArray(refs) && refs.length > 0) { + const first = refs[0]; + const custom = trimmedStr(protoField(first, 1)); + if (custom) return stripResourcePrefix(custom); + const preset = trimmedStr(protoField(first, 2)); + if (preset) return preset; + } + } + const direct = + trimmedStr(tile.voiceId) ?? + trimmedStr(tile.Vo) ?? + trimmedStr(tile.voice); + return direct ? stripResourcePrefix(direct) : null; +} + +/** Merges custom voices from `cj` and titles from `lr` into a copy of `baseTiles`. */ +function mergeProjectVoices( + baseTiles: Map, + rawData: unknown, +): Map { + if (!rawData || typeof rawData !== "object") return baseTiles; + const cjRaw = readOwn(rawData, "cj"); + const lrRaw = readOwn(rawData, "lr"); + if (!cjRaw && !lrRaw) return baseTiles; + + const lrTitles = indexWorkflowTitles(lrRaw); + const entries: Array<[unknown, unknown]> = []; + if (cjRaw instanceof Map) { + for (const pair of cjRaw.entries()) entries.push(pair); + } else if (Array.isArray(cjRaw)) { + for (const item of cjRaw) entries.push([undefined, item]); + } else if (cjRaw && typeof cjRaw === "object") { + for (const pair of Object.entries(cjRaw as Record)) { + entries.push(pair); + } + } + if (entries.length === 0) return baseTiles; + + const merged = new Map(baseTiles); + const existingWorkflowIds = new Set(); + for (const tile of merged.values()) { + const wf = trimmedStr(tile.workflowId); + if (wf) existingWorkflowIds.add(stripResourcePrefix(wf)); + const pm = trimmedStr(tile.primaryMediaId); + if (pm) existingWorkflowIds.add(stripResourcePrefix(pm)); + } + + const voiceByRef = new Map(); + + for (const [rawKey, mediaVal] of entries) { + if (!mediaVal || typeof mediaVal !== "object") continue; + const jspb = toSerializedJspb(mediaVal); + let mediaId: string | null = null; + let workflowId: string | null = null; + let title: string | null = null; + let promptText: string | null = null; + let inlineUrl: string | null = null; + let createdAt: Date | undefined; + + if (jspb) { + const audioBranch = protoField(jspb, 11); + if (!audioBranch || typeof audioBranch !== "object") continue; + const rawId = trimmedStr(protoField(jspb, 1)) ?? trimmedStr(rawKey); + if (!rawId || /^voices\//i.test(rawId)) continue; + const audioMeta = protoField(audioBranch, 1); + if (protoField(audioMeta, 3) === true) continue; + + mediaId = stripResourcePrefix(rawId); + const rawWf = trimmedStr(protoField(jspb, 3)); + workflowId = rawWf ? stripResourcePrefix(rawWf) : null; + + const mediaMeta = protoField(jspb, 6); + createdAt = parseProtoDate(protoField(mediaMeta, 1)); + const labels = protoField(audioMeta, 12); + const firstLabel = Array.isArray(labels) && labels.length > 0 ? labels[0] : undefined; + title = + (rawWf ? lrTitles.get(rawWf) : undefined) ?? + (workflowId ? lrTitles.get(workflowId) : undefined) ?? + lrTitles.get(rawId) ?? + lrTitles.get(mediaId) ?? + trimmedStr(protoField(mediaMeta, 2)) ?? + trimmedStr(protoField(firstLabel, 2)) ?? + trimmedStr(protoField(firstLabel, 1)) ?? + trimmedStr(protoField(audioMeta, 5)) ?? + "Custom voice"; + promptText = + trimmedStr(protoField(audioMeta, 8)) ?? + trimmedStr(protoField(audioMeta, 2)) ?? + trimmedStr(protoField(audioMeta, 7)); + inlineUrl = + trimmedStr(protoField(audioMeta, 4)) ?? + trimmedStr(protoField(audioMeta, 6)); + } else { + const rawType = String(readOwn(mediaVal, "type") ?? readOwn(mediaVal, "kind") ?? "").toUpperCase(); + const rawMime = String(readOwn(mediaVal, "mimeType") ?? "").toLowerCase(); + const hasAudioShape = + rawType === "VOICE" || + rawType === "AUDIO" || + rawMime.startsWith("audio/") || + readOwn(mediaVal, "audio") != null || + readOwn(mediaVal, "voice") != null || + (rawType === "" && + readOwn(mediaVal, "image") == null && + readOwn(mediaVal, "video") == null); + if (!hasAudioShape) continue; + if (readOwn(mediaVal, "isPreset") === true || readOwn(mediaVal, "Rv") === true) continue; + const rawId = + trimmedStr(readOwn(mediaVal, "id")) ?? + trimmedStr(readOwn(mediaVal, "mediaId")) ?? + trimmedStr( readOwn(mediaVal, "name")) ?? + trimmedStr(rawKey); + if (!rawId || /^voices\//i.test(rawId)) continue; + mediaId = stripResourcePrefix(rawId); + const rawWf = trimmedStr(readOwn(mediaVal, "workflowId")); + workflowId = rawWf ? stripResourcePrefix(rawWf) : null; + title = + trimmedStr(readOwn(mediaVal, "displayName")) ?? + trimmedStr(readOwn(mediaVal, "title")) ?? + (rawWf ? lrTitles.get(rawWf) : undefined) ?? + (workflowId ? lrTitles.get(workflowId) : undefined) ?? + lrTitles.get(rawId) ?? + lrTitles.get(mediaId) ?? + trimmedStr(readOwn(mediaVal, "name")) ?? + "Custom voice"; + promptText = + trimmedStr(readOwn(mediaVal, "prompt")) ?? + trimmedStr(readOwn(mediaVal, "description")); + inlineUrl = + trimmedStr(readOwn(mediaVal, "url")) ?? + trimmedStr(readOwn(mediaVal, "kc")) ?? + trimmedStr(readOwn(mediaVal, "fifeUrl")); + const rawDate = readOwn(mediaVal, "lc") ?? readOwn(mediaVal, "hc"); + if (rawDate instanceof Date) createdAt = rawDate; + } + + if (!mediaId) continue; + const resolvedTitle = title || "Custom voice"; + voiceByRef.set(mediaId, { mediaId, title: resolvedTitle }); + if (workflowId) { + voiceByRef.set(workflowId, { mediaId, title: resolvedTitle }); + } + + if ( + merged.has(mediaId) || + existingWorkflowIds.has(mediaId) || + (workflowId !== null && (merged.has(workflowId) || existingWorkflowIds.has(workflowId))) + ) { + continue; + } + + const synthesized: FlowTile = { + id: mediaId, + workflowId: workflowId ?? mediaId, + primaryMediaId: mediaId, + displayName: resolvedTitle, + type: "VOICE", + ...(inlineUrl ? { kc: inlineUrl, url: inlineUrl } : {}), + ...(promptText ? { prompt: promptText } : {}), + ...(createdAt ? { hc: createdAt } : {}), + }; + merged.set(mediaId, synthesized); + } + + if (voiceByRef.size > 0) { + for (const [id, tile] of merged.entries()) { + if (String(tile?.type ?? "").toUpperCase() !== "CHARACTER") continue; + const ref = readCharacterVoiceRef(tile); + if (!ref) continue; + const hit = voiceByRef.get(ref); + if (!hit) continue; + merged.set(id, { + ...tile, + voiceMediaId: hit.mediaId, + ...(tile.voiceName == null ? { voiceName: hit.title } : {}), + }); + } + } + + return merged; +} + /** 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; const query = projectQuery(store); + const rawQueryData = query?.state.data; if (query) { - const cached = tileMap(query.state.data, store.format.rows); - if (cached) return cached; + const cached = tileMap(rawQueryData, store.format.rows); + if (cached) return mergeProjectVoices(cached, rawQueryData); } const signalQuery = readOwn(store.service, store.format.tileQuery); if (!signalQuery || typeof signalQuery !== "object" || !("data" in signalQuery)) return null; const readData = readOwn(signalQuery, "data"); const signalData: unknown = typeof readData === "function" ? readData.call(signalQuery) : readData; - return indexTileRows(signalData) ?? tileMap(signalData, store.format.rows); + const indexed = indexTileRows(signalData) ?? tileMap(signalData, store.format.rows); + if (!indexed) return null; + return mergeProjectVoices(indexed, rawQueryData ?? signalData); } /** Returns the bound store only when the project and runtime session match. */ diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 67e6de1..2d4f281 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -6,6 +6,15 @@ import { readOwn } from "./angular"; import { characterPersonalityNotes, characterVoice } from "./character_bio"; import { activeProjectStoreFormat, snapshotFormat } from "./frontend_builds"; +import { + cleanMediaIdKey, + collectTileVariantIds, + getFreshCachedMedia, + nonExpiredMediaUrl, + sceneClipTrimState, + sceneSingleUntrimmedClip, + selectBestVideoVariant, +} from "./media_variants"; import { currentProjectStore, projectInRoute } from "./project_store"; import { sceneContents } from "./scene_tiles"; import { @@ -314,51 +323,92 @@ export function readStoreTiles(tileMap: Map): { } const charMedia = baseKind === "character" ? characterLookMedia(t) : { url: null, primaryMediaId: null }; - const charFallbackUrl = charMedia.url; + const charFallbackUrl = nonExpiredMediaUrl(charMedia.url); const charLookPrimaryMediaId = charMedia.primaryMediaId; - const videoMediaUrl = - baseKind === "video" - ? readMediaUrl(t.Fb, true) || - readMediaUrl(t, true) || - 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 sceneData = baseKind === "scene" ? sceneContents(rawTile) : null; + const singleSceneClip = sceneData ? sceneSingleUntrimmedClip(sceneData.clips) : null; + const singleSceneMediaId = singleSceneClip + ? cleanMediaIdKey(singleSceneClip.primaryMediaId) || String(singleSceneClip.primaryMediaId) + : null; + const singleSceneHist = + singleSceneClip && sceneData && singleSceneClip.workflowId != null + ? sceneData.history.get(String(singleSceneClip.workflowId)) + : undefined; + const singleSceneMedia = legacyMedia( + Array.isArray(singleSceneHist) + ? singleSceneHist.find((x) => x && cleanMediaIdKey(x.id) === singleSceneMediaId) || + singleSceneHist[0] || + null + : null, + ); + + const bestVideo = baseKind === "video" ? selectBestVideoVariant(rawTile) : null; + const videoMediaUrl = bestVideo ? bestVideo.url : null; + + const selectedStatusSource = + baseKind === "video" && bestVideo?.media + ? bestVideo.media + : baseKind === "scene" && singleSceneMedia + ? singleSceneMedia + : null; + const mediaStatus = String( + selectedStatusSource?.Zc ?? t.Fb?.Zc ?? t.fb?.Zc ?? t.Zc ?? "", + ).toLowerCase(); + const mediaError = formatMediaError( + selectedStatusSource?.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(selectedStatusSource?.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" + ? singleSceneMediaId + : baseKind === "video" + ? bestVideo?.primaryMediaId ?? null + : charLookPrimaryMediaId || + t.primaryMediaId || + t.Fb?.id || + t.Fb?.mediaId || + t.fb?.mediaId || + t.mediaId || + null; const cachedEntry = primaryMediaId - ? runtimeState.mediaInfoCache.get(String(primaryMediaId)) + ? getFreshCachedMedia(String(primaryMediaId)) : undefined; const kind = 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 = nonExpiredMediaUrl(asHttpOrDataUrl(cachedEntry?.url)); + + const singleSceneUrl = singleSceneClip + ? nonExpiredMediaUrl( + readMediaUrl(singleSceneMedia, true) || + readMediaUrl(singleSceneClip, true) || + readMediaUrl(singleSceneMedia) || + readMediaUrl(singleSceneClip), + ) + : null; + + const tileMediaUrl = + baseKind === "scene" + ? singleSceneUrl + : baseKind === "video" + ? videoMediaUrl + : baseKind === "character" && charLookPrimaryMediaId + ? charFallbackUrl + : nonExpiredMediaUrl( + readMediaUrl(t.Fb) || + readMediaUrl(t) || + readMediaUrl(t.fb) || + charFallbackUrl, + ); const rawMediaUrl = isSignedUrlStr(tileMediaUrl) ? tileMediaUrl : isSignedUrlStr(cachedMediaUrl) @@ -390,6 +440,17 @@ export function readStoreTiles(tileMap: Map): { const { start: trimStart, end: trimEnd } = videoTrimBounds(t); + const sceneClipDurationTotal = + sceneData && sceneData.clips.length > 0 + ? sceneData.clips.reduce((acc, clip) => { + const { startSec, endSec } = sceneClipTrimState(clip); + return acc + Math.max(0, endSec - startSec); + }, 0) + : null; + const variantIds = baseKind === "scene" ? [] : collectTileVariantIds(rawTile); + const mediaKindHint = + cachedEntry?.media_kind ?? (kind === "audio" ? "audio" : null); + const topEntry: Omit = { id: tid, name: tname, @@ -400,10 +461,17 @@ export function readStoreTiles(tileMap: Map): { ? String(t.fb.prompt) : t.prompt ? String(t.prompt) - : null, - url: mediaUrl ? normalizeFlowMediaUrl(String(mediaUrl), kind, env) : null, + : singleSceneMedia?.prompt + ? String(singleSceneMedia.prompt) + : null, + url: mediaUrl + ? normalizeFlowMediaUrl(String(mediaUrl), kind === "scene" ? "video" : kind, env) + : null, collection_id: cid, primary_media_id: primaryMediaId ? String(primaryMediaId) : null, + ...(variantIds.length > 0 ? { variant_ids: variantIds } : {}), + ...(mediaKindHint ? { media_kind_hint: mediaKindHint } : {}), + ...(cachedEntry?.pcm_audio ? { pcm_audio: true } : {}), personality_notes: bio == null ? null : String(bio), voice: voiceRaw != null ? voiceRaw : null, trim_start_seconds: trimStart, @@ -411,25 +479,33 @@ 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" && bestVideo + ? bestVideo.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 + : typeof singleSceneMedia?.tc?.width === "number" + ? singleSceneMedia.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, + baseKind === "video" && bestVideo + ? bestVideo.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 + : typeof singleSceneMedia?.tc?.height === "number" + ? singleSceneMedia.tc.height + : null, duration: typeof t.durationSeconds === "number" ? t.durationSeconds @@ -443,7 +519,7 @@ export function readStoreTiles(tileMap: Map): { ? t.Fb.Lf : typeof t.Lf === "number" ? t.Lf - : null, + : sceneClipDurationTotal, created_at: t.hc instanceof Date ? t.hc.toISOString() @@ -516,17 +592,18 @@ export function readStoreTiles(tileMap: Map): { : mObj?.id ? String(mObj.id) : null; - const cachedClipVideoUrl = clipPrimaryMediaId - ? asHttpOrDataUrl( - runtimeState.mediaInfoCache.get(clipPrimaryMediaId)?.url, - ) - : null; - const tileClipUrl = + const cachedClipEntry = clipPrimaryMediaId + ? getFreshCachedMedia(clipPrimaryMediaId) + : undefined; + const cachedClipVideoUrl = nonExpiredMediaUrl( + asHttpOrDataUrl(cachedClipEntry?.url), + ); + const tileClipUrl = nonExpiredMediaUrl( readMediaUrl(mObj, true) || - readMediaUrl(clip, true) || - readMediaUrl(mObj) || - readMediaUrl(clip) || - null; + readMediaUrl(clip, true) || + readMediaUrl(mObj) || + readMediaUrl(clip), + ); const rawClipUrl = isSignedUrlStr(tileClipUrl) ? tileClipUrl : isSignedUrlStr(cachedClipVideoUrl) diff --git a/ts/resolve_video_url.ts b/ts/resolve_video_url.ts index 403b2bc..17b9d14 100644 --- a/ts/resolve_video_url.ts +++ b/ts/resolve_video_url.ts @@ -5,6 +5,7 @@ import { fifeEnv as getFifeEnv } from "./dom"; import { readBuildLabel } from "./frontend_builds"; +import { getFreshCachedMedia, isExpiredSignedUrl } from "./media_variants"; import { runtimeState } from "./state"; import type { ResolvedMediaResult } from "./types"; @@ -27,6 +28,8 @@ interface MediaExtractState { unsignedCandidates: string[]; /** Media family from the wire message. */ mediaKind: ResolvedMediaKind | null; + /** True when case `11` audio resolved raw 24 kHz PCM bytes. */ + pcmAudio: boolean; } /** Returns true when `val` is a plain sparse JSPB field map object. */ @@ -76,27 +79,30 @@ export async function resolveVideoUrl( return { ok: false, error: "missing_wiz_or_media_id" }; } - 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: - typeof cachedInfo.download_url === "string" && - /^https?:\/\//i.test(cachedInfo.download_url) - ? cachedInfo.download_url - : cachedInfo.url, - candidates: cachedInfo.candidates.slice(), - ...(cachedInfo.media_kind ? { media_kind: cachedInfo.media_kind } : {}), - }; + if (bypassCache) { + runtimeState.mediaInfoCache.delete(cacheKey); + } else { + const cachedInfo = getFreshCachedMedia(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: + typeof cachedInfo.download_url === "string" && + /^https?:\/\//i.test(cachedInfo.download_url) + ? cachedInfo.download_url + : cachedInfo.url, + candidates: cachedInfo.candidates.slice(), + ...(cachedInfo.media_kind ? { media_kind: cachedInfo.media_kind } : {}), + ...(cachedInfo.pcm_audio ? { pcm_audio: true } : {}), + }; + } } const { fifeHost, authuser, isSignedCdnHost } = getFifeEnv(); @@ -167,10 +173,12 @@ export async function resolveVideoUrl( } }; - const recordSigned = (state: MediaExtractState, direct: string): void => { + const recordSigned = (state: MediaExtractState, direct: string): boolean => { + if (isExpiredSignedUrl(direct)) return false; pushCandidate(state.signedCandidates, direct); state.signedDownloadUrl ||= direct; state.signedStreamUrl ||= direct; + return true; }; const hasExtractedUrls = (state: MediaExtractState): boolean => @@ -316,9 +324,10 @@ export async function resolveVideoUrl( !(a6Case1 && isSignedUrl(a6Case1)), ); - const a1 = jspbField(audio, 1); + const a1 = jspbField(audio, 1); const a2 = jspbField(audio, 2); const a5 = jspbField(audio, 5); + let addedCase11Audio = false; for (const rawAudio of [ a6Case2, a6Case3, @@ -347,7 +356,9 @@ export async function resolveVideoUrl( const direct = asDirectUrl(rawAudio); if (!direct) continue; if (isSignedUrl(direct)) { - recordSigned(state, direct); + if (recordSigned(state, direct)) { + addedCase11Audio = true; + } } else { const rewritten = proxyActive ? rewriteFifeUrl(direct, null, true) || direct @@ -358,9 +369,13 @@ export async function resolveVideoUrl( } state.unsignedDownloadUrl ||= rewritten; state.unsignedStreamUrl ||= rewritten; + addedCase11Audio = true; } } - if (hasExtractedUrls(state)) { + if (addedCase11Audio) { + state.mediaKind ||= "audio"; + state.pcmAudio = true; + } else if (hasExtractedUrls(state)) { state.mediaKind ||= "audio"; } } @@ -444,6 +459,7 @@ export async function resolveVideoUrl( unsignedDownloadUrl: null, unsignedCandidates: [], mediaKind: null, + pcmAudio: false, }; let lastErr = await fetchAs29s([cacheKey, null, [1]], state); if ( @@ -484,6 +500,8 @@ export async function resolveVideoUrl( download_url: finalDl, candidates: candidates.slice(), ...(state.mediaKind ? { media_kind: state.mediaKind } : {}), + ...(state.pcmAudio ? { pcm_audio: true } : {}), + cached_at: Date.now(), }); 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..8021f4a --- /dev/null +++ b/ts/scene_export.ts @@ -0,0 +1,335 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Export multi-clip or trimmed scenes via GjQLTd and IxdSwd batchexecute RPCs. + +import { readBuildLabel } from "./frontend_builds"; +import { cleanMediaIdKey, sceneClipTrimState } from "./media_variants"; +import { sceneContents } from "./scene_tiles"; +import { runtimeState } from "./state"; +import type { SceneExportRequest, SceneExportResult } from "./types"; + +/** Staged scene export job token awaiting `IxdSwd` completion. */ +interface PendingSceneExport { + /** Raw JSPB operation token returned at field `2` of `GjQLTd`. */ + opToken: unknown; + /** Timestamp when the job started in epoch milliseconds. */ + createdAt: number; +} + +/** Revocation delay for staged MP4 `blob:` URLs in milliseconds (5 minutes). */ +const STAGED_BLOB_TTL_MS = 5 * 60 * 1000; + +/** Retention limit for unfinished export handles in milliseconds (10 minutes). */ +const PENDING_EXPORT_TTL_MS = 10 * 60 * 1000; + +/** Active scene export operation handles keyed by generated `export_id`. */ +const pendingExports = new Map(); + +/** Staged `blob:` URL cleanup timers keyed by object URL. */ +const stagedBlobTimers = new Map>(); + +/** Monotonic counter for local `export_id` keys. */ +let nextExportSeq = 1; + +/** Returns true when `val` is a plain sparse JSPB field map object. */ +function isSparseMap(val: unknown): val is Record { + return val !== null && typeof val === "object" && !Array.isArray(val); +} + +/** Reads 1-based protobuf `fieldNumber` from a dense JSPB array or trailing sparse map. */ +function jspbField(msg: unknown, fieldNumber: number): unknown { + if (fieldNumber < 1) return undefined; + if (isSparseMap(msg)) { + return msg[String(fieldNumber)]; + } + if (!Array.isArray(msg) || msg.length === 0) { + return undefined; + } + const denseIdx = fieldNumber - 1; + const lastIdx = msg.length - 1; + const tail = msg[lastIdx]; + if (isSparseMap(tail)) { + if (denseIdx < lastIdx && msg[denseIdx] != null) { + return msg[denseIdx]; + } + return tail[String(fieldNumber)]; + } + return denseIdx <= lastIdx ? msg[denseIdx] : undefined; +} + +/** Encodes a `google.protobuf.Duration` value in seconds into its Closure JSPB array layout. */ +function encodeDurationJspb(secondsValue: number): Array { + if (!Number.isFinite(secondsValue) || secondsValue === 0) { + return []; + } + const sign = secondsValue < 0 ? -1 : 1; + const abs = Math.abs(secondsValue); + let whole = Math.floor(abs); + let nanos = Math.round((abs - whole) * 1e9); + if (nanos >= 1e9) { + whole += 1; + nanos -= 1e9; + } + const signedSec = whole === 0 ? 0 : sign * whole; + const signedNanos = nanos === 0 ? 0 : sign * nanos; + if (signedNanos === 0) { + return signedSec === 0 ? [] : [signedSec]; + } + return [signedSec === 0 ? null : signedSec, signedNanos]; +} + +/** Decodes a standard or URL-safe Base64 string (or byte array) into a `Uint8Array`. */ +function decodeProtoBytes(raw: unknown): Uint8Array | null { + if (raw instanceof Uint8Array) { + return raw.byteLength > 0 ? raw : null; + } + if (Array.isArray(raw) && raw.every((n) => typeof n === "number")) { + return raw.length > 0 ? new Uint8Array(raw) : null; + } + if (typeof raw !== "string" || raw.length === 0) { + return null; + } + const normalized = raw.replace(/-/g, "+").replace(/_/g, "/").replace(/\s+/g, ""); + const padLen = (4 - (normalized.length % 4)) % 4; + const padded = normalized + "=".repeat(padLen); + try { + const binary = atob(padded); + if (binary.length === 0) return null; + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes; + } catch { + return null; + } +} + +/** Stages MP4 bytes in a browser `Blob` URL and schedules automatic revocation. */ +function stageMp4Blob(bytes: Uint8Array): string { + const copy = new Uint8Array(bytes.byteLength); + copy.set(bytes); + const blob = new Blob([copy], { type: "video/mp4" }); + const blobUrl = URL.createObjectURL(blob); + const timer = setTimeout(() => { + stagedBlobTimers.delete(blobUrl); + URL.revokeObjectURL(blobUrl); + }, STAGED_BLOB_TTL_MS); + stagedBlobTimers.set(blobUrl, timer); + return blobUrl; +} + +/** Releases a previously staged `blob:` URL immediately. */ +function releaseStagedBlob(blobUrl: string): void { + const timer = stagedBlobTimers.get(blobUrl); + if (timer !== undefined) { + clearTimeout(timer); + stagedBlobTimers.delete(blobUrl); + } + if (blobUrl.startsWith("blob:")) { + URL.revokeObjectURL(blobUrl); + } +} + +/** Prunes expired operation handles from `pendingExports`. */ +function pruneExpiredHandles(nowMs = Date.now()): void { + for (const [key, item] of pendingExports.entries()) { + if (nowMs - item.createdAt >= PENDING_EXPORT_TTL_MS) { + pendingExports.delete(key); + } + } +} + +/** Executes one `batchexecute` RPC and returns the parsed `wrb.fr` payload array. */ +async function callBatchExecuteRpc( + rpcId: string, + innerArgs: unknown[], + timeoutMs: number, +): Promise<{ ok: true; proto: unknown } | { ok: false; error: string }> { + const wiz = window.WIZ_global_data || {}; + const at = typeof wiz.SNlM0e === "string" ? wiz.SNlM0e : ""; + const sid = typeof wiz.FdrFJe === "string" ? wiz.FdrFJe : ""; + const bl = readBuildLabel() ?? (typeof wiz.cfb2h === "string" ? wiz.cfb2h : ""); + if (!at) { + return { ok: false, error: "missing_wiz_token" }; + } + + const reqPayload = JSON.stringify([ + [[rpcId, JSON.stringify(innerArgs), null, "generic"]], + ]); + const params = new URLSearchParams({ + rpcids: rpcId, + "source-path": location.pathname || "/", + bl, + "f.sid": sid, + hl: "en", + rt: "c", + }); + const body = `f.req=${encodeURIComponent(reqPayload)}&at=${encodeURIComponent(at)}`; + try { + const resp = await fetch( + `/_/AiSandboxAngularFrontend/data/batchexecute?${params.toString()}`, + { + method: "POST", + credentials: "include", + signal: AbortSignal.timeout(timeoutMs), + headers: { + "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", + }, + body, + }, + ); + if (!resp.ok) { + return { ok: false, error: `http_${resp.status}` }; + } + const text = await resp.text(); + for (const line of text.split(/\r?\n/)) { + if (!line.startsWith("[")) continue; + let entries: unknown; + try { + entries = JSON.parse(line); + } catch { + continue; + } + if (!Array.isArray(entries)) continue; + for (const entry of entries) { + if ( + Array.isArray(entry) && + entry[0] === "wrb.fr" && + entry[1] === rpcId && + typeof entry[2] === "string" + ) { + try { + return { ok: true, proto: JSON.parse(entry[2]) }; + } catch { + return { ok: false, error: "invalid_rpc_proto_json" }; + } + } + } + } + return { ok: false, error: `empty_${rpcId}_response` }; + } catch (err) { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + }; + } +} + +/** Inspects an `IxdSwd` response message and stages state `3` MP4 bytes as a `blob:` URL. */ +function interpretExportPollProto( + exportId: string, + proto: unknown, +): SceneExportResult { + const rawState = jspbField(proto, 1); + const state = typeof rawState === "number" ? rawState : Number(rawState ?? 0); + if (state === 3) { + pendingExports.delete(exportId); + const rawBytes = jspbField(proto, 5); + const bytes = decodeProtoBytes(rawBytes); + if (!bytes || bytes.byteLength === 0) { + return { ok: false, error: "scene_export_empty_mp4" }; + } + const blobUrl = stageMp4Blob(bytes); + return { ok: true, status: "ready", blob_url: blobUrl }; + } + if (state === 1 || state === 2 || state === 6) { + return { ok: true, status: "pending", export_id: exportId }; + } + pendingExports.delete(exportId); + return { + ok: false, + error: `scene_export_failed_state_${String(state)}`, + }; +} + +/** Starts, polls, or releases a Google Flow scene MP4 export over `batchexecute`. */ +export async function exportScene( + req: SceneExportRequest, +): Promise { + pruneExpiredHandles(); + const action = req?.action ?? "start"; + const rpcTimeoutMs = + typeof req?.timeout_ms === "number" && req.timeout_ms > 0 + ? req.timeout_ms + : 10_000; + + if (action === "release") { + if (typeof req.blob_url === "string" && req.blob_url) { + releaseStagedBlob(req.blob_url); + } + if (typeof req.export_id === "string" && req.export_id) { + pendingExports.delete(req.export_id); + } + return { ok: true, status: "released" }; + } + + if (action === "poll") { + const exportId = typeof req.export_id === "string" ? req.export_id.trim() : ""; + const pending = exportId ? pendingExports.get(exportId) : undefined; + if (!pending) { + return { ok: false, error: "unknown_scene_export_id" }; + } + const pollRes = await callBatchExecuteRpc("IxdSwd", [pending.opToken], rpcTimeoutMs); + if (!pollRes.ok) { + return pollRes; + } + return interpretExportPollProto(exportId, pollRes.proto); + } + + if (action !== "start") { + return { ok: false, error: "unknown_scene_export_action" }; + } + + const sceneId = typeof req.scene_id === "string" ? req.scene_id.trim() : ""; + if (!sceneId) { + return { ok: false, error: "missing_scene_id" }; + } + const tileMap = runtimeState.store?.getTileMap(); + if (!(tileMap instanceof Map)) { + return { ok: false, error: "store_not_bound" }; + } + const tile = + tileMap.get(sceneId) ?? + Array.from(tileMap.values()).find((t) => String(t?.id ?? "") === sceneId); + if (!tile) { + return { ok: false, error: "scene_not_found" }; + } + + const { clips } = sceneContents(tile); + if (clips.length === 0) { + return { ok: false, error: "scene_has_no_clips" }; + } + + const clipSpecs: unknown[] = []; + for (const clip of clips) { + const mediaId = cleanMediaIdKey(clip?.primaryMediaId); + if (!mediaId) { + return { ok: false, error: "scene_clip_missing_media_id" }; + } + const { startSec, endSec } = sceneClipTrimState(clip); + clipSpecs.push([ + mediaId, + null, + encodeDurationJspb(startSec), + encodeDurationJspb(endSec), + ]); + } + + const startRes = await callBatchExecuteRpc("GjQLTd", [clipSpecs], rpcTimeoutMs); + if (!startRes.ok) { + return startRes; + } + const opToken = jspbField(startRes.proto, 2); + if (opToken == null || (!Array.isArray(opToken) && !isSparseMap(opToken))) { + return { ok: false, error: "missing_scene_export_token" }; + } + + const exportId = `scene-export-${Date.now()}-${nextExportSeq++}`; + pendingExports.set(exportId, { + opToken, + createdAt: Date.now(), + }); + return { ok: true, status: "pending", export_id: exportId }; +} diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..e2a365c 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -90,8 +90,8 @@ export interface FlowMediaPayload { voice?: unknown; /** Trim start timestamp in seconds. */ Ac?: number; - /** Alternative trim start timestamp in seconds. */ - Cg?: number; + /** Alternative trim start timestamp in seconds, or scene clip history map in build 20261120.00. */ + Cg?: number | Map | Record; /** Trim end timestamp in seconds. */ Ic?: number; /** Alternative trim end timestamp in seconds. */ @@ -242,6 +242,8 @@ export interface FlowTile extends FlowMediaPayload { voiceName?: unknown; /** Attached voice identifier. */ voiceId?: unknown; + /** Resolved custom voice media identifier on look-less character tiles. */ + voiceMediaId?: string; /** Minified voice descriptor. */ Vo?: unknown; /** Audio voice references list. */ @@ -254,8 +256,14 @@ export interface FlowTile extends FlowMediaPayload { createTime?: string; /** Scene clip array. */ Oc?: SceneClipItem[]; + /** Scene clip array in build 20261120.00. */ + Uc?: SceneClipItem[]; /** Scene clip workflow history lookup. */ Yf?: Map | Record; + /** Generation history items on media tiles. */ + history?: FlowMediaPayload[]; + /** Upsampled video variants (`1080p` and `4K`) in build 20261120.00. */ + yn?: FlowMediaPayload[]; /** Tile width alias. */ width?: number; /** Tile height alias. */ @@ -486,6 +494,10 @@ 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 bytes. */ + pcm_audio?: boolean; + /** Epoch timestamp in milliseconds when the entry entered the cache. */ + cached_at?: number; } /** Result returned by `checkAuth`. */ @@ -534,6 +546,12 @@ export interface SnapshotAssetItem { collection_name: string | null; /** Primary media identifier. */ primary_media_id: string | null; + /** Additional variant and history media identifiers associated with this tile. */ + variant_ids?: string[]; + /** Cached wire media family hint (`video`, `image`, or `audio`) when known. */ + media_kind_hint?: "video" | "image" | "audio" | null; + /** True when cached media resolution flagged raw 24 kHz PCM audio bytes. */ + pcm_audio?: boolean; /** Character personality notes. */ personality_notes: string | null; /** Assigned voice name or identifier. */ @@ -615,8 +633,30 @@ export type ResolvedMediaResult = download_url: string; candidates: string[]; media_kind?: "video" | "image" | "audio"; + pcm_audio?: boolean; }; +/** Request payload for `exportScene`. */ +export interface SceneExportRequest { + /** Operation (`start`, `poll`, or `release`). */ + action?: "start" | "poll" | "release"; + /** Scene tile identifier for `start`. */ + scene_id?: string | null; + /** Pending export operation handle for `poll` or `release`. */ + export_id?: string | null; + /** Staged `blob:` URL to revoke for `release`. */ + blob_url?: string | null; + /** Optional per-RPC timeout in milliseconds. */ + timeout_ms?: number | null; +} + +/** Result returned by `exportScene`. */ +export type SceneExportResult = + | { ok: false; error: string } + | { ok: true; status: "pending"; export_id: string } + | { ok: true; status: "ready"; blob_url: string } + | { ok: true; status: "released" }; + /** Configuration payload shared by `setupGeneration` and `attachIngredients`. */ export interface GenerationConfig { /** Generation mode (`video`, `image`, `character`, or `scene`). */ @@ -851,6 +891,8 @@ export interface FlowMcpRuntime { submitGeneration: () => Promise; /** Creates Flow scenes and adds clips. */ sceneOp: (req: SceneOpRequest) => Promise; + /** Starts, polls, or releases a scene MP4 export via `GjQLTd` and `IxdSwd`. */ + exportScene: (req: SceneExportRequest) => Promise; /** Applies video trim timestamps or drives the scene builder extend workflow. */ videoOp: (req: VideoOpRequest) => Promise; /** Opens/exits the character editor and creates or updates character fields. */