diff --git a/package.json b/package.json index 1bd964f..09aff8c 100644 --- a/package.json +++ b/package.json @@ -73,7 +73,7 @@ "tinycolor2": "^1.6.0", "undo-redo-manager2": "^1.0.0", "use-fs-access": "^1.3.2", - "video-core-sdk": "1.0.64", + "video-core-sdk": "1.0.70", "xlsx": "^0.18.5" }, "optionalDependencies": { diff --git a/qrcode.jpg b/qrcode.jpg index 34458ee..193e308 100644 Binary files a/qrcode.jpg and b/qrcode.jpg differ diff --git a/src/language/enUS.ts b/src/language/enUS.ts index 55165d6..c08f783 100644 --- a/src/language/enUS.ts +++ b/src/language/enUS.ts @@ -48,11 +48,19 @@ export const enUS = { header_project_file: 'Project File', header_project_title: 'Project File Import/Export', header_project_upload_tip1: 'Click to upload project file or drag and drop here', - header_project_upload_tip2: 'Supports JSON format project files', + header_project_upload_tip2: 'Supports JSON or ZIP (with materials) project files', header_project_confirm_title: 'System Notification', header_project_confirm_content: 'Importing a new project will overwrite the current project. Continue?', header_project_export: 'Export Project File', header_project_toast: 'Invalid data format', + header_project_zip_invalid: 'Failed to parse the zip file, please check its integrity', + header_project_json_missing: 'project.json not found in the zip', + header_project_import_no_root: 'Local storage folder is not ready, please refresh the page and select a folder first', + header_project_import_write_failed: 'Failed to write material files to local storage, import aborted', + header_project_import_partial: 'Import finished, {{failed}} material files failed to write or are missing, see console for details', + header_project_export_success: 'Project exported successfully (with all materials)', + header_project_export_partial: 'Export finished: {{success}} materials packed, {{failed}} failed to fetch (original URLs kept in project), see console for details', + header_project_export_failed: 'Export failed, please try again', header_project_poster: 'Capture Video Cover', // 导出弹窗 diff --git a/src/language/zhCN.ts b/src/language/zhCN.ts index 0216228..efe4acf 100644 --- a/src/language/zhCN.ts +++ b/src/language/zhCN.ts @@ -48,11 +48,19 @@ export const zhCN = { header_project_file: '工程文件', header_project_title: '工程文件导入/导出', header_project_upload_tip1: '点击上传工程文件或拖拽工程文件到这里', - header_project_upload_tip2: '支持任JSON格式的工程文件', + header_project_upload_tip2: '支持 JSON 或 ZIP(含素材)格式的工程文件', header_project_confirm_title: '系统提示', header_project_confirm_content: '导入新的项目会覆盖当前的项目,是否继续?', header_project_export: '导出工程文件', header_project_toast: '数据格式不合法', + header_project_zip_invalid: 'zip 包解析失败,请确认文件完整', + header_project_json_missing: 'zip 包中未找到 project.json 工程文件', + header_project_import_no_root: '本地存储文件夹未就绪,请刷新页面重新选择后导入', + header_project_import_write_failed: '素材文件写入本地存储失败,导入已中止', + header_project_import_partial: '导入完成,{{failed}} 个素材文件写入失败或缺失,详见控制台', + header_project_export_success: '工程文件导出成功(含全部素材)', + header_project_export_partial: '导出完成:{{success}} 个素材已打包,{{failed}} 个素材获取失败(工程内保留原地址),详见控制台', + header_project_export_failed: '导出失败,请重试', header_project_poster: '截取视频封面', // 导出弹窗 diff --git a/src/pages/editor/common/dragitem/DragItem.tsx b/src/pages/editor/common/dragitem/DragItem.tsx index 28ee80e..15ab9b5 100644 --- a/src/pages/editor/common/dragitem/DragItem.tsx +++ b/src/pages/editor/common/dragitem/DragItem.tsx @@ -79,7 +79,8 @@ export default function DragItem(props: IProps) { fileType: item.type, type: item.type as any, isLocal: isLocal ? true : false, - noAudioTracks: !hasAudio, + // audio 素材必然存在音轨,不允许被标记为无音轨(否则导出合成时会被排除) + noAudioTracks: item.type === 'audio' ? false : !hasAudio, mustFetch: item.type === 'image' ? true : false, thumb: isLocal ? item._thumbPath || item.urls.thumb : item.urls.thumb, frames: item.attrs.frames, diff --git a/src/pages/editor/components/header/Project.tsx b/src/pages/editor/components/header/Project.tsx index 4ddfe4e..39a95ec 100644 --- a/src/pages/editor/components/header/Project.tsx +++ b/src/pages/editor/components/header/Project.tsx @@ -3,6 +3,8 @@ import { Button, Modal, Toast, Upload } from '@douyinfe/semi-ui'; import styles from './project.module.less'; import { helper } from 'video-core-sdk'; import { util } from '@utils/index'; +import { exportProjectZip } from '@utils/projectExport'; +import { importProjectZip } from '@utils/projectImport'; import dayjs from 'dayjs'; import { Intl, language } from '@language/index'; import { stores } from '@stores/index'; @@ -12,6 +14,41 @@ type Props = {}; const Project = (props: Props) => { const { editor } = stores; const [visible, setVisible] = useState(false); + const [exporting, setExporting] = useState(false); + const [exportProgress, setExportProgress] = useState(''); + + // 导出工程文件(JSON + 全部素材打包为 zip) + const handleExport = async () => { + if (exporting) return; + const ndata = editor.movie.sortZIndexNewData(); + // 去掉重复的resource + editor.movie.clearUnUsedResource(ndata); + setExporting(true); + setExportProgress(''); + try { + const res = await exportProjectZip(ndata, `${ndata.title}_${dayjs().format('YYYYMMDDHHmmss')}`, { + onProgress: (done, total) => setExportProgress(`${done}/${total}`), + }); + if (res.failed.length > 0) { + console.warn('导出时获取失败的素材:', res.failed); + Toast.warning({ + content: language.val('header_project_export_partial', { + success: res.success, + failed: res.failed.length, + }), + duration: 5, + }); + } else { + Toast.success(language.val('header_project_export_success')); + } + } catch (err) { + console.error('导出工程文件失败:', err); + Toast.error(language.val('header_project_export_failed')); + } finally { + setExporting(false); + setExportProgress(''); + } + }; return ( <> diff --git a/src/pages/editor/components/sources/addItem.ts b/src/pages/editor/components/sources/addItem.ts index 8a80703..baa68e9 100644 --- a/src/pages/editor/components/sources/addItem.ts +++ b/src/pages/editor/components/sources/addItem.ts @@ -35,7 +35,8 @@ export const addImageVideoAudioItem = async ( fileType: item.type, type: item.type as any, isLocal: isLocal ? true : false, - noAudioTracks: !hasAudio, + // audio 素材必然存在音轨,不允许被标记为无音轨(否则导出合成时会被排除) + noAudioTracks: item.type === 'audio' ? false : !hasAudio, mustFetch: item.type === 'image' ? true : false, thumb: isLocal ? item._thumbPath || '' : item.urls.thumb, frames: isLocal ? item.attrs.frames || '' : item.attrs.frames, diff --git a/src/pages/editor/components/timeline2/tracks/useBackground.tsx b/src/pages/editor/components/timeline2/tracks/useBackground.tsx index d03d6c9..2b34abc 100644 --- a/src/pages/editor/components/timeline2/tracks/useBackground.tsx +++ b/src/pages/editor/components/timeline2/tracks/useBackground.tsx @@ -131,7 +131,8 @@ const useBackground = ( uploadBase64, reURL: reURL, }); - resource.noAudioTracks = res.noAudioTracks; + // audio 素材必然存在音轨,不允许被探测结果覆盖为无音轨 + resource.noAudioTracks = resource.type === 'audio' ? false : res.noAudioTracks; resource.attrs.frames = res.frames; resource.attrs.frameScale = res.frameScale; options.framesURL = res.frames; @@ -145,7 +146,7 @@ const useBackground = ( updateMaterialAttrs(resource.originId, { framesPath: res.frames, frameScale: res.frameScale, - noAudioTracks: res.noAudioTracks, + noAudioTracks: resource.type === 'audio' ? false : res.noAudioTracks, }).catch(e => console.warn('同步 IndexedDB 帧图数据失败:', e)); } } else { diff --git a/src/services/localStorageService.ts b/src/services/localStorageService.ts index c507639..4a136f7 100644 --- a/src/services/localStorageService.ts +++ b/src/services/localStorageService.ts @@ -133,6 +133,19 @@ async function copyFileToLocal( return { relativePath: `${dirName ? dirName + '/' : ''}${actualFileName}`, fileName: actualFileName }; } +/** 将文件写入本地存储的指定相对路径(供工程包导入使用),root 可传入已获取的句柄避免重复查询 */ +export async function saveFileToLocal( + file: File | Blob, + relativePath: string, + root?: FileSystemDirectoryHandle, +): Promise { + const dir = root || (await getRootHandle()); + if (!dir) return null; + const fileName = relativePath.split('/').filter(Boolean).pop() || 'file'; + const result = await copyFileToLocal(dir, file, relativePath, fileName); + return result.relativePath; +} + /** * 创建本地 uploadBase64 回调(供 getUploadBeforeData 使用) * 直接将数据保存到本地文件夹,返回 { storage_path } 格式 @@ -466,6 +479,36 @@ async function deleteFileByPath(root: FileSystemDirectoryHandle, relativePath: s } } +/** 读取本地素材文件为 File 对象(失败返回 null,不弹提示,供打包导出使用) */ +export async function getMaterialFile(relativePath: string): Promise { + // 非本地资源,直接跳过 + if (!relativePath.startsWith('materials/')) { + return null; + } + + const root = await getRootHandle(); + if (!root) return null; + + try { + const parts = relativePath.split('/').filter(Boolean); + const fileName = parts.pop()!; + const dirPath = parts.join('/'); + + let dir = root; + if (dirPath) { + for (const seg of dirPath.split('/')) { + dir = await dir.getDirectoryHandle(seg); + } + } + + const fileHandle = await dir.getFileHandle(fileName); + return await fileHandle.getFile(); + } catch (err) { + console.warn('读取本地素材文件失败:', relativePath, err); + return null; + } +} + /** 读取素材文件为 URL */ export async function getMaterialFileUrl(relativePath: string): Promise { @@ -676,23 +719,22 @@ export async function getLocalProjectList(params: ProjectListParams): Promise<[a } /** - * 将资源中的相对路径解析为 blob URL 并缓存到 resourceManage + * 将资源中的本地素材路径解析为 blob URL 并缓存到 resourceManage * 在数据加载后和新增资源后调用 + * 注意:video-core-sdk 1.0.69 起没有 cacheLocalBlobUrl 方法,需通过 fetchBlob 写入缓存 */ export async function hydrateResourcePaths( resources: Array<{ url?: string; thumb?: string; frames?: string; wave?: string; [key: string]: any }>, - resourceManage?: { cacheLocalBlobUrl: (path: string, blobUrl: string) => void }, + resourceManage?: { fetchBlob: (path: string) => Promise }, ): Promise { for (const res of resources) { const paths = [res.url, res.thumb, res.frames, res.wave].filter( - (p): p is string => !!p && !p.startsWith('blob:') && !p.startsWith('data:') && !/^https?:\/\//.test(p), + (p): p is string => !!p && p.startsWith('materials/'), ); for (const p of paths) { try { - const blobUrl = await getMaterialFileUrl(p); - if (blobUrl && resourceManage) { - resourceManage.cacheLocalBlobUrl(p, blobUrl); - } + // fetchBlob 内部会调用 getMaterialFileUrl 解析 materials/ 路径并写入 blob 缓存 + await resourceManage?.fetchBlob?.(p); } catch { /* ignore */ } diff --git a/src/utils/export.ts b/src/utils/export.ts index 716e3fd..2ebed64 100644 --- a/src/utils/export.ts +++ b/src/utils/export.ts @@ -1,8 +1,41 @@ import { helper, MovieEncoding } from 'video-core-sdk'; import { config } from '../config'; import { plugins } from '@plugins/index'; +import { getMaterialFileUrl } from '@services/localStorageService'; import type { IWatermark, MovieData } from 'video-core-sdk'; +/** + * 预解析本地素材为 blob URL 并写入导出实例的缓存。 + * + * 导出的音频合成链路 getAllMedia → fetchFile 取的是 resourceManage 的 blob 缓存, + * 而导出 Movie 的 loadUsedResource 是不等待的后台任务,音频编码启动时缓存往往还没就绪, + * 会拿到未解析的 materials/ 相对地址(fetch 回 index.html),导致 FFmpeg 合成失败、 + * 导出收尾死循环(控制台反复输出「音频已经编码--> false」)。 + * 必须在 me.run() 之前显式 await 完成预解析。 + */ +async function prewarmLocalMaterials(me: any, data: MovieData): Promise { + const resourceManage = me?._movie?.resourceManage || me?.current?.resourceManage; + if (!resourceManage?.fetchBlob) { + return; + } + const paths = new Set(); + for (const res of (data.resouces || []) as Array>) { + for (const p of [res.url, res.thumb, res.frames, res.wave]) { + if (typeof p === 'string' && p.startsWith('materials/')) { + paths.add(p); + } + } + } + await Promise.all( + [...paths].map(p => + resourceManage.fetchBlob(p).catch((err: any) => { + console.warn('导出预解析本地素材失败:', p, err); + return null; + }), + ), + ); +} + export const exportMovie = async (params: { format: 'mp4' | 'gif' | 'mp3'; fps: number; @@ -26,6 +59,15 @@ export const exportMovie = async (params: { const values: any = { ...other, }; + + // 历史工程中 audio 素材可能被误标 noAudioTracks=true(音频合成时会被直接排除,导致导出无声音)。 + // 音频必然存在音轨,导出前强制修正;使用浅拷贝避免改动编辑器内的数据 + const exportData: MovieData = { + ...data, + resouces: (data.resouces || []).map(r => + r.type === 'audio' && r.noAudioTracks ? { ...r, noAudioTracks: false } : r, + ), + } as MovieData; const totalTime = helper.getTotalTime(data); if (values.gifTimes) { values.gifTimes[1] = totalTime; @@ -53,7 +95,9 @@ export const exportMovie = async (params: { resourceHost: config.resourcesHost, EModuleEffectSourcePath: config.EModuleEffectSourcePath, plugins: plugins, - movieData: data, + movieData: exportData, + // 本地存储模式下 materials/ 路径需要解析为 blob URL,否则导出时音频/视频素材无法加载 + getMaterialFileUrl: getMaterialFileUrl, watermark: params.watermark, // renderEnv: 'web', times: values.format === 'gif' ? values.gifTimes : undefined, @@ -67,6 +111,9 @@ export const exportMovie = async (params: { // } console.log('onReady=---->', values); + // 先等本地素材全部解析成 blob URL,再开始编码(音频合成依赖此缓存) + await prewarmLocalMaterials(me, exportData); + if (values.format === 'mp4') { await me.run(); } diff --git a/src/utils/projectExport.ts b/src/utils/projectExport.ts new file mode 100644 index 0000000..f9a697c --- /dev/null +++ b/src/utils/projectExport.ts @@ -0,0 +1,323 @@ +import JSZip from 'jszip'; +import pLimit from 'p-limit'; +import type { MovieData } from 'video-core-sdk'; +import { utils } from 'video-core-sdk'; +import { config } from '@config/index'; +import { getMaterialFile } from '@services/localStorageService'; + +/** 素材上需要打包的文件字段,suffix 用于同素材相关文件命名;attrs.* 为异步补生成的帧图/音波路径 */ +const RESOURCE_FILE_FIELDS: Array<{ key: string; suffix: string }> = [ + { key: 'url', suffix: '' }, + { key: 'thumb', suffix: '_thumb' }, + { key: 'wave', suffix: '_wave' }, + { key: 'frames', suffix: '_frames' }, + { key: 'attrs.frames', suffix: '_frames' }, + { key: 'attrs.wave', suffix: '_wave' }, +]; + +/** 读取(可能嵌套在 attrs 里的)字段值 */ +function getFieldValue(obj: Record, key: string): any { + if (!key.includes('.')) { + return obj[key]; + } + const [outer, inner] = key.split('.'); + return obj[outer]?.[inner]; +} + +/** 根据扩展名推断素材分类文件夹 */ +const EXT_FOLDER_MAP: Record = { + mp4: 'video', + webm: 'video', + mov: 'video', + mkv: 'video', + mp3: 'audio', + wav: 'audio', + aac: 'audio', + m4a: 'audio', + flac: 'audio', + png: 'image', + jpg: 'image', + jpeg: 'image', + gif: 'image', + webp: 'image', + svg: 'image', + bmp: 'image', + apng: 'image', + json: 'lottie', + ttf: 'font', + otf: 'font', + woff: 'font', + woff2: 'font', +}; + +export interface ExportProjectZipResult { + /** 打包的素材文件总数 */ + total: number; + /** 成功打包的文件数 */ + success: number; + /** 获取失败的素材(保留原始地址,不影响导出) */ + failed: Array<{ name: string; url: string }>; +} + +export interface ExportProjectZipOptions { + onProgress?: (done: number, total: number) => void; +} + +/** 替换文件名中的非法字符 */ +function sanitizeFileName(name: string): string { + return (name || 'file').replace(/[\\/:*?"<>|]/g, '_').trim() || 'file'; +} + +/** 从路径型 URL 中提取文件名(去掉查询参数),非路径型返回空 */ +function getPathFileName(url: string): string { + const clean = url.split(/[?#]/)[0]; + const last = clean.split('/').filter(Boolean).pop() || ''; + // data:/blob: 这类地址提取出来的不是合法文件名,交由调用方用资源名兜底 + if (!last || !/\.[a-zA-Z0-9]{1,6}$/.test(last)) { + return ''; + } + try { + return decodeURIComponent(last); + } catch { + return last; + } +} + +function getFileExt(name: string): string { + const mat = name.match(/\.([a-zA-Z0-9]{1,6})$/); + return mat ? mat[1].toLowerCase() : ''; +} + +/** 素材在 zip 内的分类文件夹:优先使用素材类型,其次按扩展名推断 */ +function getResourceFolder(res: { type?: string; url?: string }): string { + const type = (res.type || '').split('/').filter(Boolean).pop() || ''; + if (type) return sanitizeFileName(type); + const ext = getFileExt(getPathFileName(res.url || '')); + return EXT_FOLDER_MAP[ext] || 'other'; +} + +/** data:/blob: 地址的媒体类型 */ +function mimeFromDataUrl(url: string): string { + const mat = url.match(/^data:([^;,]+)[;,]/); + return mat ? mat[1] : ''; +} + +function extFromMime(mime: string): string { + const map: Record = { + 'image/png': 'png', + 'image/jpeg': 'jpg', + 'image/webp': 'webp', + 'image/gif': 'gif', + 'image/svg+xml': 'svg', + 'video/mp4': 'mp4', + 'audio/mpeg': 'mp3', + 'audio/wav': 'wav', + 'application/json': 'json', + 'text/text': 'json', // 音波数据(btoa(JSON.stringify(peacks)))的 mime + 'text/plain': 'txt', + }; + const key = mime.split(';')[0].trim(); + return map[key] || 'bin'; +} + +/** 获取素材文件内容:本地路径读文件系统,其余地址走 fetch */ +async function loadResourceBlob(url: string): Promise { + try { + if (url.startsWith('materials/')) { + return await getMaterialFile(url); + } + if (/^(data:|blob:)/i.test(url)) { + const resp = await fetch(url); + return await resp.blob(); + } + // 相对路径的资源地址需要拼接资源 host + const target = /^https?:\/\//i.test(url) ? url : utils.reURL(url, config.resourcesHost); + const resp = await fetch(target); + if (!resp.ok) { + return null; + } + return await resp.blob(); + } catch (err) { + console.warn('获取素材失败:', url, err); + return null; + } +} + +/** 触发浏览器下载 Blob 文件 */ +function downloadBlob(blob: Blob, fileName: string): void { + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = fileName; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +} + +/** + * 导出工程文件(JSON + 全部素材)为一个 zip 包 + * + * zip 结构: + * ├── project.json 工程数据(素材地址已改写为包内相对路径) + * └── materials/{素材类型}/{文件名} 按素材路径/类型分文件夹存放 + * + * 本地素材(materials/ 开头的路径)在包内保持原路径,工程数据无需改写; + * 远端/data:/blob: 素材下载后放入对应类型文件夹,并将工程数据中的地址改写为包内路径; + * 获取失败的素材保留原始地址,不影响工程数据可用性。 + */ +export async function exportProjectZip( + ndata: MovieData, + fileName: string, + options: ExportProjectZipOptions = {}, +): Promise { + // 深拷贝,改写素材地址不能影响编辑器内的数据 + const data = JSON.parse(JSON.stringify(ndata)) as MovieData; + const zip = new JSZip(); + const failed: ExportProjectZipResult['failed'] = []; + + // 同一地址只打包一次,多个字段引用时复用同一个包内路径 + interface PackTask { + url: string; + zipPath: string; + name: string; + // 获取成功后需要改写为包内路径的字段(zipPath 与原地址相同时为空) + rewrites: Array<{ target: Record; key: string }>; + } + const urlTaskMap = new Map(); + const tasks: PackTask[] = []; + const usedZipPaths = new Set(); + let done = 0; + + const uniqueZipPath = (path: string): string => { + if (!usedZipPaths.has(path)) { + usedZipPaths.add(path); + return path; + } + const dot = path.lastIndexOf('.'); + const stem = dot > path.lastIndexOf('/') ? path.slice(0, dot) : path; + const ext = dot > path.lastIndexOf('/') ? path.slice(dot) : ''; + let i = 2; + let next = `${stem}_${i}${ext}`; + while (usedZipPaths.has(next)) { + i++; + next = `${stem}_${i}${ext}`; + } + usedZipPaths.add(next); + return next; + }; + + for (const res of (data.resouces || []) as Array>) { + const folder = getResourceFolder(res); + const resName = res.name || res.id || 'file'; + // 用不带扩展名的素材名给封面/帧图等相关文件命名 + const resStem = sanitizeFileName(resName).replace(/\.[^.]+$/, '') || 'file'; + + for (const { key, suffix } of RESOURCE_FILE_FIELDS) { + const value = getFieldValue(res, key); + if (!value || typeof value !== 'string') { + continue; + } + // 改写目标:attrs.* 字段写在 res.attrs 上 + const [ns, innerKey] = key.split('.'); + const rewriteTarget = innerKey ? res.attrs : res; + const rewriteKey = innerKey || key; + + const exist = urlTaskMap.get(value); + if (exist) { + // 地址已被收集,复用包内路径和获取结果 + if (exist.zipPath !== value) { + exist.rewrites.push({ target: rewriteTarget, key: rewriteKey }); + } + continue; + } + + let zipPath: string; + if (value.startsWith('materials/')) { + // 本地素材:包内保持原路径,工程数据不用改 + zipPath = uniqueZipPath(value); + } else { + // 远端/内联素材:按类型放入 materials/{type}/,并改写工程数据 + let name = getPathFileName(value); + if (!name) { + const mime = mimeFromDataUrl(value); + const ext = mime ? extFromMime(mime) : 'bin'; + name = `${resStem}${suffix}.${ext}`; + } else if (suffix) { + const dot = name.lastIndexOf('.'); + name = `${name.slice(0, dot)}${suffix}${name.slice(dot)}`; + } + zipPath = uniqueZipPath(`materials/${folder}/${sanitizeFileName(name)}`); + } + + const task: PackTask = { + url: value, + zipPath, + name: resName, + rewrites: zipPath !== value ? [{ target: rewriteTarget, key: rewriteKey }] : [], + }; + urlTaskMap.set(value, task); + tasks.push(task); + } + } + + // 工程封面(本地模式下是 materials/ 路径或 data:URL,同样需要进包) + const posterValue = (data as any).poster; + if (typeof posterValue === 'string' && posterValue && !posterValue.startsWith('blob:')) { + const posterExist = urlTaskMap.get(posterValue); + if (posterExist) { + if (posterExist.zipPath !== posterValue) { + posterExist.rewrites.push({ target: data as any, key: 'poster' }); + } + } else { + let posterZipPath: string; + if (posterValue.startsWith('materials/')) { + posterZipPath = uniqueZipPath(posterValue); + } else { + const mime = mimeFromDataUrl(posterValue); + let ext = mime ? extFromMime(mime) : ''; + if (!ext) { + ext = getPathFileName(posterValue).split('.').pop() || 'png'; + } + posterZipPath = uniqueZipPath(`materials/poster/poster.${ext}`); + } + const posterTask: PackTask = { + url: posterValue, + zipPath: posterZipPath, + name: 'poster', + rewrites: posterZipPath !== posterValue ? [{ target: data as any, key: 'poster' }] : [], + }; + urlTaskMap.set(posterValue, posterTask); + tasks.push(posterTask); + } + } + + const total = tasks.length; + options.onProgress?.(done, total); + + const limit = pLimit(4); + await Promise.all( + tasks.map(task => + limit(async () => { + const blob = await loadResourceBlob(task.url); + if (blob) { + // 媒体文件已是压缩格式,STORE 避免 CPU 浪费 + zip.file(task.zipPath, blob, { compression: 'STORE' }); + for (const { target, key } of task.rewrites) { + target[key] = task.zipPath; + } + } else { + failed.push({ name: task.name, url: task.url }); + } + done++; + options.onProgress?.(done, total); + }), + ), + ); + + zip.file('project.json', JSON.stringify(data, null, 2), { compression: 'DEFLATE' }); + const blob = await zip.generateAsync({ type: 'blob', compression: 'STORE' }); + downloadBlob(blob, `${fileName}.zip`); + + return { total, success: total - failed.length, failed }; +} diff --git a/src/utils/projectImport.ts b/src/utils/projectImport.ts new file mode 100644 index 0000000..96bfc73 --- /dev/null +++ b/src/utils/projectImport.ts @@ -0,0 +1,268 @@ +import JSZip from 'jszip'; +import pLimit from 'p-limit'; +import type { MovieData } from 'video-core-sdk'; +import { checkNdata } from './util'; +import { localDB, type MaterialRecord } from '@database/localDB'; +import { getRootHandle, saveFileToLocal } from '@services/localStorageService'; + +/** 已知素材分类文件夹名,用于识别 zip 内素材路径结构 */ +const KNOWN_MATERIAL_TYPES = new Set([ + 'video', + 'image', + 'audio', + 'text', + 'lottie', + 'font', + 'sticker', + 'effect', + 'filter', + 'transition', + 'other', + 'apng', + 'face', + 'role', + 'scene', + 'special', + 'goods', + 'poster', // 工程封面 +]); + +export interface ImportProjectZipResult { + /** 素材地址已改写为本地路径的工程数据 */ + data: MovieData; + /** 成功写入本地存储的素材文件数 */ + fileCount: number; + /** 写入失败或 zip 中缺失的素材路径 */ + skipped: string[]; +} + +export interface ImportProjectZipOptions { + onProgress?: (done: number, total: number) => void; +} + +/** zip 内条目路径归一化(部分压缩工具使用反斜杠) */ +function normalizeZipPath(path: string): string { + return path.replace(/\\/g, '/').replace(/^\.\//, ''); +} + +/** + * 归一化 materials/ 之后的路径片段: + * 去掉导出时携带的旧 appId 段,统一为 {type}/... 结构, + * 拼上当前 appId 后可隔离不同工程导入的素材,避免同名互相覆盖 + */ +function normalizeMaterialRest(rest: string): string { + const segs = rest.split('/').filter(Boolean); + if (segs.length === 0) { + return 'other/file'; + } + if (KNOWN_MATERIAL_TYPES.has(segs[0].toLowerCase())) { + return segs.join('/'); + } + if (segs.length >= 2 && KNOWN_MATERIAL_TYPES.has(segs[1].toLowerCase())) { + return segs.slice(1).join('/'); + } + return ['other', ...segs].join('/'); +} + +/** 在 zip 中定位 project.json,兼容直接压缩和套一层文件夹两种打包方式 */ +function findProjectEntry(zip: JSZip): { basePath: string; entry: any } | null { + let best: { basePath: string; entry: any; depth: number } | null = null; + for (const [rawName, entry] of Object.entries(zip.files)) { + if ((entry as any).dir) { + continue; + } + const name = normalizeZipPath(rawName); + const segs = name.split('/').filter(Boolean); + if (segs[segs.length - 1] !== 'project.json') { + continue; + } + if (!best || segs.length < best.depth) { + best = { basePath: segs.slice(0, -1).join('/'), entry: entry as any, depth: segs.length }; + } + } + return best ? { basePath: best.basePath, entry: best.entry } : null; +} + +/** 为导入的本地素材建立/更新索引记录,使素材面板可见且可被清理 */ +async function saveMaterialRecords(ndata: MovieData, appId: string, sizeMap: Map): Promise { + const now = Date.now(); + const existing = await localDB.materials.where('appId').equals(appId).toArray(); + const byPath = new Map(existing.map(r => [r.relativePath, r])); + const seen = new Set(); + + const pick = (v: any): string | undefined => + typeof v === 'string' && v.startsWith('materials/') ? v : undefined; + + for (const res of (ndata.resouces || []) as Array>) { + const url = pick(res.url); + if (!url || seen.has(url)) { + continue; // 非本地素材不建记录 + } + seen.add(url); + const old = byPath.get(url); + const thumb = pick(res.thumb); + const frames = pick(res.frames); + const wave = pick(res.wave); + const record: MaterialRecord = { + id: old?.id ?? `imp_${now}_${Math.random().toString(36).slice(2, 8)}`, + appId, + name: res.name || url.split('/').pop() || 'material', + type: (res.type as string) || 'other', + fileName: url.split('/').pop(), + relativePath: url, + thumbRelativePath: thumb, + thumbFileName: thumb?.split('/').pop(), + framesRelativePath: frames, + framesFileName: frames?.split('/').pop(), + waveRelativePath: wave, + waveFileName: wave?.split('/').pop(), + size: sizeMap.get(url) ?? old?.size ?? 0, + attrs: { ...(res.attrs || {}) }, + from: res.from === 'system' ? 'system' : 'user', + tag: old?.tag, + createdAt: old?.createdAt ?? now, + updatedAt: now, + }; + await localDB.materials.put(record); + } +} + +/** + * 导入工程包(zip:project.json + materials/ 素材) + * + * 1. 解压并定位 project.json(根目录或套一层文件夹均可),校验数据合法性; + * 2. 将包内 materials/ 下全部素材文件写入本地存储目录, + * 统一归一到 materials/{appId}/{type}/ 路径下; + * 3. 改写工程数据中的素材地址为本地路径(远端/data: 地址保持不变); + * 4. 为本地素材建立 IndexedDB 索引记录(同路径覆盖更新,重复导入不产生重复记录)。 + */ +export async function importProjectZip( + file: File, + appId: string, + options: ImportProjectZipOptions = {}, +): Promise { + let zip: JSZip; + try { + zip = await JSZip.loadAsync(file); + } catch (err) { + console.error('zip 解析失败:', err); + throw new Error('header_project_zip_invalid'); + } + + const project = findProjectEntry(zip); + if (!project) { + throw new Error('header_project_json_missing'); + } + + const ndata = JSON.parse(await project.entry.async('string')) as MovieData; + if (!checkNdata(ndata)) { + throw new Error('header_project_toast'); + } + + // 素材要写入本地存储目录,根句柄必须就绪 + const root = await getRootHandle(); + if (!root) { + throw new Error('header_project_import_no_root'); + } + + // 收集素材文件:包内 materials/ 路径 -> 本地目标路径 + const materialsPrefix = project.basePath ? `${project.basePath}/materials/` : 'materials/'; + const pathMap = new Map(); + const writeTasks: Array<{ entry: any; innerPath: string; targetPath: string }> = []; + + for (const [rawName, entry] of Object.entries(zip.files)) { + if ((entry as any).dir) { + continue; + } + const name = normalizeZipPath(rawName); + if (!name.startsWith(materialsPrefix)) { + continue; + } + const rest = name.slice(materialsPrefix.length); + // 过滤 mac 压缩产生的资源叉文件和隐藏文件 + if (rest.split('/').some(seg => seg.startsWith('.'))) { + continue; + } + const innerPath = `materials/${rest}`; + if (pathMap.has(innerPath)) { + continue; + } + const targetPath = `materials/${appId}/${normalizeMaterialRest(rest)}`; + pathMap.set(innerPath, targetPath); + writeTasks.push({ entry: entry as any, innerPath, targetPath }); + } + + const skipped: string[] = []; + const sizeMap = new Map(); + let done = 0; + const total = writeTasks.length; + options.onProgress?.(done, total); + + const limit = pLimit(4); + await Promise.all( + writeTasks.map(task => + limit(async () => { + try { + const blob = await task.entry.async('blob'); + const saved = await saveFileToLocal(blob, task.targetPath, root); + if (saved) { + sizeMap.set(task.targetPath, blob.size); + } else { + skipped.push(task.innerPath); + } + } catch (err) { + console.warn('写入素材文件失败:', task.innerPath, err); + skipped.push(task.innerPath); + } + done++; + options.onProgress?.(done, total); + }), + ), + ); + + // 全部写入失败时中止导入,避免得到一个素材全部丢失的工程 + if (total > 0 && sizeMap.size === 0) { + throw new Error('header_project_import_write_failed'); + } + + // 改写工程数据中的素材地址,并记录缺失的引用 + for (const res of (ndata.resouces || []) as Array>) { + for (const key of ['url', 'thumb', 'wave', 'frames'] as const) { + const value = res[key]; + if (typeof value === 'string' && value.startsWith('materials/')) { + const target = pathMap.get(value); + if (target) { + res[key] = target; + } else if (!skipped.includes(value)) { + skipped.push(value); + } + } + } + if (res.attrs && typeof res.attrs === 'object') { + for (const key of ['frames', 'wave'] as const) { + const value = res.attrs[key]; + if (typeof value === 'string' && value.startsWith('materials/')) { + const target = pathMap.get(value); + if (target) { + res.attrs[key] = target; + } + } + } + } + } + + // 工程封面路径同样需要映射 + const posterValue = (ndata as any).poster; + if (typeof posterValue === 'string' && posterValue.startsWith('materials/')) { + const target = pathMap.get(posterValue); + if (target) { + (ndata as any).poster = target; + } else if (!skipped.includes(posterValue)) { + skipped.push(posterValue); + } + } + + await saveMaterialRecords(ndata, appId, sizeMap); + + return { data: ndata, fileCount: sizeMap.size, skipped }; +} diff --git a/src/utils/util.ts b/src/utils/util.ts index e96e7ef..a499ff2 100644 --- a/src/utils/util.ts +++ b/src/utils/util.ts @@ -275,7 +275,8 @@ export function downloadJson(jsonData, fileName) { export async function checkVideoUrlHasAudio(url: string, type?: string) { // 检查格式 const ext = type || utils.getFileTypeFromFileName(url); - if (['aac', 'mp3', 'wav'].includes(ext)) { + // 音频类型/常见音频格式必然存在音轨,无需探测 + if (['audio', 'aac', 'mp3', 'wav', 'm4a', 'flac', 'ogg'].includes(ext)) { return true; } if (ext !== 'video') return false; diff --git a/stats.html b/stats.html new file mode 100644 index 0000000..777dba9 --- /dev/null +++ b/stats.html @@ -0,0 +1,4949 @@ + + + + + + + + Rollup Visualizer + + + +
+ + + + + diff --git a/yarn.lock b/yarn.lock index 48bed9d..5d6ec44 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5956,10 +5956,10 @@ vfile@^6.0.0: "@types/unist" "^3.0.0" vfile-message "^4.0.0" -video-core-sdk@1.0.64: - version "1.0.64" - resolved "https://registry.npmmirror.com/video-core-sdk/-/video-core-sdk-1.0.64.tgz#71a32e89bb2fb89dacf1b7d5564a653ab6fe8669" - integrity sha512-FLhBJmiU6+kG9/vvGR/5nR88/LjO86LAuwCbhsCnxbPz80XOES5eM82FlYVEgk6oKJ4EWKXvs1lMdV+KAskqmA== +video-core-sdk@1.0.70: + version "1.0.70" + resolved "https://registry.npmmirror.com/video-core-sdk/-/video-core-sdk-1.0.70.tgz#adc8aa9e7497a602c3dea7a702348c6e0b2910f0" + integrity sha512-J6d2UsZb0/9VT3ozxqeYtpbwIKp/9Bj7giXcQG23XyE1sLZ7yCPxb1ZcKrY4tm+ijwsZhFLfwLzat5PMq4s2PQ== vite-plugin-imp@^2.4.0: version "2.4.0"