clipoox-render 0.4.3 → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -3
- package/scripts/render-local.mjs +5160 -1446
- package/web/assets/FxEmbed-DbfuM8Yo.js +1 -0
- package/web/assets/MotionEmbed-CBQ-8Tzh.js +1 -0
- package/web/assets/PluginStore-OOEx0lP5.js +3 -0
- package/web/assets/ShotComposer-Cng515xa.js +287 -0
- package/web/assets/{ShotComposer-VixLbeMe.css → ShotComposer-deLi4grZ.css} +1 -1
- package/web/assets/TemplateEmbed-hjwM2b0o.js +2 -0
- package/web/assets/{TimelinePlugins-BYZ9y4m3.js → TimelinePlugins-D-NakABP.js} +4 -4
- package/web/assets/TimelineShotFx-D3kGhHN3.js +2 -0
- package/web/assets/TransitionEmbed-DR26yI3a.js +1 -0
- package/web/assets/{Whiteboard-BP_DvIAV.js → Whiteboard-BhxY0D0Z.js} +3 -3
- package/web/assets/aerial-BisYSXzG.js +2 -0
- package/web/assets/agentTools-CPFQeiDP.js +2 -0
- package/web/assets/aiInbetween-AOOM1e6p.js +2 -0
- package/web/assets/analyzerRun-Dtp2o7gT.js +1 -0
- package/web/assets/analyzerSandbox-BG_3Cea1.js +33 -0
- package/web/assets/api-BFN7blbw.js +3158 -0
- package/web/assets/auraTrack-D_gxHNVe.js +1 -0
- package/web/assets/breakthrough-0qFpZW-V.js +2 -0
- package/web/assets/{cameraPresets-CYw0OdM3.js → cameraPresets-eK3mP7qb.js} +1 -1
- package/web/assets/cameraTracker-BAQHuTV-.js +72 -0
- package/web/assets/captionLayout-CWPcbid-.js +1 -0
- package/web/assets/clientExport-DvpTTndR.js +1 -0
- package/web/assets/clientJobs-CIrYTMpn.js +2 -0
- package/web/assets/clientJobs-CuuUyhEy.js +1 -0
- package/web/assets/cutoutClean-CLYYAuXg.js +1 -0
- package/web/assets/depthEstimate-B7D7cGCl.js +1 -0
- package/web/assets/directorTools-CJD4Huqk.js +1 -0
- package/web/assets/distortFrames-BLt1icUb.js +2 -0
- package/web/assets/{distortGL-QalhICvi.js → distortGL-BA5molk-.js} +3 -3
- package/web/assets/draco_decoder-C32yEggz.wasm +0 -0
- package/web/assets/draco_decoder-Z1_iN-Ht.wasm +0 -0
- package/web/assets/draco_decoder-fzg4nYZr.js +34 -0
- package/web/assets/draco_wasm_wrapper-DxJM36Ib.js +117 -0
- package/web/assets/draco_wasm_wrapper-fZCQGLGb.js +116 -0
- package/web/assets/editTools-NKLsWZD1.js +1 -0
- package/web/assets/{engine-BedcnK45.js → engine-DioUF2mX.js} +1 -1
- package/web/assets/exportGlb-BOdI9cVS.js +2 -0
- package/web/assets/faceTracker-D7CbF-qX.js +1 -0
- package/web/assets/fightDirector-CYP8jxo8.js +1 -0
- package/web/assets/fightDrama-DIPcRKnc.js +2 -0
- package/web/assets/focusTool-vfabPqQ5.js +1 -0
- package/web/assets/{frameSink-DeM8xC8_.js → frameSink-DYs2gTzq.js} +3 -3
- package/web/assets/glTransitionSources.generated-DM5sRMX2.js +3695 -0
- package/web/assets/gltfLoader-U0Eebg7v.js +2 -0
- package/web/assets/{gpuCompose-CA3UmOl4.js → gpuCompose-DbnZuelB.js} +1 -1
- package/web/assets/gpuExport-CQ7ZhpsX.js +198 -0
- package/web/assets/handMatte-DIbMuqCu.js +1 -0
- package/web/assets/handTracker-DY_g5Xmg.js +2 -0
- package/web/assets/i18n-BJppIrtF.js +3 -0
- package/web/assets/index-BfrDwjDI.js +4247 -0
- package/web/assets/index-CKtv7gGE.js +9 -0
- package/web/assets/{index-D5oyVCRl.js → index-DxdDhmLR.js} +2 -2
- package/web/assets/layer-worker-DK67WH1a.js +5 -0
- package/web/assets/library-B6KsZUKq.js +1 -0
- package/web/assets/lottieLayer-C2YbiXhK.js +161 -0
- package/web/assets/{lottie_light_canvas-B-d7-ATe.js → lottie_light_canvas-DX9Wf-DS.js} +1 -1
- package/web/assets/main-B27kf5aL.css +1 -0
- package/web/assets/main-BKatDoGw.js +309 -0
- package/web/assets/mapBake-C-G7WpFM.js +1 -0
- package/web/assets/maskTrack-LMrwm5ub.js +1 -0
- package/web/assets/matteFixRun-B38CbeEt.js +1 -0
- package/web/assets/matteQuality-9X-jgJrH.js +1 -0
- package/web/assets/objectLocate-CKi3OTnL.js +1 -0
- package/web/assets/objectSegmenter-CziPuM61.js +1 -0
- package/web/assets/{objectTrack.worker-BlZkgpOX.js → objectTrack.worker-b7DJ-ub6.js} +196 -196
- package/web/assets/pathTracer-bqau16sX.js +2 -0
- package/web/assets/pendingMatte-CQb7jPg1.js +2 -0
- package/web/assets/personAi-CQntGDqK.js +2 -0
- package/web/assets/personHq-B1c0QVJT.js +2 -0
- package/web/assets/plateCamera-D7iLiNBy.js +1 -0
- package/web/assets/plateCameraMatch-BM88dx-a.js +2 -0
- package/web/assets/plateFollow-4iGUDTu1.js +2 -0
- package/web/assets/plateMatte-zTyuHHqh.js +2 -0
- package/web/assets/plugin-guide.en-DO_fHbzT.js +1 -0
- package/web/assets/plugin-guide.vi-CMJDxOhi.js +1 -0
- package/web/assets/pluginAutomation-DSg-sYLF.js +1 -0
- package/web/assets/poseTracker-DZl8l2qS.js +1 -0
- package/web/assets/productTools-B-jh8ukh.js +2 -0
- package/web/assets/remote-DJd9xWjn.js +963 -0
- package/web/assets/{rigTrack-urT3nDK0.js → rigTrack-XaMj1yaH.js} +1 -1
- package/web/assets/rotoMaskStore-DdpmT9C3.js +1 -0
- package/web/assets/{rotoMatte-C-2o3vv0.js → rotoMatte-i-cJTYmK.js} +1 -1
- package/web/assets/rotoscope-DqRSWmHR.js +1 -0
- package/web/assets/sceneTrack-Bbov7zET.js +1 -0
- package/web/assets/sceneTrack-DIPzBmMK.js +1 -0
- package/web/assets/{sceneTrack.worker-CT4uoTKn.js → sceneTrack.worker-Bav9h0pv.js} +180 -180
- package/web/assets/shot-worker-m-q77W9f.js +1 -0
- package/web/assets/{shotFxAgent-BFLkqs8v.js → shotFxAgent-DIMS7BGA.js} +2 -2
- package/web/assets/{skin-DY4QLaBI.js → skin-DrUzJE1u.js} +1 -1
- package/web/assets/{spark.module-DzziUgOj.js → spark.module-Y1SEI8Xz.js} +10 -10
- package/web/assets/spellDuel-DNnyQDVr.js +2 -0
- package/web/assets/store-GFMJzaWS.js +1 -0
- package/web/assets/surfaceLight-C--moyc9.js +1 -0
- package/web/assets/surfacePin-B4-1UqXD.js +2 -0
- package/web/assets/{textAnimators-DUZjhVGO.js → textAnimators-BVXTl8bU.js} +1 -1
- package/web/assets/{thumb-CS0ZuiGS.js → thumb-CTfDJgLp.js} +1 -1
- package/web/assets/timeline3d-Dn7PqmEe.js +2 -0
- package/web/assets/timeline3dExport-DCOr6ARB.js +1 -0
- package/web/assets/timelineComp-Dx_kED5V.js +1 -0
- package/web/assets/timelineOps-afzSo188.js +525 -0
- package/web/assets/timelineProps-eYgO6gs5.js +1 -0
- package/web/assets/timelineText-RKyRP988.js +1 -0
- package/web/assets/{titleArt-Drsrtfiv.js → titleArt-CUtA0C3I.js} +4 -4
- package/web/assets/{titleFrameBudget-CLZWaFHO.js → titleFrameBudget-X7HLSDre.js} +721 -704
- package/web/assets/titleFrames-aMG7HdVe.js +1 -0
- package/web/assets/{tool-DktQYmS6.js → tool-DpFjybaq.js} +1 -1
- package/web/assets/{tools-Co9aRDiT.js → tools-CeOU0p13.js} +1 -1
- package/web/assets/toonTools-DLmo37Z_.js +2 -0
- package/web/assets/trackAnchor-hAOtEhKO.js +1 -0
- package/web/assets/userFonts-1kuRjWOo.js +1 -0
- package/web/assets/{vfxAlpha-71tSN86T.js → vfxAlpha-DxS5-QwY.js} +2 -2
- package/web/assets/vfxBackground-CYpaQaTa.js +2 -0
- package/web/assets/videoExport-Cg4B2Nyh.js +1 -0
- package/web/assets/views-CUXyRb9x.js +1 -0
- package/web/assets/weaponDuel-nFECu9nk.js +1 -0
- package/web/assets/windowFrames-1wAkkWnv.js +1 -0
- package/web/layer-worker.html +3 -3
- package/web/shot-worker.html +41 -0
- package/web/assets/FxEmbed-BCmj9Q5C.js +0 -1
- package/web/assets/GLTFLoader-BHWu1lKg.js +0 -1
- package/web/assets/MotionEmbed-CEmbcq8Z.js +0 -1
- package/web/assets/PluginStore-C5hyahvG.js +0 -3
- package/web/assets/ShotComposer-0DUtMTVI.js +0 -287
- package/web/assets/TemplateEmbed-ANxSs7H5.js +0 -2
- package/web/assets/TimelineShotFx-q5PQwq-V.js +0 -2
- package/web/assets/TransitionEmbed-O6LInGWq.js +0 -1
- package/web/assets/aerial-CGLDKKtP.js +0 -2
- package/web/assets/agentTools-2Ghb80VH.js +0 -2
- package/web/assets/analyzerRun-DRgxrcJA.js +0 -1
- package/web/assets/analyzerSandbox-DuIVFnsk.js +0 -33
- package/web/assets/api-CJ8PdbfZ.js +0 -3168
- package/web/assets/auraTrack-DQw9sVU6.js +0 -1
- package/web/assets/breakthrough-BNj_iTDr.js +0 -2
- package/web/assets/captionLayout-DvDPTwO9.js +0 -1
- package/web/assets/clientExport-xhoXY6Dh.js +0 -1
- package/web/assets/depthEstimate-DEpeCojm.js +0 -1
- package/web/assets/directorTools-C5CpTmci.js +0 -1
- package/web/assets/distortFrames-Dia8O1NM.js +0 -2
- package/web/assets/editTools-CY_JrQfw.js +0 -1
- package/web/assets/exportEncode-QYsT9JBO.js +0 -1
- package/web/assets/exportGlb-TSj09XoV.js +0 -2
- package/web/assets/faceTracker-CnCWOwnJ.js +0 -1
- package/web/assets/fightDirector-DCI_FWTh.js +0 -1
- package/web/assets/fightDrama-Bg7uP_2Q.js +0 -2
- package/web/assets/gpuExport-D31azOQA.js +0 -198
- package/web/assets/handMatte-Dl-xVXFR.js +0 -1
- package/web/assets/handTracker-CplBsAFg.js +0 -2
- package/web/assets/layer-worker-DFuo32bk.js +0 -5
- package/web/assets/library-BufgA-Pl.js +0 -1
- package/web/assets/lottieLayer-DzbA3bHV.js +0 -158
- package/web/assets/main-Ca_CVxMz.css +0 -1
- package/web/assets/main-VVYiW8XD.js +0 -309
- package/web/assets/mapBake-BKOcEd0w.js +0 -1
- package/web/assets/maskTrack-CHGXtBRy.js +0 -1
- package/web/assets/matteFixRun-vgYrINet.js +0 -1
- package/web/assets/objectLocate-BJltm8Ob.js +0 -1
- package/web/assets/pendingMatte-BPyzzx4y.js +0 -2
- package/web/assets/personAi-gJu03SjU.js +0 -2
- package/web/assets/plateCamera-B2JvhjJw.js +0 -1
- package/web/assets/plateCameraMatch-ByB9nVQT.js +0 -2
- package/web/assets/plateFollow-C9S-l7RH.js +0 -2
- package/web/assets/plateMatte-J4qlNHnY.js +0 -2
- package/web/assets/plugin-guide.en-CGYh_9Su.js +0 -1
- package/web/assets/plugin-guide.vi-DMphSELb.js +0 -1
- package/web/assets/pluginAutomation-CkP3tA9r.js +0 -1
- package/web/assets/poseTracker-DGLbouqt.js +0 -1
- package/web/assets/productTools-CkaWF1bM.js +0 -2
- package/web/assets/remote-C7J0Tqhb.js +0 -1433
- package/web/assets/rotoMaskStore-DPziPKAN.js +0 -1
- package/web/assets/rotoscope-GvPFRUBg.js +0 -1
- package/web/assets/shot-worker-6dYkHPoL.js +0 -1
- package/web/assets/spellDuel-BD3m2ebA.js +0 -2
- package/web/assets/store-DW4E9xnW.js +0 -1
- package/web/assets/surfaceLight-aDSYU8Jg.js +0 -1
- package/web/assets/surfacePin-m83hCgGP.js +0 -2
- package/web/assets/timeline3d-DOw-CpZI.js +0 -2
- package/web/assets/timeline3dExport-BtYLU1pw.js +0 -1
- package/web/assets/timelineComp-B4GtoH2f.js +0 -1
- package/web/assets/timelineProps-D7MVutxu.js +0 -1
- package/web/assets/timelineText-BH09jfSM.js +0 -1
- package/web/assets/titleFrames-BI1DnLBn.js +0 -1
- package/web/assets/toonTools-CD9clJvN.js +0 -2
- package/web/assets/trackAnchor-sOjTtd3I.js +0 -1
- package/web/assets/userFonts-CwlKh9NR.js +0 -1
- package/web/assets/vfxBackground-Bq7lJvmZ.js +0 -2
- package/web/assets/videoExport-D4KbireJ.js +0 -1
- package/web/assets/views-ozVF4ABO.js +0 -1
- package/web/assets/weaponDuel-ZhX-tjGZ.js +0 -1
- package/web/assets/windowFrames-CpqX3kOM.js +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BfrDwjDI.js","assets/three.module-Bx43vjkH.js","assets/remote-DJd9xWjn.js","assets/index-CKtv7gGE.js","assets/i18n-BJppIrtF.js","assets/api-BFN7blbw.js","assets/titleFrameBudget-X7HLSDre.js","assets/gltfLoader-U0Eebg7v.js","assets/store-GFMJzaWS.js","assets/rotoMaskStore-DdpmT9C3.js","assets/sceneTrack-Bbov7zET.js","assets/timelineOps-afzSo188.js","assets/cameraTracker-BAQHuTV-.js","assets/textAnimators-BVXTl8bU.js","assets/timelineComp-Dx_kED5V.js","assets/rigTrack-XaMj1yaH.js","assets/clientJobs-CuuUyhEy.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as L}from"./titleFrameBudget-X7HLSDre.js";import{WebGLRenderer as q,ACESFilmicToneMapping as A,SRGBColorSpace as D,Color as c,Vector3 as P,EquirectangularReflectionMapping as I}from"./three.module-Bx43vjkH.js";class O{constructor(e){this.canvas=e,this.renderer=new q({canvas:e,antialias:!0,preserveDrawingBuffer:!0,powerPreference:"high-performance"}),this.renderer.toneMapping=A,this.renderer.outputColorSpace=D}renderer;tracer=null;envTex=null;raf=0;running=!1;disposed=!1;targetSamples=64;async start(e,a={}){if(this.stop(),this.disposed)return;const u=Math.max(8,Math.min(256,a.targetSamples??64)),T=Math.max(2,Math.min(8,a.bounces??4));this.targetSamples=u;const f=this.canvas.parentElement?.getBoundingClientRect(),w=Math.max(320,Math.round(f?.width||this.canvas.clientWidth||960)),M=Math.max(180,Math.round(f?.height||this.canvas.clientHeight||540)),E=Math.min(window.devicePixelRatio||1,1.5);this.renderer.setPixelRatio(E),this.renderer.setSize(w,M,!1),this.renderer.toneMappingExposure=e.look.exposure;try{const{WebGLPathTracer:h,ProceduralEquirectTexture:R}=await L(async()=>{const{WebGLPathTracer:o,ProceduralEquirectTexture:b}=await import("./index-BfrDwjDI.js");return{WebGLPathTracer:o,ProceduralEquirectTexture:b}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]));if(this.disposed)return;this.tracer||(this.tracer=new h(this.renderer));const r=this.tracer;r.bounces=T,r.transmissiveBounces=4,r.filterGlossyFactor=.5,r.multipleImportanceSampling=!0,r.dynamicLowRes=!1,r.renderScale=1,r.tiles.set(2,2),this.envTex?.dispose();const s=new R(512,256),_=new c(e.look.sky.zenith),v=new c(e.look.sky.horizon),C=new c(e.look.sky.ground),i=new c(e.look.sky.glow),z=new P(...e.sunDir).normalize(),d=Math.max(.25,e.look.sky.gain*Math.max(.45,e.look.envIntensity)),x=e.look.sky.glowPower,k=e.look.sky.disk,t=new c,m=new P;s.generationCallback=(o,b,U,G)=>{m.setFromSpherical(o).normalize();const g=m.y;g>=0?t.copy(v).lerp(_,Math.pow(Math.min(1,g),.55)):t.copy(v).multiplyScalar(.78).lerp(C,Math.min(1,-g*4.5));const p=Math.max(0,m.dot(z));if(x>0){const n=(Math.pow(p,6)*.16+Math.pow(p,48)*.65)*x;t.r+=i.r*n,t.g+=i.g*n,t.b+=i.b*n}if(k>0&&p>.9985){const n=(p-.9985)/.0015*Math.min(k,8);t.r+=i.r*n,t.g+=i.g*n,t.b+=i.b*n}G.setRGB(t.r*d,t.g*d,t.b*d)},s.update(),s.mapping=I,this.envTex=s;const S=a.view==="viewport"?e.camera:e.shotCamera;S.updateMatrixWorld(!0);const l=S.clone();l.aspect=w/M,l.updateProjectionMatrix(),l.updateMatrixWorld(!0);const B=e.prepareForTrace(),F=e.scene.environment,W=e.scene.background;e.scene.environment=s,e.scene.background=s,e.scene.updateMatrixWorld(!0);try{r.setScene(e.scene,l)}finally{e.scene.environment=F,e.scene.background=W,B()}if(this.disposed)return;this.running=!0,a.onProgress?.(0,u);const y=()=>{if(!this.running||this.disposed||!this.tracer)return;this.tracer.renderSample();const o=Math.floor(this.tracer.samples);a.onProgress?.(Math.min(o,this.targetSamples),this.targetSamples),o<this.targetSamples?this.raf=requestAnimationFrame(y):this.running=!1};this.raf=requestAnimationFrame(y)}catch(h){this.running=!1,a.onError?.(h instanceof Error?h.message:String(h))}}captureDataUrl(){return this.canvas.toDataURL("image/png")}stop(){this.running=!1,this.raf&&(cancelAnimationFrame(this.raf),this.raf=0)}dispose(){this.stop(),this.disposed=!0,this.tracer?.dispose(),this.tracer=null,this.envTex?.dispose(),this.envTex=null,this.renderer.dispose()}}export{O as ShotPathTracer};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/objectSegmenter-CziPuM61.js","assets/titleFrameBudget-X7HLSDre.js","assets/personHq-B1c0QVJT.js","assets/matteQuality-9X-jgJrH.js","assets/api-BFN7blbw.js","assets/i18n-BJppIrtF.js","assets/index-CKtv7gGE.js","assets/cutoutClean-CLYYAuXg.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{di as O,dj as C,_ as B,de as v,kx as H,hl as D,b_ as M,ky as j}from"./titleFrameBudget-X7HLSDre.js";import{o as T}from"./timelineOps-afzSo188.js";import{s as R,d as W,w as z,p as F}from"./personHq-B1c0QVJT.js";import{u as g}from"./store-GFMJzaWS.js";import{t as m}from"./i18n-BJppIrtF.js";import{al as _}from"./api-BFN7blbw.js";import"./sceneTrack-Bbov7zET.js";import"./cameraTracker-BAQHuTV-.js";import"./textAnimators-BVXTl8bU.js";import"./timelineComp-Dx_kED5V.js";import"./rigTrack-XaMj1yaH.js";import"./clientJobs-CuuUyhEy.js";import"./matteQuality-9X-jgJrH.js";import"./index-CKtv7gGE.js";const $=e=>document.querySelector(`video[data-clip-media="${e.id}"]`)?.currentSrc||e.url;function A(e,c=!1,t=!1){let d=null,s=-1;const l=(r,n="info")=>{const a=g.getState();d!==null&&a.dismissToast(d),a.toast(r,n),d=g.getState().toasts.at(-1)?.id??null};return l(c?m("Đang chạy Pro Cut cho “{0}” trên máy chủ… (khoảng 2 phút cho 1 phút video)",[e]):t?m("Đang tách vật thể AI cho “{0}”… (chạy trên máy, không tốn credit)",[e]):m("Đang tách người AI cho “{0}”… (chạy trên máy, không tốn credit)",[e])),{progress:r=>{const n=Math.floor(r.done/r.total*4)*25;n>s&&n<100&&n>0&&(s=n,l(c?m("Đang giữ lại người trong kết quả Pro Cut “{0}”… {1}%",[e,n]):t?m("Đang tách vật thể AI cho “{0}”… {1}%",[e,n]):m("Đang tách người AI cho “{0}”… {1}%",[e,n])))},done:(r,n="ok")=>l(r,n)}}const E=e=>{const c=document.querySelector(`video[data-clip-media="${e.id}"]`);return{duration:e.duration,sourceDuration:e.sourceDuration,width:c?.videoWidth||void 0,height:c?.videoHeight||void 0}};async function L(e,c,t){if(e.kind!=="video")throw Error(m("Chỉ tách người được trên clip video"));const d=await R({clip:e,url:$(e),signal:t,onProgress:c}),s=O(g.getState().clips.filter(l=>l.id!==e.id));if(d.data&&s+d.data.length>C)throw Error(m("Timeline đã chứa quá nhiều mặt nạ người AI (giới hạn lưu của dự án). Hãy xoá bớt mặt nạ ở clip khác hoặc cắt ngắn clip."));return d}async function N(e,c,t,d){const{segmentObject:s}=await B(async()=>{const{segmentObject:n}=await import("./objectSegmenter-CziPuM61.js");return{segmentObject:n}},__vite__mapDeps([0,1,2,3,4,5,6,7])),l=await s({clip:e,url:$(e),pts:c.pts.map(([n,a])=>({x:n,y:a})),at:c.at,signal:d,onProgress:t}),r=O(g.getState().clips.filter(n=>n.id!==e.id));if(l.data&&r+l.data.length>C)throw Error(m("Timeline đã chứa quá nhiều mặt nạ người AI (giới hạn lưu của dự án). Hãy xoá bớt mặt nạ ở clip khác hoặc cắt ngắn clip."));return l}const I=(e,c)=>e.map(t=>{if(t.id!==c||!t.personPending)return t;const d={...t};return delete d.personPending,d}),k=new Set,rt=e=>k.has(e);function at(e,c){for(const t of e)t.personPending&&t.kind==="video"&&!k.has(t.id)&&(k.add(t.id),q(t.id,c).finally(()=>k.delete(t.id)))}async function ct({ids:e,checkpoint:c=()=>{}}={}){const t=g.getState().clips.filter(s=>s.personPending&&s.kind==="video"&&(!e||e.includes(s.id))).map(s=>s.id),d=[];for(const s of t){if(k.has(s))continue;k.add(s);const l=new Set(g.getState().clips.filter(r=>r.person?.src==="object").map(r=>r.id));try{await q(s,c);const r=g.getState().clips.find(a=>a.id===s),n=!r?.personPending&&(!!r?.person||g.getState().clips.some(a=>a.person?.src==="object"&&!l.has(a.id)));d.push({clipId:s,ok:n,message:n?"matte completed":"matte dropped or failed"})}catch(r){d.push({clipId:s,ok:!1,message:String(r?.message||r)})}finally{k.delete(s)}}return d}async function q(e,c){let t=g.getState().clips.find(i=>i.id===e);if(!t?.personPending||g.getState().timelineTracks[t.track]?.locked||v(t.personPending).length&&(await V(t,c),t=g.getState().clips.find(i=>i.id===e),!t?.personPending||!H(t.personPending)))return;const s=t.personPending.job,l=A(t.label,!!s);let r;try{if(s){const i=await W(t,await z(s),{onProgress:l.progress}),o=t.person&&t.person.src!=="object"?t.person.pick:void 0;r=o?{...i,pick:o}:i}else r=t.person&&t.person.src!=="object"?t.person:await L(t,l.progress)}catch(i){_(s?"person-matte-hq":"person-matte",i.message,{op:"pending",...E(t)}),l.done(s?m("Chưa chạy Pro Cut được cho “{0}”: {1}",[t.label,i.message]):m("Chưa tách được người cho “{0}”: {1} — mở Roto → Tách người rồi “Đặt ra sau người”.",[t.label,i.message]),"error"),g.getState().clips.find(o=>o.id===e)?.personPending&&g.setState(o=>({clips:I(o.clips,e)}));return}const n=g.getState(),a=n.clips.find(i=>i.id===e);if(!a||!a.personPending&&!s)return;const f=D(n.clips,new Map([[e,r]])),u=[...(a.personPending?.behind??[]).filter(i=>f.some(o=>o.id===i)).map(i=>({op:"placeBehindPerson",clipId:i,sourceClipId:e})),...(a.personPending?.then??[]).map(i=>({...i,clipId:e}))],P=M({...n.timelineFormat,resolution:"720p"}),b=f.find(i=>i.id===e);for(let i=0;i<u.length;i++){const o=u[i];if(o.op!=="clonePerson"||o.feet!=null||!b)continue;const h=await F(b,Math.max(0,(o.start??b.start)-b.start),P.width,P.height).catch(()=>null);h&&(u[i]={...o,feet:h.feet,...o.horizon==null?{horizon:h.horizon}:{}})}const p=u.length?T(f,u,[],n.timelineTracks,n.timelineCamera,{noPendingMatte:!0,W:P.width,H:P.height}):null;g.setState({clips:I(n.clips,e)}),c(),g.setState({clips:p?p.clips:f,...p?{timelineTracks:p.tracks}:{}});const w=p?p.applied.filter(i=>i.startsWith("placeBehindPerson")).length:0,y=p?p.applied.filter(i=>/^(personEcho|clonePerson|personElectric|speedBolt)/.test(i)).length:0;l.done(p?.errors.length?m("Đã tách người cho “{0}”; {1} lớp chưa đặt ra sau người được: {2}",[a.label,p.errors.length,p.errors.join(" · ")]):y&&!w?m("Đã tách người cho “{0}” và tạo {1} hiệu ứng (vệt bóng / nhân bản).",[a.label,y]):u.length?m("Đã tách người cho “{0}” và đặt {1} lớp ra sau người.",[a.label,w]):s?m("Đã Pro Cut cho “{0}” ({1} khung).",[a.label,r.n]):m("Đã tách người cho “{0}” ({1} khung).",[a.label,r.n]),p?.errors.length?"error":"ok")}async function V(e,c){const t=e.id,d=v(e.personPending),s=A(e.label,!1,!0),l=new Map,r=[];for(const o of d)try{l.set(`${t}|${o.id}`,await N(e,{pts:o.pts,at:o.at},s.progress))}catch(h){r.push(`${o.name}: ${h.message}`),_("object-matte",h.message,{op:"pending",...E(e)})}const n=g.getState(),a=n.clips.find(o=>o.id===t);if(!a?.personPending)return;const f=v(a.personPending);let u=n.clips;for(const o of f)l.has(`${t}|${o.id}`)||(u=u.map(h=>h.id===t?j(h,o.id):h));const P=f.filter(o=>l.has(`${t}|${o.id}`)).flatMap(o=>{const h=o.behind.filter(S=>u.some(x=>x.id===S));return h.length?h.map(S=>({op:"placeBehindObject",clipId:S,sourceClipId:t,objectId:o.id})):[{op:"cutOutObject",clipId:t,objectId:o.id}]}),b=M({...n.timelineFormat,resolution:"720p"}),p=P.length?T(u,P,[],n.timelineTracks,n.timelineCamera,{noPendingMatte:!0,objectMattes:l,W:b.width,H:b.height}):null;let w=u;for(const o of f)w=w.map(h=>h.id===t?j(h,o.id):h);g.setState({clips:w}),p&&(c(),g.setState({clips:p.clips,timelineTracks:p.tracks}));const y=p?p.clips.filter(o=>!n.clips.some(h=>h.id===o.id)).length:0,i=[...r,...p?.errors??[]];s.done(i.length?m("Đã tách {0} vật thể của “{1}”; chưa tách được: {2}",[y,a.label,i.join(" · ")]):m("Đã tách {0} vật thể của “{1}”, mỗi vật thể một layer riêng.",[y,a.label]),i.length?"error":"ok")}export{E as clipDetail,rt as matteRunning,A as progressToast,at as resumePendingMattes,ct as runPendingMattes,L as segmentClipMatte,N as segmentClipObject};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/poseTracker-DZl8l2qS.js","assets/titleFrameBudget-X7HLSDre.js","assets/store-GFMJzaWS.js","assets/index-CKtv7gGE.js","assets/i18n-BJppIrtF.js","assets/personHq-B1c0QVJT.js","assets/matteQuality-9X-jgJrH.js","assets/api-BFN7blbw.js","assets/rigTrack-XaMj1yaH.js","assets/objectSegmenter-CziPuM61.js","assets/cutoutClean-CLYYAuXg.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as K}from"./titleFrameBudget-X7HLSDre.js";import{S as yt}from"./personHq-B1c0QVJT.js";import{a as ht,s as nt,i as xt,d as gt,b as pt,g as Mt,o as _t,t as bt,c as Pt,r as Et}from"./cutoutClean-CLYYAuXg.js";import"./matteQuality-9X-jgJrH.js";import"./api-BFN7blbw.js";import"./i18n-BJppIrtF.js";import"./index-CKtv7gGE.js";const wt=`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${yt}/wasm`,Ot=[0,11,12,13,14,23,24,25,26],st=512,Y=512;async function Rt(){if(typeof window<"u"&&window.__personPoseStub)return{detect:window.__personPoseStub,close:()=>{}};const[{FilesetResolver:b,PoseLandmarker:P},{POSE_MODEL_URL:n}]=await Promise.all([K(()=>import("./vision_bundle-9zIsgJJP.js"),[]),K(()=>import("./poseTracker-DZl8l2qS.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]))]),s=await b.forVisionTasks(wt),R=await P.createFromOptions(s,{baseOptions:{modelAssetPath:n,delegate:"CPU"},runningMode:"VIDEO",numPoses:4,minPoseDetectionConfidence:.4,minPosePresenceConfidence:.4,minTrackingConfidence:.4});let w=0;return{detect:(u,y)=>(w=Math.max(w+1,Math.round(y)),(R.detectForVideo(u,w).landmarks??[]).map(M=>M.map(h=>[h.x,h.y,h.visibility??1]))),close:()=>R.close()}}async function kt(b,P,n,s){const[{detect:R,close:w},{objectProbability:u}]=await Promise.all([Rt(),K(()=>import("./objectSegmenter-CziPuM61.js"),__vite__mapDeps([9,1,5,6,7,4,3,10]))]),y=Object.assign(document.createElement("canvas"),{width:st,height:Math.max(2,Math.round(st*P/b))}),A=y.getContext("2d",{willReadFrequently:!0}),M=Object.assign(document.createElement("canvas"),{width:Y,height:Y}),h=M.getContext("2d",{willReadFrequently:!0}),at=Object.assign(document.createElement("canvas"),{width:n,height:s}),Q=at.getContext("2d",{willReadFrequently:!0}),B=n*s,v={frames:0,ai:0,rejected:0,tPose:0,tPrep:0,tRead:0,tMap:0,tClean:0};return{stats:v,close:()=>{window.__cutoutDebug&&console.log("# ai stats",JSON.stringify(v)),w()},async frame(G,k,rt){v.frames++;let Z=performance.now();const C=t=>{const r=performance.now();v[t]+=r-Z,Z=r};A.drawImage(G,0,0,y.width,y.height);const tt=R(y,rt).filter(t=>Array.isArray(t)&&t.length>=33);C("tPose");const{label:L,regions:it}=ht(k,n,s,128),T=it.filter(t=>t.area>=.002*B).sort((t,r)=>r.area-t.area);if(!T.length)return null;const J=nt(k,n,s,3,!0),$=t=>[Math.max(0,Math.min(n-1,Math.floor(t[0]*n))),Math.max(0,Math.min(s-1,Math.floor(t[1]*s)))],D=t=>t[2]>.6&&t[0]>=0&&t[0]<1&&t[1]>=0&&t[1]<1,ct=t=>{const r=new Map;for(const m of t)if(D(m)){const[l,O]=$(m),i=L[O*n+l]||(J[O*n+l]>=128?At(L,n,s,l,O,3):0);i&&r.set(i,(r.get(i)??0)+1)}let f=0,x=1;for(const[m,l]of r)l>x&&(x=l,f=m);return f},V=new Map;for(const t of tt){const r=ct(t);r&&V.set(r,[...V.get(r)??[],t])}const I=(tt.length?T.filter(t=>V.has(t.id)):T.filter(t=>t.area>=.25*T[0].area)).slice(0,4);if(!I.length)return null;const N=new Float32Array(B),et=new Uint8Array(B),lt=(t,r)=>{for(let f=-2;f<=2;f++)for(let x=-2;x<=2;x++){const m=t+x,l=r+f;m>=0&&l>=0&&m<n&&l<s&&(et[l*n+m]=1)}};C("tPrep");for(const t of I){const r=V.get(t.id)??[],f=[];for(const e of r){for(const o of Ot)if(D(e[o])){const[c,d]=$(e[o]);J[d*n+c]>=128&&f.push([e[o][0]*n,e[o][1]*s])}if(D(e[11])&&D(e[12])){const o=(e[11][0]+e[12][0])/2,c=(e[11][1]+e[12][1])/2,[d,g]=$([o,c]);J[g*n+d]>=128&&f.push([o*n,c*s])}}{const e=t.x1-t.x0+3,o=t.y1-t.y0+3,c=t.x0-1,d=t.y0-1,g=p=>{const F=p%e+c,H=(p/e|0)+d;return F>=0&&H>=0&&F<n&&H<s&&L[H*n+F]===t.id},X=new Int32Array(e*o);for(let p=0;p<X.length;p++)X[p]=g(p)?1:0;for(const p of xt(gt(F=>X[F]===1,e,o),X,1,e,o,6))f.push([p[0]+c+.5,p[1]+d+.5])}if(!f.length)continue;let x=t.x0,m=t.y0,l=t.x1+1,O=t.y1+1;for(const e of r)for(const o of e)D(o)&&(x=Math.min(x,o[0]*n),m=Math.min(m,o[1]*s),l=Math.max(l,o[0]*n),O=Math.max(O,o[1]*s));const i=b/n,a=Et(x*i,m*i,l*i,O*i,b,P);C("tPrep"),h.drawImage(G,a.sx,a.sy,a.sw,a.sh,0,0,Y,Y);const E=await u(M,f.map(([e,o])=>({x:(e*i-a.sx)/a.sw,y:(o*i-a.sy)/a.sh})).filter(e=>e.x>0&&e.x<1&&e.y>0&&e.y<1).slice(0,24));C("tRead");const j=Math.max(4,Math.round(.15*Math.max(t.x1-t.x0,t.y1-t.y0))),U=Math.max(0,t.x0-j,Math.floor(a.sx/i)),q=Math.max(0,t.y0-j,Math.floor(a.sy/i)),dt=Math.min(n-1,t.x1+j,Math.ceil((a.sx+a.sw)/i)),mt=Math.min(s-1,t.y1+j,Math.ceil((a.sy+a.sh)/i)),_=dt-U+1,S=mt-q+1,W=new Uint8Array(_*S);for(let e=0;e<S;e++)for(let o=0;o<_;o++)L[(e+q)*n+o+U]===t.id&&(W[e*_+o]=255);const ut=nt(W,_,S,j,!0),z=new Float32Array(_*S);for(let e=0;e<S;e++){const o=((e+q+.5)*i-a.sy)/a.sh*E.height-.5;if(!(o<-.5||o>E.height-.5))for(let c=0;c<_;c++){const d=e*_+c;if(!ut[d])continue;const g=((c+U+.5)*i-a.sx)/a.sw*E.width-.5;g<-.5||g>E.width-.5||(z[d]=pt(E.data,E.width,E.height,g,o))}}const ot=Mt(E.data,.8)||_t(z,W,.5,128).inB<.5;ot?v.rejected++:v.ai++;for(let e=0;e<S;e++)for(let o=0;o<_;o++){const c=e*_+o,d=(e+q)*n+o+U,g=ot?W[c]?k[d]/255:0:z[c];g>N[d]&&(N[d]=g)}for(const[e,o]of f)lt(Math.floor(e),Math.floor(o));C("tMap")}bt(N,k,n,s,Math.max(2,Math.round(.012*Math.max(I[0].x1-I[0].x0,I[0].y1-I[0].y0)))),Q.drawImage(G,0,0,n,s);const ft=Pt(N,Q.getImageData(0,0,n,s).data,n,s,{seeds:et});return C("tClean"),ft}}}function At(b,P,n,s,R,w){for(let u=1;u<=w;u++)for(let y=-u;y<=u;y++)for(let A=-u;A<=u;A++){const M=s+A,h=R+y;if(M>=0&&h>=0&&M<P&&h<n&&b[h*P+M])return b[h*P+M]}return 0}export{kt as personAiReader};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/poseTracker-DZl8l2qS.js","assets/titleFrameBudget-X7HLSDre.js","assets/store-GFMJzaWS.js","assets/index-CKtv7gGE.js","assets/i18n-BJppIrtF.js","assets/rigTrack-XaMj1yaH.js","assets/matteQuality-9X-jgJrH.js","assets/api-BFN7blbw.js","assets/personAi-CQntGDqK.js","assets/cutoutClean-CLYYAuXg.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{a7 as at,da as _t,db as Pt,cw as kt,kz as z,kA as xt,kB as D,kC as St,kD as rt,kE as st,kF as At,kG as Ot,_ as L,kH as vt,d1 as bt}from"./titleFrameBudget-X7HLSDre.js";import{p as G,m as Ct,g as Tt,l as Ft,r as Rt,t as It,f as Dt,c as et,a as Lt,b as Vt}from"./matteQuality-9X-jgJrH.js";import{bO as it,e as Ut,a as Nt,s as jt,r as Ht}from"./api-BFN7blbw.js";import{t as _}from"./i18n-BJppIrtF.js";async function ie(t,e,r,a){const n=t.person;if(!n)return null;const s=await at(n),i=_t(s,n,Pt(t,e)),o=G(i,n.w,n.h);if(!o)return null;const u=(c,f)=>{const g=kt(t,c,f,e,r,a,n.mw,n.mh);return[g.px/r,g.py/a]},h=u(o.x+o.w/2,o.y+o.h),m=u(o.x+o.w/2,o.y)[1],l=c=>Math.round(c*1e3)/1e3;return{feet:[l(h[0]),l(h[1])],horizon:l(Math.min(h[1]-.1,m+.07*(h[1]-m)))}}const ct="1.0.1",lt=`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${ct}/wasm`,ht="https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_multiclass_256x256/float32/1/selfie_multiclass_256x256.tflite",Wt={multiclass:{path:ht,person:t=>{const e=t[0],r=new Float32Array(e.length);for(let a=0;a<e.length;a++)r[a]=1-e[a];return r}},selfie:{path:"/models/selfie_segmenter.tflite",person:t=>t[0]}},zt=640,Gt=640*640,Xt=512,Kt=32,Bt=8,ut=120,W=new Map;async function dt(t="selfie"){if(typeof window<"u"&&window.__personSegmenterStub)return window.__personSegmenterStub;let e;for(const r of t==="selfie"?["selfie"]:[t,"selfie"])try{return await $t(r)}catch(a){e=a,console.warn(`person model ${r} failed to load`,a)}throw e}function $t(t){const e=t,r=W.get(e);if(r)return r;const a=(t==="pose"?Qt():(async()=>{const{FilesetResolver:n,ImageSegmenter:s}=await L(async()=>{const{FilesetResolver:m,ImageSegmenter:l}=await import("./vision_bundle-9zIsgJJP.js");return{FilesetResolver:m,ImageSegmenter:l}},[]),i=await n.forVisionTasks(lt),o=Wt[t],u=await s.createFromOptions(i,{baseOptions:{modelAssetPath:o.path,delegate:"CPU"},runningMode:"VIDEO",outputConfidenceMasks:!0,outputCategoryMask:!1});let h=0;return(m,l)=>{h=Math.max(h+1,Math.round(l));const c=u.segmentForVideo(m,h);try{const f=c.confidenceMasks;if(!f?.length)throw Error("no mask");return{data:o.person(f.map(g=>g.getAsFloat32Array())),width:f[0].width,height:f[0].height}}finally{c.close()}}})()).catch(n=>{throw W.delete(e),n});return W.set(e,a),a}async function Qt(){const[{FilesetResolver:t,PoseLandmarker:e},{POSE_MODEL_URL:r}]=await Promise.all([L(()=>import("./vision_bundle-9zIsgJJP.js"),[]),L(()=>import("./poseTracker-DZl8l2qS.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]))]),a=await t.forVisionTasks(lt),n=await e.createFromOptions(a,{baseOptions:{modelAssetPath:r,delegate:"CPU"},runningMode:"VIDEO",numPoses:4,outputSegmentationMasks:!0,minPoseDetectionConfidence:.4,minPosePresenceConfidence:.4,minTrackingConfidence:.4});let s=0;return(i,o)=>{s=Math.max(s+1,Math.round(o));const u=n.detectForVideo(i,s);try{const h=u.segmentationMasks??[];if(!h.length)return{data:new Float32Array(i.width*i.height),width:i.width,height:i.height};const m=h[0].width,l=h[0].height,c=new Float32Array(m*l);for(const f of h){const g=f.getAsFloat32Array();for(let w=0;w<c.length;w++)g[w]>c[w]&&(c[w]=g[w])}return{data:c,width:m,height:l}}finally{u.close()}}}async function Jt(t){return await(await dt())(t,performance.now())}function Yt(t,e,r){const a=new Uint8Array(e*r);for(let n=0;n<r;n++){const s=Math.floor(n*t.height/r),i=Math.max(s+1,Math.floor((n+1)*t.height/r));for(let o=0;o<e;o++){const u=Math.floor(o*t.width/e),h=Math.max(u+1,Math.floor((o+1)*t.width/e));let m=0,l=0;for(let c=s;c<i&&c<t.height;c++)for(let f=u;f<h&&f<t.width;f++)m+=t.data[c*t.width+f],l++;a[n*e+o]=Math.round(Math.max(0,Math.min(1,l?m/l:0))*255)}}return a}const K={r:.5,eps:.001,lo:.3,hi:.7};function X(t,e,r,a,n,s=!0,i=K){let o=t.data;if(s&&e&&e.length===t.width*t.height*4){const u=Math.max(2,Math.round(Math.max(t.width,t.height)/128));o=Ct(Tt(o,Ft(e,t.width,t.height),t.width,t.height,{r:Math.max(1,Math.round(u*i.r)),eps:i.eps}),i.lo,i.hi)}return Rt(o,t.width,t.height,r,a,n)}const nt=(t,e)=>Math.abs(t.currentTime-e)<=1e-4?Promise.resolve():new Promise((r,a)=>{const n=window.setTimeout(()=>a(Error(_("Seek video quá lâu"))),8e3);t.onseeked=()=>{window.clearTimeout(n),r()},t.currentTime=e});function mt(t,e=!0){const a=Object.assign(document.createElement("canvas"),{width:t.videoWidth,height:t.videoHeight}),n=a.getContext("2d"),s=()=>(n.drawImage(t,0,0,a.width,a.height),a);let i=null,o=!1,u=!e||typeof t.requestVideoFrameCallback!="function";return async h=>u||i===null?(await nt(t,h),i=h,s()):i>=h-.02||o||await new Promise(l=>{const c=window.setTimeout(()=>l(!1),4e3),f=(g,w)=>{i=w.mediaTime,w.mediaTime>=h-.02?(window.clearTimeout(c),s(),t.pause(),l(!0)):t.requestVideoFrameCallback(f)};t.onended=()=>{o=!0,window.clearTimeout(c),l(!0)},t.requestVideoFrameCallback(f),t.play().catch(()=>{window.clearTimeout(c),l(!1)})})?a:(u=!0,t.pause(),await nt(t,h),i=h,s())}async function ft({clip:t,url:e,fps:r,signal:a,onProgress:n,quality:s={}}){if(t.kind!=="video")throw Error(_("Chỉ tách người được trên clip video"));const i=await dt(s.model),o=Object.assign(document.createElement("video"),{muted:!0,playsInline:!0,preload:"auto",crossOrigin:"anonymous"});o.src=e;const u=typeof window<"u"&&!!window.__personSegmenterStub,{crop:h=!u,refine:m=!0,smooth:l=!0,levels:c=Kt,edge:f=K}=s,g=s.ai??(!u&&s.model!=="pose"&&t.duration*(t.playbackRate||1)<=ut);try{await new Promise((d,y)=>{o.onloadeddata=()=>d(),o.onerror=()=>y(Error(_("Không đọc được video để tách người (CORS / định dạng)")))});const w=o.videoWidth,M=o.videoHeight,p=Math.min(s.inputW??zt,w,Math.round(Math.sqrt(Gt*w/M))),k=Math.max(2,Math.round(p*M/w)),x=t.inPoint||0,V=t.duration*(t.playbackRate||1),Q=s.plan??(r?{...st(w,M),fps:r}:At(w,M,V)),{w:S,h:A}=Q;let O=Q.fps;for(;Math.ceil(V*O)+1>Ot&&O>1;)O/=2;const J=Math.max(1,Math.ceil(V*O)+1),Y=Object.assign(document.createElement("canvas"),{width:p,height:k}),Z=Y.getContext("2d",{willReadFrequently:!0}),C=document.createElement("canvas"),q=C.getContext("2d",{willReadFrequently:!0}),pt={x:0,y:0,w:1,h:1},U=B({mw:w,mh:M,w:S,h:A,fps:O,s0:x},c),N=l?It(d=>U.push(d)):null,gt=mt(o,s.step!==!1);let v=null;if(g)try{v=await(await L(async()=>{const{personAiReader:d}=await import("./personAi-CQntGDqK.js");return{personAiReader:d}},__vite__mapDeps([8,1,9,6,7,4,3]))).personAiReader(w,M,S,A)}catch(d){console.warn("person AI cut-out",d)}let T=o,F=null,j=null,H=0;const tt=async()=>{Z.drawImage(T,0,0,p,k);const d=await i(Y,++H);return j=X(d,m?Z.getImageData(0,0,p,k).data:null,pt,S,A,m,f)},Mt=(d,y)=>!d||!y?d??y:{x:Math.min(d.x,y.x),y:Math.min(d.y,y.y),w:Math.max(d.x+d.w,y.x+y.w)-Math.min(d.x,y.x),h:Math.max(d.y+d.h,y.y+y.h)-Math.min(d.y,y.y)},yt=()=>Mt(G(F,S,A,{thr:64}),j&&G(j,S,A,{thr:64}));for(let d=0;d<J;d++){if(a?.aborted)throw new DOMException("Đã huỷ","AbortError");const y=Math.max(0,Math.min(o.duration-1/60,x+d/O));T=await gt(y);const E=h&&F&&d%Bt?Dt(yt(),w,M):null;let P;if(E){const b=Math.min(1,Xt/Math.max(E.sw,E.sh)),R=Math.max(2,Math.round(E.sw*b)),I=Math.max(2,Math.round(E.sh*b));(C.width!==R||C.height!==I)&&Object.assign(C,{width:R,height:I}),q.drawImage(T,E.sx,E.sy,E.sw,E.sh,0,0,R,I);const Et=await i(C,++H);P=X(Et,m?q.getImageData(0,0,R,I).data:null,{x:E.sx/w,y:E.sy/M,w:E.sw/w,h:E.sh/M},S,A,m,f),et(P)<.5*et(F)&&(P=await tt())}else P=await tt();if(F=P,v)try{P=await v.frame(T,P,++H)??P}catch(b){console.warn("person AI cut-out",b),v.close(),v=null}N?N.push(P):U.push(P),n?.({done:d+1,total:J}),d%4===3&&await new Promise(b=>setTimeout(b,0))}return N?.finish(),v?.close(),await U.finish({},{store:s.store!==!1})}finally{o.removeAttribute("src"),o.load()}}function B({mw:t,mh:e,w:r,h:a,fps:n,s0:s},i=32){const o=vt(r,a),u=z({w:r,h:a,lv:i,ck:o});return{push:h=>u.push(h),async finish(h={},{store:m=!0}={}){if(!u.n)throw Error(_("Không đọc được khung hình nào của video"));let l=u.finish(),c=u.n,f=n;for(;l.length>xt;){if(c<4)throw Error(_("Clip quá dài để lưu mặt nạ người — hãy cắt ngắn clip."));const p=await D({v:2,w:r,h:a,n:c,ck:o,lv:i,data:l}),k=z({w:r,h:a,lv:i,ck:o});for(let x=0;x<c;x+=2)k.push(p[x]);l=k.finish(),c=k.n,f/=2}const g={v:2,mw:t,mh:e,w:r,h:a,fps:f,s0:+s.toFixed(4),n:c,ck:o,lv:i,data:l,feather:.008,grow:-.1,...h};if(!m)return g;const w=await D(g);let M=g;try{const p=await it(l);M={...g,ref:p},delete M.data}catch(p){if(l.length>St)throw p}return rt(M,w),M}}}async function Zt(t,{mw:e,mh:r,w:a,h:n,fps:s,s0:i},o={},u={}){const{lv:h,...m}=o,l=B({mw:e,mh:r,w:a,h:n,fps:s,s0:i},h??16);for(const c of t)l.push(c);return l.finish(m,u)}const ce=Object.freeze(Object.defineProperty({__proto__:null,AI_MAX_SECONDS:ut,EDGE:K,MULTICLASS_URL:ht,SEGMENTER_VERSION:ct,downscaleMask:Yt,frameStepper:mt,matteWriter:B,packMatte:Zt,personProbability:Jt,refinedFrame:X,segmentPerson:ft},Symbol.toStringTag,{value:"Module"})),wt="clipoox:person-hq",$=t=>Math.round(t.duration*Math.abs(t.playbackRate||1)*1e3)/1e3,ot=600,le=async t=>(await Ut(wt,{span:$(t)})).credits;function qt(t){return t.kind!=="video"?_("Chỉ tách người được trên clip video"):t.gcsUri?$(t)>ot?_("Pro Cut tối đa {0} phút mỗi lần — hãy tách clip ngắn hơn",[ot/60]):null:_("Pro Cut cần video đã lưu trong Media (tải lên trước).")}async function he(t,{canvasId:e,mw:r,mh:a}={}){const n=qt(t);if(n)throw Error(n);const s=await jt({gcsUri:t.gcsUri}),i=r&&a?{mw:Math.round(r),mh:Math.round(a)}:{};return(await Ht(wt,{videoUrl:s,trimStart:t.inPoint||0,span:$(t),...i},e)).jobId}async function ue(t,{signal:e,every:r=4e3}={}){for(let a=0;;){if(e?.aborted)throw new DOMException("Đã huỷ","AbortError");let n=null;try{n=await Nt(t,!0),a=0}catch(s){const i=s.status;if(i===403||i===404||++a>5)throw s}if(n?.status==="succeeded"){const s=n.output?.matte;if(!s)throw Error(_("Pro Cut không trả về mặt nạ"));return bt(s)}if(n?.status==="failed")throw Error(n.error?_(n.error):_("Pro Cut thất bại — credit đã được hoàn lại"));await new Promise(s=>setTimeout(s,r))}}const te=160,ee=6,ne=t=>document.querySelector(`video[data-clip-media="${t.id}"]`)?.currentSrc||t.url;async function de(t,e,{signal:r,onProgress:a}={}){const n=await ft({clip:t,url:ne(t),signal:r,onProgress:a,quality:{model:"pose",plan:{...st(e.mw,e.mh,te),fps:ee},refine:!1,levels:16,store:!1}}),[s,i]=await Promise.all([at({...e,pick:void 0}),D(n)]),o=z({w:e.w,h:e.h,lv:e.lv??32,ck:e.ck}),u=Lt(e.w,e.h);for(let c=0;c<e.n;c++){if(r?.aborted)throw new DOMException("Đã huỷ","AbortError");const f=Math.max(0,Math.min(n.n-1,(e.s0+c/e.fps-n.s0)*n.fps)),g=i[Math.floor(f)],w=i[Math.min(n.n-1,Math.floor(f)+1)],M=new Uint8Array(g.length);for(let p=0;p<M.length;p++)M[p]=g[p]>w[p]?g[p]:w[p];o.push(u.keep(s[c],Vt(M,n.w,n.h,e.w,e.h))),c%24===23&&await new Promise(p=>setTimeout(p,0))}const h=o.finish(),m={...e,ref:void 0,data:h};delete m.ref;const l={...e,ref:await it(h)};return rt(l,await D(m)),l}export{ht as M,ct as S,qt as a,le as b,he as c,de as d,Yt as e,Zt as f,mt as g,$ as h,ce as i,B as m,ie as p,ft as s,ue as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{aO as R,du as O,fr as T,dk as q,bn as P,a7 as F,fs as k}from"./remote-DJd9xWjn.js";import{nG as W,ng as _,nh as D,nH as H,nI as j,nJ as U,nK as B,l7 as G}from"./titleFrameBudget-X7HLSDre.js";import{plateMatte as J,matteAt as L}from"./plateMatte-zTyuHHqh.js";import{t as C}from"./i18n-BJppIrtF.js";import"./index-CKtv7gGE.js";import"./api-BFN7blbw.js";import"./three.module-Bx43vjkH.js";import"./gltfLoader-U0Eebg7v.js";import"./store-GFMJzaWS.js";import"./rotoMaskStore-DdpmT9C3.js";import"./sceneTrack-Bbov7zET.js";import"./timelineOps-afzSo188.js";import"./cameraTracker-BAQHuTV-.js";import"./textAnimators-BVXTl8bU.js";import"./timelineComp-Dx_kED5V.js";import"./rigTrack-XaMj1yaH.js";import"./clientJobs-CuuUyhEy.js";import"./rotoMatte-i-cJTYmK.js";const X=15,Y=240,$=480;async function z(i,a,n,o,s,M){const e=Object.assign(document.createElement("video"),{muted:!0,playsInline:!0,preload:"auto",crossOrigin:"anonymous"});e.src=i;try{await new Promise((h,g)=>{e.onloadeddata=()=>h(),e.onerror=()=>g(new Error(C("Không đọc được video nền (CORS / định dạng)")))});const f=e.videoWidth||1280,p=e.videoHeight||720,r=Math.min($,f),m=Math.max(2,Math.round(r*p/f)),c=Object.assign(document.createElement("canvas"),{width:r,height:m}),x=c.getContext("2d",{willReadFrequently:!0}),w=Math.max(2,Math.round(n*o)+1),v=[],u=[];for(let h=0;h<w;h++){if(s?.aborted)throw new DOMException("Đã huỷ","AbortError");const g=Math.min(n,h/o),b=Math.max(0,Math.min(e.duration-1/60,a+g));Math.abs(e.currentTime-b)>1e-4&&await new Promise((d,S)=>{const A=window.setTimeout(()=>S(new Error(C("Seek video quá lâu"))),8e3);e.onseeked=()=>{window.clearTimeout(A),d()},e.currentTime=b}),x.drawImage(e,0,0,r,m),v.push(B(x.getImageData(0,0,r,m).data,r,m)),u.push(g),M?.(h+1,w)}return{frames:v,times:u,W:r,H:m}}finally{e.removeAttribute("src"),e.load()}}function N(i){const a=F(i,0),n=k(a);return{position:[...a.position],q:n.quaternion.toArray(),distance:Math.max(.5,Math.hypot(...a.target.map((s,M)=>s-a.position[M]))),lens:a.lens}}async function ft(i,a){const n=i.plate,o=i.shots.find(t=>t.id===i.activeShot);if(!n||!o)throw new Error("no-plate");const s=P.plateUrl?await P.plateUrl(n).catch(()=>n.url):n.url,M=a.fps??X,e=Math.min(o.duration,n.duration),{frames:f,times:p,W:r}=await z(s,n.inPoint,e,M,a.signal,a.progress),m=O(o.aspect),c=N(o),x=G(c.lens,r,m),w=await J(i,s,{signal:a.signal}),v=w?t=>{const l=L(w,n.inPoint+p[t]);return l.box?(y,K)=>l.at(y,K)>.05||l.at(y+.02,K)>.05||l.at(y-.02,K)>.05:null}:null,u=_(f,x,{skip:v}),h=u.filter(t=>t.lost).length;if(h>u.length/2)throw new Error("camera-not-found");const g=D(f,x,{skip:v}),b=Math.ceil(u.length/Y);let d,S="turn",A=null,E=0;if(g?.mode==="free"){const t=H(g,c);d=j(t.cams,p,o.duration,{distance:c.distance,lens:c.lens,every:b,newId:a.newId}),S="travel",A=t.by;for(let l=1;l<t.cams.length;l++)E+=Math.hypot(...t.cams[l].position.map((y,K)=>y-t.cams[l-1].position[K]))}else d=U(u,p,o.duration,c,{W:r,aspect:m,every:b,newId:a.newId});const I=d.map(t=>Math.atan2(t.target[0]-t.position[0],-(t.target[2]-t.position[2]))*180/Math.PI);return{stage:{...i,shots:i.shots.map(t=>{if(t.id!==o.id)return t;const{handheld:l,...y}=t;return{...y,...q(d)}})},keys:d.length,frames:u.length,lost:h,mode:S,scale:A,travel:Math.round(E*100)/100,matte:w?w.made?"made":"timeline":"none",pan:Math.round((Math.max(...I)-Math.min(...I))*10)/10,lens:[Math.min(...d.map(t=>t.lens)),Math.max(...d.map(t=>t.lens))]}}function wt(i,a={}){const n=i.shots.find(r=>r.id===i.activeShot),o=R(n),s=O(n.aspect),M=s>=1?1920:Math.round(1920*s/2)*2,e=s>=1?Math.round(1920/s/2)*2:1920,f=Math.max(2,Math.round(n.duration*o)+1),p=[];for(let r=0;r<f;r++){const m=Math.min(n.duration,r/o),c=T(n,n.duration?m/n.duration:0);p.push({t:m,position:c.position.toArray(),q:c.quaternion.toArray(),lens:c.getFocalLength()})}return W(p,{fps:o,width:M,height:e,name:`${n.name} · Clipoox`,plate:a.plate??"",maxKeys:a.maxKeys})}export{X as TRACK_FPS,Y as TRACK_MAX_KEYS,wt as shotBlenderScript,ft as trackPlateCamera};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/plateFollow-4iGUDTu1.js","assets/titleFrameBudget-X7HLSDre.js","assets/remote-DJd9xWjn.js","assets/index-CKtv7gGE.js","assets/i18n-BJppIrtF.js","assets/api-BFN7blbw.js","assets/three.module-Bx43vjkH.js","assets/gltfLoader-U0Eebg7v.js","assets/store-GFMJzaWS.js","assets/rotoMaskStore-DdpmT9C3.js","assets/sceneTrack-Bbov7zET.js","assets/timelineOps-afzSo188.js","assets/cameraTracker-BAQHuTV-.js","assets/textAnimators-BVXTl8bU.js","assets/timelineComp-Dx_kED5V.js","assets/rigTrack-XaMj1yaH.js","assets/clientJobs-CuuUyhEy.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as rt}from"./titleFrameBudget-X7HLSDre.js";import{n as st,fs as at}from"./remote-DJd9xWjn.js";import{mainBody as it,worldOf as ct,smooth as ht,depthOf as ut,lowestFoot as mt,rayOf as nt,FOOT_HEIGHT as ft,median as W}from"./plateFollow-4iGUDTu1.js";import"./index-CKtv7gGE.js";import"./i18n-BJppIrtF.js";import"./api-BFN7blbw.js";import"./three.module-Bx43vjkH.js";import"./gltfLoader-U0Eebg7v.js";import"./store-GFMJzaWS.js";import"./rotoMaskStore-DdpmT9C3.js";import"./sceneTrack-Bbov7zET.js";import"./timelineOps-afzSo188.js";import"./cameraTracker-BAQHuTV-.js";import"./textAnimators-BVXTl8bU.js";import"./timelineComp-Dx_kED5V.js";import"./rigTrack-XaMj1yaH.js";import"./clientJobs-CuuUyhEy.js";const B=Math.PI/180,et=(t,n)=>[t[1]*n[2]-t[2]*n[1],t[2]*n[0]-t[0]*n[2],t[0]*n[1]-t[1]*n[0]],pt=(t,n)=>t[0]*n[0]+t[1]*n[1]+t[2]*n[2],Q=t=>{const n=Math.hypot(t[0],t[1],t[2])||1;return[t[0]/n,t[1]/n,t[2]/n]},z=Object.freeze({lean:25,lines:60,minShare:.06,agree:.7,maxTilt:40,minLines:6,minSupport:1});function dt(t,n,r,{lean:s=z.lean,minShare:M=z.minShare,max:i=z.lines}={}){const y=n*r,E=new Float32Array(y),A=new Float32Array(y),m=new Float32Array(y);let x=0,v=0;for(let c=1;c<r-1;c++)for(let h=1;h<n-1;h++){const a=c*n+h,d=t[a-n-1],H=t[a-n],_=t[a-n+1],b=t[a-1],w=t[a+1],q=t[a+n-1],R=t[a+n],S=t[a+n+1],V=_+2*w+S-d-2*b-q,I=q+2*R+S-d-2*H-_,G=Math.hypot(V,I);E[a]=V,A[a]=I,m[a]=G,x+=G,v+=G*G}const p=x/y,T=Math.max(48,p+1.2*Math.sqrt(Math.max(0,v/y-p*p))),P=.5,g=Math.round(2*s/P)+1,u=Math.ceil(Math.hypot(n,r)/2)+2,F=new Uint16Array(g*(2*u+1)),o=new Float32Array(g),l=new Float32Array(g);for(let c=0;c<g;c++){const h=(-s+c*P)*B;o[c]=Math.cos(h),l[c]=Math.sin(h)}const e=[];for(let c=1;c<r-1;c++)for(let h=1;h<n-1;h++){const a=c*n+h;if(m[a]<T||m[a]<m[a-1]||m[a]<=m[a+1])continue;let d=Math.atan2(A[a],E[a])/B;if(d>90?d-=180:d<-90&&(d+=180),Math.abs(d)>s)continue;const H=m[a-1]-2*m[a]+m[a+1],_=H<-1e-6?Math.max(-.5,Math.min(.5,.5*(m[a-1]-m[a+1])/H)):0;e.push(h+_-n/2,c-r/2,d);const b=Math.max(0,Math.round((d-3+s)/P)),w=Math.min(g-1,Math.round((d+3+s)/P));for(let q=b;q<=w;q++)F[q*(2*u+1)+Math.round(e[e.length-3]*o[q]+e[e.length-2]*l[q])+u]++}const O=[],C=Math.max(12,M*r*.6);for(let c=0;c<g;c++)for(let h=0;h<=2*u;h++){const a=F[c*(2*u+1)+h];a>=C&&O.push([a,c,h])}O.sort((c,h)=>h[0]-c[0]);const L=e.length/3,N=new Uint8Array(L),j=[],D=c=>{let h=0,a=0,d=0,H=0;for(const q of c){const R=e[q*3],S=e[q*3+1];h+=S,a+=R,d+=S*S,H+=R*S}const _=c.length,b=_*d-h*h;if(_<2||Math.abs(b)<1e-6)return null;const w=(_*H-a*h)/b;return{p:(a-w*h)/_,q:w}};let K=0;for(const[,c,h]of O){if(j.length>=i||K++>i*6)break;const a=o[c],d=l[c],H=h-u,_=-s+c*P;let b=[];for(let f=0;f<L;f++)!N[f]&&Math.abs(e[f*3]*a+e[f*3+1]*d-H)<=1.6&&Math.abs(e[f*3+2]-_)<=7&&b.push(f);if(b.length<C)continue;let w=D(b);if(!w)continue;const q=(f,J)=>{const lt=Math.hypot(1,f.q),tt=[];for(let U=0;U<L;U++)!N[U]&&Math.abs(e[U*3]-f.p-f.q*e[U*3+1])/lt<=J&&Math.abs(e[U*3+2]-_)<=10&&tt.push(U);return tt};b=q(w,1.2),w=D(b)??w,b.sort((f,J)=>e[f*3+1]-e[J*3+1]);let R=0,S=0,V=0;for(let f=1;f<=b.length;f++)(f===b.length||e[b[f]*3+1]-e[b[f-1]*3+1]>6)&&(e[b[f-1]*3+1]-e[b[V]*3+1]>e[b[S]*3+1]-e[b[R]*3+1]&&(R=V,S=f-1),V=f);const I=b.slice(R,S+1);if(I.length<C)continue;w=D(I)??w;const G=Math.hypot(1,w.q),X=e[I[0]*3+1],Y=e[I[I.length-1]*3+1],Z=(Y-X)*G;let $=0;for(const f of I)$+=((e[f*3]-w.p-w.q*e[f*3+1])/G)**2;if(!(Z<M*r||Math.sqrt($/I.length)>.8||Math.abs(Math.atan(-w.q)/B-_)>2.5)){for(const f of q(w,2))e[f*3+1]>=X-2&&e[f*3+1]<=Y+2&&(N[f]=1);j.push({x0:w.p+w.q*X+n/2,y0:X+r/2,x1:w.p+w.q*Y+n/2,y1:Y+r/2,length:Z})}}return j.sort((c,h)=>h.length-c.length).slice(0,i)}function Mt(t,n,r,s,{agree:M=z.agree,maxTilt:i=z.maxTilt}={}){const y=t.map(o=>({n:Q(et([o.x0-n/2,o.y0-r/2,s],[o.x1-n/2,o.y1-r/2,s])),length:o.length}));if(y.length<3)return null;const E=Math.sin(M*B),A=o=>{let l=0;const e=[];for(const O of y)Math.abs(pt(O.n,o))<E&&(l+=O.length,e.push(O));return{score:l,inl:e}},m=o=>o[1]>0?[-o[0],-o[1],-o[2]]:o;let x=null;const v=[[0,-1,0]];for(let o=0;o<y.length;o++)for(let l=o+1;l<y.length;l++){const e=et(y[o].n,y[l].n);Math.hypot(...e)>1e-4&&v.push(m(Q(e)))}for(const o of v){if(Math.acos(Math.min(1,-o[1]))>i*B)continue;const l=A(o);(!x||l.score>x.score)&&(x={...l,U:o})}if(!x||x.inl.length<3)return null;const p=[0,0,0,0,0,0,0,0,0];for(const o of x.inl)for(let l=0;l<3;l++)for(let e=0;e<3;e++)p[l*3+e]+=o.length*o.n[l]*o.n[e];const T=p[0]+p[4]+p[8];p[0]+=T*1e-6,p[4]+=T*1e-6,p[8]+=T*1e-6;const g=(o=>{const[l,e,O,C,L,N,j,D,K]=o,c=L*K-N*D,h=-(C*K-N*j),a=C*D-L*j,d=l*c+e*h+O*a;return Math.abs(d)<1e-18?null:[c/d,-(e*K-O*D)/d,(e*N-O*L)/d,h/d,(l*K-O*j)/d,-(l*N-O*C)/d,a/d,-(l*D-e*j)/d,(l*L-e*C)/d]})(p);let u=x.U;if(g)for(let o=0;o<12;o++)u=m(Q([g[0]*u[0]+g[1]*u[1]+g[2]*u[2],g[3]*u[0]+g[4]*u[1]+g[5]*u[2],g[6]*u[0]+g[7]*u[1]+g[8]*u[2]]));Math.acos(Math.min(1,-u[1]))>i*B&&(u=x.U);const F=x.inl.reduce((o,l)=>o+l.length,0)/r;return{tilt:Math.asin(Math.max(-1,Math.min(1,u[2])))/B,roll:Math.atan2(u[0],-u[1])/B,lines:x.inl.length,support:F,up:u}}function gt(t,n,r,s){const M=dt(t,n,r),i=Mt(M,n,r,s/36*n);return i&&i.lines>=z.minLines&&i.support>=z.minSupport?{...i,found:M.length}:null}const ot=28,yt=1.5,k=t=>Math.round(t*1e3)/1e3,bt=(t,n)=>{const r=t.filter(Number.isFinite).sort((s,M)=>s-M);return r.length?r[Math.min(r.length-1,Math.floor(r.length*n))]:NaN},wt=(t,n,r,s)=>{const M=n*Math.PI/180;return at({position:[0,0,0],target:[0,Math.sin(M),-Math.cos(M)],lens:t,roll:r,aspect:s})};function xt(t,n="16:9"){const r=t.lens??ot,s=t.tilt??t.seen?.tilt??0,M=t.roll??(t.tilt==null?t.seen?.roll:null)??0,i={lens:t.lens!=null?"given":"assumed",tilt:t.tilt!=null?"given":t.seen?"lines":"level",height:t.height!=null?"given":"default",place:"default"},y=wt(r,s,M,n),E=it(t.frames.filter(p=>p.lm&&p.lm.length>=33),t.aspect).filter(p=>p.lm);let A=t.height??yt,m=[0,-4];if(E.length>=2){const p=E.map(l=>l.wl&&l.wl.length>=33?l.wl:ct(l.lm,t.aspect)),T=ht(E.map((l,e)=>ut(y,l.lm,p[e]))),P=E.map((l,e)=>{const O=mt(l.lm);return-nt(y,l.lm[O][0],l.lm[O][1]).y*T[e]+ft[O]}),g=bt(P,.7);t.height==null&&g>.15&&g<30&&(A=g,i.height="feet");const u=E.map((l,e)=>nt(y,(l.lm[23][0]+l.lm[24][0])/2,(l.lm[23][1]+l.lm[24][1])/2).multiplyScalar(T[e])),F=u.filter((l,e)=>Math.abs(P[e]-A)<.2*A),o=F.length>=2?F:u;m=[W(o.map(l=>l.x)),W(o.map(l=>l.z))],i.place="person"}const x=s*Math.PI/180,v=[k(-m[0]),k(A),k(-m[1])];return{lens:k(r),height:k(A),tilt:k(s),roll:k(M),distance:k(Math.hypot(m[0],m[1])),position:v,target:[k(v[0]),k(v[1]+Math.sin(x)*4),k(v[2]-Math.cos(x)*4)],by:i,lines:t.tilt==null?t.seen?.lines??0:0}}function At(t,n){const r={...t.plate,match:{lens:n.lens,height:n.height,tilt:n.tilt,roll:n.roll}};return{...t,plate:r,shots:t.shots.map(s=>s.id!==t.activeShot?s:{...s,position:n.position,target:n.target,lens:n.lens,roll:n.roll,endPosition:n.position,endTarget:n.target,endLens:n.lens,motion:"static",cameraKeys:[]})}}const vt=t=>{const n=t.shots.find(r=>r.id===t.activeShot);return!!t.plate&&!!n&&!n.cameraKeys?.length};function Ut(t){const n=t.shots.find(M=>M.id===t.activeShot),r=st().shots[0],s=(M,i)=>M.every((y,E)=>Math.abs(y-i[E])<1e-6);return!!n&&s(n.position,r.position)&&s(n.target,r.target)&&Math.abs(n.lens-r.lens)<1e-6&&!n.roll}async function zt(t,n={},r={}){const s=t.plate,M=t.shots.find(v=>v.id===t.activeShot);if(!s||!M)throw new Error("no-plate");if(!vt(t))throw new Error("camera-keyed");const[i,y]=(M.aspect||"16:9").split(":").map(Number);let E=[],A=i/y||16/9,m=null;if(!(n.lens!=null&&n.height!=null&&n.tilt!=null)){const{readPlate:v}=await rt(async()=>{const{readPlate:T}=await import("./plateFollow-4iGUDTu1.js");return{readPlate:T}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),p=await v(t,r);E=p.tracked.frames,A=i/y||p.tracked.aspect,n.tilt==null&&(m=await Et(p.url,s.inPoint,p.span,n.lens??ot,r.signal).catch(T=>{if(T.name==="AbortError")throw T;return null}))}const x=xt({frames:E,aspect:A,lens:n.lens??null,tilt:n.tilt??null,roll:n.roll??null,height:n.height??null,seen:m},M.aspect);return{stage:At(t,x),match:x,found:E.filter(v=>v.lm).length}}async function Et(t,n,r,s,M){const i=Object.assign(document.createElement("video"),{muted:!0,playsInline:!0,preload:"auto",crossOrigin:"anonymous"});i.src=t;try{await new Promise((T,P)=>{i.onloadeddata=()=>T(),i.onerror=()=>P(new Error("plate-unreadable"))});const y=i.videoWidth||1280,E=i.videoHeight||720,A=Math.min(960,y),m=Math.max(2,Math.round(A*E/y)),x=Object.assign(document.createElement("canvas"),{width:A,height:m}),v=x.getContext("2d",{willReadFrequently:!0}),p=[];for(const T of[.1,.3,.5,.7,.9]){if(M?.aborted)throw new DOMException("Đã huỷ","AbortError");const P=Math.max(0,Math.min(i.duration-1/60,n+r*T));Math.abs(i.currentTime-P)>1e-4&&await new Promise((o,l)=>{const e=window.setTimeout(()=>l(new Error("plate-seek")),8e3);i.onseeked=()=>{window.clearTimeout(e),o()},i.currentTime=P}),v.drawImage(i,0,0,A,m);const g=v.getImageData(0,0,A,m).data,u=new Uint8Array(A*m);for(let o=0;o<u.length;o++)u[o]=g[o*4]*77+g[o*4+1]*150+g[o*4+2]*29>>8;const F=gt(u,A,m,s);F&&p.push({tilt:F.tilt,roll:F.roll,lines:F.lines})}return Tt(p)}finally{i.removeAttribute("src"),i.load()}}function Tt(t){if(t.length<2)return null;const n=W(t.map(s=>s.tilt)),r=W(t.map(s=>s.roll));return t.filter(s=>Math.abs(s.tilt-n)<=5).length<Math.max(2,t.length*.6)?null:{tilt:k(n),roll:k(r),lines:Math.round(W(t.map(s=>s.lines)))}}export{yt as MATCH_HEIGHT,ot as MATCH_LENS,At as applyCameraMatch,xt as matchCamera,zt as matchPlateCamera,vt as matchable,Tt as tiltOfReads,Et as tiltOfStills,Ut as untouchedCamera};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/poseTracker-DZl8l2qS.js","assets/titleFrameBudget-X7HLSDre.js","assets/store-GFMJzaWS.js","assets/index-CKtv7gGE.js","assets/i18n-BJppIrtF.js","assets/personHq-B1c0QVJT.js","assets/matteQuality-9X-jgJrH.js","assets/api-BFN7blbw.js","assets/rigTrack-XaMj1yaH.js","assets/plateMatte-zTyuHHqh.js","assets/rotoMatte-i-cJTYmK.js","assets/plateCameraMatch-BM88dx-a.js","assets/remote-DJd9xWjn.js","assets/three.module-Bx43vjkH.js","assets/gltfLoader-U0Eebg7v.js","assets/rotoMaskStore-DdpmT9C3.js","assets/sceneTrack-Bbov7zET.js","assets/timelineOps-afzSo188.js","assets/cameraTracker-BAQHuTV-.js","assets/textAnimators-BVXTl8bU.js","assets/timelineComp-Dx_kED5V.js","assets/clientJobs-CuuUyhEy.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as U}from"./titleFrameBudget-X7HLSDre.js";import{fq as Z,ee as $,fr as tt,ef as nt,bn as G}from"./remote-DJd9xWjn.js";import{m as et}from"./rigTrack-XaMj1yaH.js";import{Quaternion as ot,Vector3 as v}from"./three.module-Bx43vjkH.js";import"./index-CKtv7gGE.js";import"./i18n-BJppIrtF.js";import"./api-BFN7blbw.js";import"./gltfLoader-U0Eebg7v.js";import"./store-GFMJzaWS.js";import"./rotoMaskStore-DdpmT9C3.js";import"./sceneTrack-Bbov7zET.js";import"./timelineOps-afzSo188.js";import"./cameraTracker-BAQHuTV-.js";import"./textAnimators-BVXTl8bU.js";import"./timelineComp-Dx_kED5V.js";import"./clientJobs-CuuUyhEy.js";const n={eyeL:2,eyeR:5,earL:7,earR:8,shL:11,shR:12,elL:13,elR:14,wrL:15,wrR:16,hipL:23,hipR:24,knL:25,knR:26,anL:27,anR:28},at=[[n.shL,n.hipL],[n.shR,n.hipR],[n.hipL,n.knL],[n.hipR,n.knR],[n.shL,n.shR]],rt=15,O=(e,r)=>e.map((t,i)=>(t+r[i])/2),C=e=>{const r=e.filter(Number.isFinite).sort((t,i)=>t-i);return r.length?r[r.length>>1]:NaN};function D(e,r,t){return new v(r*2-1,1-t*2,.5).unproject(e).sub(e.position).normalize()}const q=(e,r)=>new v(e[0],-e[1],-e[2]).applyQuaternion(r);function it(e,r){const t=O(e[n.hipL],e[n.hipR]),i=O(e[n.shL],e[n.shR]),c=.5/Math.max(.001,Math.hypot((i[0]-t[0])*r,i[1]-t[1]));return e.map(u=>[(u[0]-t[0])*r*c,(u[1]-t[1])*c,u[2]*r*c])}function st(e,r,t){return C(at.map(([i,c])=>{if(Math.min(r[i][3]??1,r[c][3]??1)<.5)return NaN;const u=Math.hypot(t[i][0]-t[c][0],t[i][1]-t[c][1]);if(u<.12)return NaN;const w=D(e,r[i][0],r[i][1]).angleTo(D(e,r[c][0],r[c][1]));return w>1e-4?u/Math.tan(w):NaN}))}const lt=e=>{const r=e.filter(Number.isFinite);return r.length?r.reduce((t,i)=>t+i,0)/r.length:NaN};function W(e){const r=e.map((i,c)=>C(e.slice(Math.max(0,c-2),c+3))),t=r.map((i,c)=>lt(r.slice(Math.max(0,c-1),c+2)));return t.map((i,c)=>{if(Number.isFinite(i))return i;for(let u=1;u<t.length;u++)for(const w of[c-u,c+u])if(Number.isFinite(t[w]))return t[w];return 4})}const ct=[[1,4],[2,5],[3,6],[7,8],[9,10],[11,12],[13,14],[15,16],[17,18],[19,20],[21,22],[23,24],[25,26],[27,28],[29,30],[31,32]],j=e=>{const r=[...e];for(const[t,i]of ct)r[t]=e[i],r[i]=e[t];return r},H=e=>(e%360+540)%360-180;function Q(e){const r=e[n.hipL][0]-e[n.hipR][0]+e[n.shL][0]-e[n.shR][0],t=e[n.hipL][2]-e[n.hipR][2]+e[n.shL][2]-e[n.shR][2];return{yaw:Math.atan2(t,r)*180/Math.PI,side:Math.abs(r)<.35*Math.hypot(r,t)}}function ht(e){const r=e.map(t=>{const{yaw:i,side:c}=Q(t.w),u=t.w[0][2]-(t.w[n.earL][2]+t.w[n.earR][2])/2,w=u<-.03?!0:u>.03?!1:null;return!c&&w!==null&&Math.abs(i)<90!==w?{lm:j(t.lm),w:j(t.w)}:t});for(let t=1;t<r.length;t++){const i=Q(r[t-1].w).yaw,c=Q(r[t].w).yaw;Math.abs(H(c-i))>110&&Math.abs(H(c+180-i))<Math.abs(H(c-i))&&(r[t]={lm:j(r[t].lm),w:j(r[t].w)})}return r}function mt(e,r=16/9){const t=[n.shL,n.shR,n.elL,n.elR,n.wrL,n.wrR,n.hipL,n.hipR,n.knL,n.knR,n.anL,n.anR],i=e.map((a,s)=>{if(!a.lm||a.lm.length<33)return null;const x=a.lm,y=O(x[n.hipL],x[n.hipR]),m=O(x[n.shL],x[n.shR]);return{i:s,t:a.t,x:y[0]*r,y:y[1],s:Math.max(.01,Math.hypot((m[0]-y[0])*r,m[1]-y[1])),vis:t.reduce((h,g)=>h+(x[g][3]??1),0)/t.length}}).filter(a=>!!a);if(i.length<4)return e;const c=i.map((a,s)=>s),u=a=>c[a]===a?a:c[a]=u(c[a]);for(let a=0;a<i.length;a++)for(let s=a+1;s<i.length;s++)Math.hypot(i[a].x-i[s].x,i[a].y-i[s].y)<=.7*Math.min(i[a].s,i[s].s)&&(c[u(a)]=u(s));const w=new Map;i.forEach((a,s)=>{const x=u(s);w.set(x,[...w.get(x)??[],a])});const M=[...w.values()].filter(a=>a.length>=3).map(a=>({g:a,t0:a[0].t,t1:a[a.length-1].t,score:a.length*C(a.map(s=>s.vis))**2}));if(!M.length||M.length===1&&M[0].g.length===i.length)return e;M.sort((a,s)=>s.score-a.score);const k=[M[0]],S=(a,s)=>Math.min(a.t1,s.t1)-Math.max(a.t0,s.t0)>.3*Math.max(.2,Math.min(a.t1-a.t0,s.t1-s.t0));for(let a=!0;a;){a=!1;for(const s of M){if(k.includes(s)||k.some(h=>S(h,s)))continue;const x=k.flatMap(h=>h.g);let y=1/0,m=!1;for(const h of[s.g[0],s.g[s.g.length-1]])for(const g of x){const R=Math.abs(g.t-h.t);R<y&&(y=R,m=Math.hypot(g.x-h.x,g.y-h.y)<=(.6+8*R)*Math.min(g.s,h.s))}m&&(k.push(s),a=!0)}}const E=new Set(k.flatMap(a=>a.g.map(s=>s.i)));return e.map((a,s)=>a.lm&&!E.has(s)?{...a,lm:null}:a)}const K=[27,28,29,30,31,32],pt={27:.09,28:.09,29:.035,30:.035,31:.03,32:.03},ft={27:"ankleR",28:"ankleL",29:"heelR",30:"heelL",31:"toeR",32:"toeL"},ut=e=>K.reduce((r,t)=>(e[t][3]??1)>=.3&&e[t][1]>e[r][1]?t:r,K[0]);function dt(e,r,t,i=16/9,c={}){const u=mt(e.filter(o=>o.lm&&o.lm.length>=33),i).filter(o=>o.lm),w=ht(u.map(o=>({lm:o.lm,w:o.wl&&o.wl.length>=33?o.wl:it(o.lm,i)}))),M=u.map((o,l)=>({...o,lm:w[l].lm})),k=w.map(o=>o.w),S=M.map(o=>r(o.t)),E=W(M.map((o,l)=>st(S[l],o.lm,k[l]))),a=(o,l,d)=>Math.hypot(o[l][0]-o[d][0],o[l][1]-o[d][1],o[l][2]-o[d][2]),s=C(k.map(o=>(a(o,n.hipL,n.knL)+a(o,n.knL,n.anL)+a(o,n.hipR,n.knR)+a(o,n.knR,n.anR))/2)),x=t/Math.max(.3,Number.isFinite(s)?s:.9),y=t/.93,m=M.map((o,l)=>{const d=k[l],f=S[l].getWorldQuaternion(new ot),b=O(d[n.hipL],d[n.hipR]),p=Y=>q(d[Y],f).multiplyScalar(x),N={hips:q(b,f).multiplyScalar(x),neck:q(O(d[n.shL],d[n.shR]),f).multiplyScalar(x),upL:p(n.shR),foreL:p(n.elR),handL:p(n.wrR),thighL:p(n.hipR),shinL:p(n.knR),footL:p(n.anR),upR:p(n.shL),foreR:p(n.elL),handR:p(n.wrL),thighR:p(n.hipL),shinR:p(n.knL),footR:p(n.anL)},{pose:F,yaw:A}=Z(N,{head:p(n.earL).add(p(n.earR)).multiplyScalar(.5),eyeA:p(n.eyeR),eyeB:p(n.eyeL)},{legTwist:!0}),z=et(F),_=O(z.hipL,z.hipR),T=Math.cos(A*Math.PI/180),I=Math.sin(A*Math.PI/180),V=new v((_[0]*T+_[2]*I)*y,_[1]*y,(-_[0]*I+_[2]*T)*y),X=D(S[l],...O(o.lm[n.hipL],o.lm[n.hipR]));return{pose:F,yaw:A,off:V,ray:X,cam:S[l],q:f,w:d,J:z}}),h=M.length,g=[...E],R=Array(h).fill(!1);if(c.floor&&h){const o=m.map((f,b)=>{const p=M[b].lm,N=ut(p),F=D(f.cam,p[N][0],p[N][1]);if(F.y>-.03)return NaN;const z=(Math.max(pt[N],f.J[ft[N]][1])*y-f.cam.position.y)/F.y;if(!(z>.3))return NaN;const _=O(f.w[n.hipL],f.w[n.hipR]),I=f.cam.position.clone().addScaledVector(F,z).add(q([_[0]-f.w[N][0],_[1]-f.w[N][1],_[2]-f.w[N][2]],f.q)).sub(f.cam.position).dot(f.ray);return I>.3?I:NaN}),l=o.map((f,b)=>f/E[b]),d=C(l.filter(f=>f>.6&&f<1.6));if(Number.isFinite(d)){const f=l.map(b=>Number.isFinite(b)&&Math.abs(b/d-1)<.12);if(f.filter(Boolean).length>=Math.max(3,h*.1)){const b=W(o.map((p,N)=>f[N]?p:NaN));for(let p=0;p<h;p++)R[p]=f[p],g[p]=f[p]?b[p]:E[p]*d}}}const B=(o,l)=>m[o].cam.position.clone().addScaledVector(m[o].ray,l).sub(m[o].off),L=m.map((o,l)=>B(l,g[l]));if(R.some(Boolean)){for(let o=0;o<h;o++)R[o]&&(L[o].y=0);for(let o=0;o<h;o++){if(R[o])continue;let l=o-1,d=o+1;for(;l>=0&&!R[l];)l--;for(;d<h&&!R[d];)d++;const f=l>=0?M[o].t-M[l].t:1/0,b=d<h?M[d].t-M[o].t:1/0;if(Math.min(f,b)>8)continue;const p=l>=0&&d<h?f/(f+b):l>=0?0:1,N=L[l>=0?l:d],F=L[d<h?d:l],A=N.x+(F.x-N.x)*p+m[o].off.x,z=N.z+(F.z-N.z)*p+m[o].off.z,{ray:_,cam:T}=m[o],I=_.x*_.x+_.z*_.z;if(I<.04)continue;const V=((A-T.position.x)*_.x+(z-T.position.z)*_.z)/I;V>.3&&(L[o]=B(o,V),g[o]=V,L[o].y<.02&&(L[o].y=0,R[o]=!0))}}const P=o=>Math.round(o*1e3)/1e3;return M.map((o,l)=>{const d=m[l].cam.position.clone().addScaledVector(m[l].ray,g[l]);return{time:o.t,pose:m[l].pose,position:[P(L[l].x),P(L[l].y),P(L[l].z)],yaw:m[l].yaw,hips:[P(d.x),P(d.y),P(d.z)],...c.floor&&R.some(Boolean)?R[l]?{grounded:!0}:{air:!0}:{}}})}let J=null;async function yt(e,r={}){const t=e.plate,i=e.shots.find(m=>m.id===e.activeShot);if(!t||!i)throw new Error("no-plate");const c=G.plateUrl?await G.plateUrl(t).catch(()=>t.url):t.url,u=r.fps??rt,w=Math.min(i.duration,t.duration),M=[t.gcsUri||t.url,t.inPoint,w,u].join("|");if(J?.key===M)return J;const[{trackPose:k},{matteAt:S,plateMatte:E}]=await Promise.all([U(()=>import("./poseTracker-DZl8l2qS.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])),U(()=>import("./plateMatte-zTyuHHqh.js"),__vite__mapDeps([9,1,10,7,4,3,2]))]),a=await E(e,c,{signal:r.signal,coarse:!0});let s;if(a){const m=g=>{const R=S(a,g).box;return R?{box:R}:null},h=Array.from({length:9},(g,R)=>S(a,t.inPoint+w*R/8).box?.h).filter(g=>g!=null).sort((g,R)=>g-R);s=Object.assign(m,{crop:h.length>3&&h[h.length>>1]<.4})}const x=m=>k({clip:{inPoint:t.inPoint,playbackRate:1},url:c,from:0,duration:w,fps:u,signal:r.signal,onProgress:r.progress,focus:m});let y=await x(s);if(s&&y.frames.filter(m=>m.lm).length<y.frames.length*.85){const m=await x();m.frames.filter(h=>h.lm).length>y.frames.filter(h=>h.lm).length&&(y=m,s=void 0)}return J={key:M,url:c,span:w,tracked:y,matte:a&&s?a.made?"made":"timeline":"none"},J}async function It(e,r,t){const i=e.plate,c=e.shots.find(L=>L.id===e.activeShot),u=e.items.find(L=>L.id===r);if(!i||!c)throw new Error("no-plate");if(!u||u.kind!=="person")throw new Error("no-person");const{url:w,span:M,tracked:k,matte:S}=await yt(e,t),E=k.frames.filter(L=>L.lm).length;if(E<2)throw new Error("no-person-in-plate");const[a,s]=(c.aspect||"16:9").split(":").map(Number),x=a/s||k.aspect;let y=e,m;const h=await U(()=>import("./plateCameraMatch-BM88dx-a.js"),__vite__mapDeps([11,1,12,3,4,7,13,14,2,15,16,17,18,19,20,8,21]));if(t.match!==!1&&h.matchable(e)&&(t.match===!0||t.lens!=null||!i.match&&h.untouchedCamera(e))){const L=typeof document>"u"?null:await h.tiltOfStills(w,i.inPoint,M,t.lens??i.match?.lens??h.MATCH_LENS,t.signal).catch(P=>{if(P.name==="AbortError")throw P;return null});m=h.matchCamera({frames:k.frames,aspect:x,lens:t.lens??null,seen:L},c.aspect),y=h.applyCameraMatch(e,m)}const g=y.shots.find(L=>L.id===y.activeShot),R=dt(k.frames,L=>tt(g,Math.min(1,L/g.duration)),.93*$(u)*(u.scale[1]||1),x,{floor:!!y.plate?.match}),B=nt(y,r,R,0,t.newId,{replace:"all"});return{stage:B.stage,keys:B.keys,found:E,frames:k.frames.length,hips:R.map(L=>({time:L.time/g.duration,at:L.hips})),matte:S,...m?{camera:m}:{}}}export{K as FEET,rt as FOLLOW_FPS,pt as FOOT_HEIGHT,n as LM,dt as bakeFollow,st as depthOf,ht as fixSides,It as followPlate,ut as lowestFoot,mt as mainBody,C as median,D as rayOf,yt as readPlate,W as smooth,it as worldOf};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/personHq-B1c0QVJT.js","assets/titleFrameBudget-X7HLSDre.js","assets/matteQuality-9X-jgJrH.js","assets/api-BFN7blbw.js","assets/i18n-BJppIrtF.js","assets/index-CKtv7gGE.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{da as c,a7 as m,_ as h}from"./titleFrameBudget-X7HLSDre.js";import"./rotoMatte-i-cJTYmK.js";import{u as w}from"./store-GFMJzaWS.js";import"./api-BFN7blbw.js";import"./i18n-BJppIrtF.js";import"./index-CKtv7gGE.js";function M(r){const l=r.plate,n=l?.timelineClipId;if(!l||!n)return null;const a=w.getState().clips,t=a.find(e=>e.id===n),o=e=>e?.person&&e.person.src!=="object"?e.person:null;return o(t)??o(a.find(e=>e.id!==n&&e.kind==="video"&&!!e.person&&(e.id===`${n}-person`||!!t&&e.url===t.url&&e.start===t.start)))}async function S(r,l,n={}){const a=M(r);try{if(a)return{p:a,frames:await m(a),made:!1};const t=r.plate,o=r.shots.find(u=>u.id===r.activeShot),{segmentPerson:e}=await h(async()=>{const{segmentPerson:u}=await import("./personHq-B1c0QVJT.js").then(d=>d.i);return{segmentPerson:u}},__vite__mapDeps([0,1,2,3,4,5])),f={id:"plate",nodeId:"",kind:"video",url:l,label:t.label,track:0,start:0,inPoint:t.inPoint,duration:Math.min(o.duration,t.duration),volume:0},p=await e({clip:f,url:l,signal:n.signal,...n.coarse?{fps:6}:{},quality:{store:!1,...n.coarse?{ai:!1}:{}}});return{p,frames:await m(p),made:!0}}catch(t){if(t.name==="AbortError")throw t;return null}}function k(r,l){const n=c(r.frames,r.p,l),{w:a,h:t}=r.p;let o=a,e=t,f=-1,p=-1,u=0;for(let i=0;i<t;i++)for(let s=0;s<a;s++)n[i*a+s]>127&&(u++,s<o&&(o=s),s>f&&(f=s),i<e&&(e=i),i>p&&(p=i));const d=f<0||u>a*t*.3?null:{x:o/a,y:e/t,w:(f-o+1)/a,h:(p-e+1)/t};return{a:n,w:a,h:t,box:d,at:(i,s)=>n[Math.min(t-1,Math.max(0,Math.floor(s*t)))*a+Math.min(a-1,Math.max(0,Math.floor(i*a)))]/255}}export{k as matteAt,S as plateMatte,M as plateMatteRef};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e='# Making plug-ins for Clipoox Timeline\n\nPlug-ins bring your own effects into Clipoox Timeline: a user adds your `.clipoox-plugin` file in the **Plug-in** tab, then one\nclick puts it in their video. This guide is written for non-programmers too.\n\n## 1. Seven kinds of plug-in\n\n| Kind | What you make | Who it is for |\n|---|---|---|\n| **Motion** | A JavaScript function that draws each frame (Canvas 2D or 3D) | Anyone who knows a little JavaScript |\n| **Lottie** | An After Effects animation exported with Bodymovin (`.json`) | Motion designers |\n| **Recipe** | A list of Clipoox\'s own editing steps (zoom, colour, text, SFX…) | Editors who want to package their way of editing |\n| **Sound pack** | Your own sound effects (WAV / MP3 / OGG / FLAC / M4A), no code — see §12 | Sound designers |\n| **Niche pack** | Many motion / Lottie / recipe items in one pack for one video niche (real estate, spa, cars…) — see §13 | Partners building big products |\n| **Clip analyzer** | Code that reads the customer\'s clip (small greyscale frames + speech) and keys zoom / position / effects itself — e.g. **auto zoom on what happens** in a screen recording — see §15 | Partners building smart tools |\n| **AI template** | A prompt + an output format; Clipoox\'s AI reads the clip\'s speech and writes a document (summary, quiz, slide outline…) — see §16 | Education and content partners |\n\n**Plug-ins cost no credits** — except **AI templates** (§16): Clipoox\'s AI writes the document, so they are charged on what the AI really uses, and the price is **always shown first** for the customer to accept.\n\nEvery plug-in can have **params** (text, colour, number, on/off, a choice, and images for Lottie) that users change in the Plug-in tab.\n\n## 2. Fastest start: edit a sample\n\n1. In Clipoox open the Timeline → **Plug-in** tab → **📘 Guide** → download the 3 samples (Motion, Lottie, Recipe).\n2. Rename the `.clipoox-plugin` file to `.zip` and unzip it (it is an ordinary zip file).\n3. Edit `manifest.json` (change `id`, `name`…) and the main file.\n4. Select **the files inside** (or the whole folder) → compress to `.zip` → rename to `.clipoox-plugin` (`.zip` also works).\n5. Clipoox → **Plug-in** tab → **+ Add plug-in** → pick the file. Clipoox checks and **test-runs** it, and tells you exactly what is wrong.\n\n## 3. Inside a package\n\n```\nmy-plugin.clipoox-plugin (a zip file)\n├── manifest.json required: information + params\n├── main.js main file (Motion) — or animation.json (Lottie) / recipe.json (Recipe)\n└── thumbnail.png optional (PNG / WebP / JPG, ≤ 256 KB). Without one, Clipoox captures a frame.\n```\n\nOnly these files are allowed (README.md / LICENSE are ignored). No sub-folders, no names containing `..`, `/` or `\\`.\n\n## 4. manifest.json\n\n```json\n{\n "format": 1,\n "id": "com.yourname.lower-third",\n "version": "1.0.0",\n "kind": "motion",\n "name": { "vi": "Lower third của tôi", "en": "My lower third" },\n "description": { "vi": "Thanh tên trượt vào", "en": "A name bar slides in" },\n "author": { "name": "Your name", "url": "https://your-site.com" },\n "entry": "main.js",\n "duration": 5,\n "params": [\n { "key": "name", "type": "text", "label": { "vi": "Tên", "en": "Name" }, "default": "Jane Doe", "maxLength": 40 },\n { "key": "accent", "type": "color", "label": { "vi": "Màu nhấn", "en": "Accent" }, "default": "#c6f432" }\n ]\n}\n```\n\n| Field | Meaning |\n|---|---|\n| `format` | Always `1` |\n| `id` | Your unique id, 3–40 lowercase letters, digits, dots / dashes: `com.yourname.plugin-name`. Same `id` = an update. |\n| `version` | Like `1.0.0`. Raise it every time you change the plug-in. |\n| `kind` | `motion`, `lottie` or `recipe` |\n| `name`, `description` | Vietnamese + English (`vi`, `en`; one is enough, it is used for both). Name ≤ 60 chars, description ≤ 300. |\n| `author` | `name` (required), `url` (optional, must be `https://`) |\n| `entry` | Main file name: `.js` for Motion, `.json` for Lottie / Recipe |\n| `engine` | Motion only: `2d` (default) or `3d` |\n| `duration` | Motion: layer length when added (0.5–20 s, required). Lottie: optional. |\n| `loop` | Lottie only: loop when the clip is longer than the animation (default `true`) |\n| `aspects` | Optional: frames it suits — `16:9`, `9:16`, `1:1`, `4:5`, `any` |\n| `tags` | Optional, recommended: up to 12 words (≤ 30 characters) saying **what video and which moment** it is for — so customers\' AI recommends it (see §11b). E.g. `["real-estate", "cta", "luxury"]` |\n| `thumbnail` | Optional image file name |\n| `minAppVersion` | Optional, default `1` |\n| `permissions` | Keep `[]`. This version grants plug-ins no permissions. |\n| `params` | Up to 24 params (below) |\n\n**Params** — each has a `key` (letters, digits, `_`; not starting with a digit), a `type`, a `label` (`vi` + `en`) and a `default`:\n\n| `type` | Extra | `default` example | For |\n|---|---|---|---|\n| `text` | `maxLength` (≤ 300), `multiline` | `"Hello"` | all kinds |\n| `number` | `min`, `max`, `step` | `1.2` | Motion, Recipe |\n| `color` | — | `"#ff5b3a"` | all kinds |\n| `boolean` | — | `true` | all kinds |\n| `select` | `options`: `[{ "value": "left", "label": { "vi": "Trái", "en": "Left" } }]` | `"left"` | Motion, Recipe |\n| `image` | no `default` | — | Lottie only |\n\nUnknown fields in the manifest are refused — spell field names exactly as above.\n\n## 5. Motion plug-ins\n\n`main.js` defines `function render(ctx, t, env)`. Clipoox calls it for **every frame**:\n\n- `ctx` — the Canvas 2D context to draw on (already cleared to transparent).\n- `t` — seconds from the start of the layer.\n- `env` — `{ width, height, duration, fps, progress, params, fonts }`. `params` holds the user\'s values; `fonts` holds font families\n that ship with Clipoox (full Vietnamese): `fonts.bevn` (Be Vietnam Pro 800/900), `fonts.mont` (Montserrat 900), `fonts.anton`,\n `fonts.oswald`, `fonts.play` (Playfair italic), `fonts.brico` (Bricolage Grotesque).\n- `M` — helpers: `M.range(t, a, b)` (0→1 between a and b), `M.ease.outExpo / outBack / inOutCubic / outBounce…`, `M.lerp`,\n `M.mix(colour1, colour2, k)`, `M.rgba(colour, alpha)`, `M.noise(x, y)`, `M.rand(seed)`, `M.spring(t)`, `M.TAU`, and the text helpers\n `M.fit`, `M.safe`, `M.icon`.\n\nA small example — a circle that pops into the middle:\n\n```js\nfunction render(ctx, t, env) {\n const { width: W, height: H, params: p } = env\n const k = M.ease.outBack(M.range(t, 0, 0.8))\n ctx.fillStyle = p.accent\n ctx.beginPath(); ctx.arc(W / 2, H / 2, H * 0.2 * k, 0, M.TAU); ctx.fill()\n ctx.fillStyle = \'#ffffff\'\n ctx.font = \'900 \' + Math.round(H * 0.08) + \'px \' + env.fonts.bevn\n ctx.textAlign = \'center\'; ctx.globalAlpha = M.range(t, 0.4, 1)\n ctx.fillText(p.name, W / 2, H / 2 + H * 0.03)\n}\n```\n\n**Rules so the exported video matches the Monitor exactly:**\n\n- Compute everything from `t` and `params`. **Do not keep state between frames** (e.g. adding up particle positions) — the Monitor\n draws frames in any order. For randomness use `M.rand(seed)` or `Math.random()` (Clipoox fixes it per frame).\n- Draw relative to `width` / `height` (no hard-coded pixels) so it works in 16:9, 9:16 and 1:1.\n- Each frame must finish in under 4 seconds (aim for under 50 ms). Endless loops are stopped.\n- For 3D set `"engine": "3d"` and write `setup(THREE, scene, camera, env)` (runs once) and `render(t, env)` (sets positions from `t`).\n\nTry code quickly: **Text** tab → Motion Code → **Empty code layer** → paste your code into the layer\'s Code box → **Apply code**.\nThat is the very sandbox plug-ins run in.\n\n## 6. Lottie plug-ins (After Effects → Bodymovin)\n\n### Export from After Effects\n\n1. Install **Bodymovin** (free): search "Bodymovin" in Creative Cloud, or get it from aescripts / GitHub airbnb/lottie-web and install it\n with a ZXP installer. The **LottieFiles for After Effects** plug-in also exports Bodymovin JSON.\n2. After Effects → **Edit → Preferences → Scripting & Expressions** → turn on *Allow Scripts to Write Files and Access Network*.\n3. Open **Window → Extensions → Bodymovin**. Tick the composition to export and choose where to save.\n4. Open the composition\'s **Settings**:\n - **Assets**: choose *Include in json* so images are embedded (Clipoox never loads images from links).\n - **Glyphs**: **tick** it (required for text users cannot change — Clipoox draws Lottie text from glyphs). For text bound to a\n `text` param, Clipoox rebuilds the glyphs with its own fonts (full Vietnamese): a font named "Anton" → Anton; Bold / Black /\n ExtraBold styles → Be Vietnam Pro ExtraBold; anything else → Be Vietnam Pro Regular.\n - **Expressions**: Clipoox **does not run expressions** (for safety). Before exporting, select properties with expressions →\n **Animation → Keyframe Assistant → Convert Expression to Keyframes**.\n5. Press **Render** → you get `data.json`. Rename it to `animation.json`.\n\nTips: keep it compact (e.g. 720×240 for a CTA button), 24–60 fps, under 5 MB. Most AE Effects (Glow, Blur…) do not export to Lottie —\nuse shape layers.\n\n### Binding params to the animation\n\nLottie params bind by **layer name** (the name in After Effects), so give layers clear names:\n\n```json\n"params": [\n { "key": "label", "type": "text", "label": { "vi": "Chữ trên nút", "en": "Button text" }, "default": "SUBSCRIBE", "bind": { "layer": "Label" } },\n { "key": "button", "type": "color", "label": { "vi": "Màu nút", "en": "Button colour" }, "default": "#ff2d2d", "bind": { "layer": "Button", "target": "fill" } },\n { "key": "cursor", "type": "boolean", "label": { "vi": "Hiện con trỏ", "en": "Show cursor" }, "default": true, "bind": { "layer": "Cursor" } },\n { "key": "avatar", "type": "image", "label": { "vi": "Ảnh kênh", "en": "Channel picture" }, "bind": { "asset": "logo" } }\n]\n```\n\n- `text` → the text layer with that name: replaces its text.\n- `color` → every fill (`fill`), stroke (`stroke`) or both (`both`) inside that layer. To recolour only part of a design, put that part\n on its own layer.\n- `boolean` → shows / hides the layer.\n- `image` → the embedded image with that `id` in the JSON\'s `assets` (often `image_0`; open the JSON and look for `"assets"`). Users pick\n a PNG / JPG / WebP ≤ 1 MB; use the same aspect ratio as the original image.\n\nEvery param must find its layer / image, otherwise Clipoox reports that it "could not be bound".\n\n## 7. Recipe plug-ins\n\n`recipe.json` is a list of editing steps — the same operations the Clipoox AI Editor uses:\n\n```json\n{\n "ops": [\n { "op": "setMotion", "clipId": "{{clip}}", "preset": "push-in" },\n { "op": "setEffect", "clipId": "{{clip}}", "property": "vivid", "numberValue": 0.3 },\n { "op": "punchIn", "clipId": "{{clip}}", "at": "{{clipMid}}", "numberValue": "{{punch}}" },\n { "op": "addMotion", "motionPreset": "lower-third", "start": "{{clipStart}}", "duration": 5, "text": "{{name}}", "color": "{{accent}}" },\n { "op": "addSfx", "sfxId": "whoosh-up", "at": "{{clipStart}}" }\n ]\n}\n```\n\n- `{{param_key}}` is replaced with the user\'s value. Built in: `{{clip}}` (the selected clip), `{{playhead}}`, `{{clipStart}}`,\n `{{clipMid}}`, `{{clipEnd}}` (seconds). When a value is exactly one `{{…}}`, numbers and true / false keep their type.\n- The user selects a clip → opens the recipe → edits its params → **Run**. All steps are **one undo** (⌘Z / Ctrl+Z).\n- Steps that cannot apply (e.g. captions before the speech is transcribed) are skipped and reported.\n\nAllowed operations: `move`, `trim`, `split`, `delete`, `rippleDelete`, `rippleTrim`, `compact`, `setVolume`, `duplicateClip`,\n`setClipProperty`, `setSpeed`, `speedRamp`, `setCrop`, `setKeyframes`, `setPropertyKeys`, `setAnimation`, `setEase`, `setEasing`,\n`setMotion`, `setLayerOrder`, `setEffect`, `cameraShake`, `addSolid`, `addAdjustmentLayer`, `duckAudio`, `addSfx`, `punchIn`, `stagger`,\n`loopKeys`, `addBounce`, `applyPalette`, `alignLayers`, `addSubtitles`, `addSocialCaptions`, `cutPauses`, `removeRetakes`, `addMotion`\n(library presets only), `addText`, `updateText`, `addShape`, `setShapeStyle`, `setReveal`, `addElement`, `setTransition`.\n\n**Glow Pro presets** (the Deep Glow-class glow): `setEffect` with `"property": "glow-pro"`, `numberValue` = intensity 0–1 and `glow` =\n`{radius 4–400, threshold 0–1, soft 0–1, spread 0–1, tint 0–1, core 0–1 (1 = the object keeps its colours, 0 = burnt-in), color "#RRGGBB"}` (all optional). Each preset is a one-op recipe,\ne.g. `{ "op": "setEffect", "clipId": "{{clip}}", "property": "glow-pro", "numberValue": 0.7, "glow": { "radius": 90, "tint": 0.6, "color": "#29e6ff" } }`.\n\n**Particle presets** (the Particular-class particle engine): `addMotion` with `"motionPreset": "particles"` (every setting at its default) or a `pt-*` preset, and `particles` = the settings to change: `emitter` (point/box/disc/line/ring/text), `ex`/`ey` 0–1, `esize`, `text`, `rate` 0–600 a second, `burst` 0–2000, `prerun` (seconds of pre-run), `life` (seconds), `speed`, `direction` (degrees, −90 = up), `spread`, `gravity`, `wind`, `drag` 0–6, `turbulence` 0–2, `shape` (dot/glow/streak/spark/smoke/square/star/heart/snow), `size`, `sizeEnd`, `color`/`colorEnd` (#RRGGBB), `opacity`, `blend` (add/normal), `seed`. A one-step recipe, e.g. `{ "op": "addMotion", "motionPreset": "particles", "start": 0, "duration": 5, "particles": { "emitter": "ring", "esize": 0.4, "rate": 160, "life": 2, "speed": 60, "spread": 360, "turbulence": 1, "shape": "star", "size": 10, "color": "#e9d4ff", "colorEnd": "#33e0ff" } }`. A bad setting is refused when the pack is checked.\n\nNot allowed: operations that **cost credits** (AI B-roll / elements, Claude Motion), export, changing the frame format, and the fields\n`code`, `html`, `prompt`, `url`. The fields of each operation are the same as in Clipoox\'s MCP guide (`get_timeline_guide`).\n\nNiche packs (§13) can also use: real-estate maps `addMap`, `updateMap`, `annotateMap`, `flyTo`, `reglueMap`, `setMapBounds`, estate text\n`estateText`, `lockup`, cards `addCard`, flashes `addFlash`, framing / camera `reframe`, `setCamera`, `setCameraKeys`, `cameraMove`,\njoins `makeSeamless`, `setJoin`, `joinCut`, `anchorMontage`, `muffleAudio`, `kineticEdit`, `parallax`, colour `colorGrade`, 3D / mattes\n`set3DLayer`, `setTrackMatte`, `separateText`, speakers `speakerBubble`, `speakerLayout`, 2D drawing `drawShape`, `addLibraryShape`,\n`applyStyle2d`, `animateShape`, `arrangeShape`, `physicsDrop` — and `usePlugin` to place **a motion / Lottie item of the same pack**:\n\n```json\n{ "op": "usePlugin", "pluginId": "@self/price-tag", "start": "{{clipMid}}", "params": { "price": "{{price}}", "accent": "{{accent}}" } }\n```\n\n## 8. Limits\n\n| | Limit |\n|---|---|\n| Whole package | ≤ 6 MB, ≤ 8 files |\n| `manifest.json` | ≤ 32 KB, up to 24 params |\n| Motion code | ≤ 40,000 characters, ≤ 4 s per frame, layer 0.5–20 s |\n| Lottie | ≤ 5 MB after cleaning, ≤ 600 s, embedded PNG / JPG / WebP / GIF images |\n| Recipe | ≤ 64 KB, ≤ 100 steps |\n| Thumbnail | ≤ 256 KB |\n| Per account | 50 plug-ins |\n| Niche pack (§13) | ≤ 60 MB, ≤ 200 items |\n\n## 9. Security — what a plug-in can NOT do\n\nClipoox runs other people\'s plug-ins, so they are locked down:\n\n- Motion code runs in its own **sandbox**: no network (`fetch`, XHR, WebSocket are all blocked), no access to the Clipoox page, cookies,\n tokens or `localStorage`, no windows, no `parent`. A frame over 4 seconds is stopped.\n- Lottie is data only: **expressions are removed**, images / fonts from links are dropped.\n- Recipes can only use the free operations above, and go through the AI Editor\'s own checks.\n- Plug-ins never touch the wallet / credits and never see anyone else\'s videos. A plug-in lives only in the account that added it.\n- Clipoox test-runs a plug-in when it is added: errors, very slow frames or two different pictures for the same moment are refused.\n\n## 10. Testing and fixing\n\n1. Add the plug-in in the **Plug-in** tab: the check list shows each step (package, sandbox run, speed, export = Monitor).\n2. After a fix: **raise** `version`, zip again, **Add plug-in** again → **Update**. Layers already in a video keep the old version;\n select one → **Update layer** to use the new one.\n3. Have the Clipoox source? `npm run plugin:pack -- ./my-plugin-folder` packs and checks it on your machine.\n\nCommon errors:\n\n| Message | Fix |\n|---|---|\n| The package has a file that is not allowed | Zip only `manifest.json`, the main file and the thumbnail. Remove other files / sub-folders. |\n| manifest.json has an unknown field | Check the field name spelling (table in section 4). |\n| A param could not be bound | The layer name in `bind` must match the layer name in After Effects. |\n| The motion code does not run | It needs `function render(ctx, t, env)`. Try the code in Motion Code first. |\n| Two renders give different pictures | Do not keep variables outside `render` between frames; compute everything from `t`. |\n| An operation costs credits | Remove AI generation steps from the recipe. |\n\n## 11. Publishing in the Plugin Store (review required)\n\nA plug-in is **official** only once the Clipoox team approves it:\n\n1. **Build and try it on your own account**: Plug-in tab → **+ Add plug-in**, or let Claude / ChatGPT (Clipoox MCP) call\n `install_plugin` — that install is a **test install, not reviewed**: only your account sees it, it is not in the store and cannot be sold.\n2. **Check the package** on platform.clipoox.com (the same checks Clipoox runs, nothing is submitted) until it passes.\n3. **Submit the plug-in** on platform.clipoox.com: the `.clipoox-plugin`, a picture, a description, the price you want, how you get paid.\n4. **An admin reviews it**: everything is checked again (code, animation, recipe, every item of a pack), the price and your revenue\n share are set, and it is published.\n5. Customers buy once on clipoox.com (bank transfer in VND or an international card in USD); author shares are paid monthly.\n\nThe first partners shipping niche packs get the **★ Pioneer partner** badge in the store and are listed first.\n\n### 11b. Recommended for the right videos: the `tags` field\n\nWhen a customer edits with their AI (Claude / ChatGPT over MCP, the `clipoox` CLI), the `recommend_blocks` tool reads their script\nand footage analysis and **picks matching plug-ins from the whole store** — including packs they have not installed (free ones\ninstall at once, paid ones come with a link to buy). Clipoox understands your plug-in from its `category`, `kind`, `aspects`, name\nand description; `tags` make it chosen for **the right kind of video and the right moment** more often.\n\nPut `tags` on the **pack manifest** (what videos the pack is for) and/or on **each item** (what that item does). Free words, in\nVietnamese or English: a word from the vocabulary below becomes a tag; any other word is a search word (`car`, `drift`, `spa`).\n\n| Group | Values |\n|---|---|\n| Video type | `talking-head`, `affiliate` (review / sales), `course`, `tvc` (ad), `real-estate`, `podcast`, `vlog` (travel, lifestyle, gaming), `explainer` (data, how it works) |\n| Role in the video | `hook`, `title`, `intro`, `lower-third`, `step`, `stat` (numbers, prices), `list`, `compare`, `proof` (reviews, awards), `quote`, `cta` (call to action, hotline), `outro`, `logo`, `transition`, `background`, `overlay`, `caption`, `look` (colour), `sfx` |\n| Style | `clean`, `minimal`, `bold`, `editorial`, `street`, `tech`, `luxury`, `playful`, `cinematic`, `corporate`, `retro`, `neon`, `soft` |\n| Energy | `calm`, `medium`, `high` |\n\n```json\n// the pack\'s manifest.json\n"category": "Real estate", "aspects": ["16:9", "9:16"], "tags": ["real-estate", "luxury"],\n// the manifest.json of the "hotline-cta" item\n"category": "promo", "tags": ["cta", "hotline", "calm"]\n```\n\nTips:\n- One clear role per item (`cta`, `stat`, `transition`…). A hotline button tagged both `stat` and `cta` gets suggested for a line about floor area.\n- `aspects` with one frame (e.g. `["9:16"]`) = composed for that frame, preferred for vertical videos; several frames = adaptive.\n- A recipe that edits a **whole video**: put its length in the name, e.g. `"Real-estate edit (30 s)"` — it is suggested as a whole-video recipe.\n- `tags` are not needed for a valid package, but well-tagged packs get recommended more once the store holds thousands of packs.\n\n## 12. Sound packs (Âm thanh)\n\nA **sound pack** is a plug-in of kind `sfx`: your own sound effects, no code. Once installed they appear in the Timeline\'s\n**Sound effects (SFX)** list under **Plug-in** — preview, "+" or drag onto an audio track, export — and the AI Editor and\nthe user\'s own AI (MCP) can pick them too. Start from the sample: Plug-in tab → download **Sounds ⤓** (8 sounds we\nsynthesised ourselves).\n\n```\nmy-sounds.clipoox-plugin (a zip file)\n├── manifest.json\n├── thumbnail.png optional (otherwise a waveform card is shown)\n└── sounds/\n ├── whoosh-soft.wav\n ├── pop.mp3\n └── room-tone.ogg\n```\n\n```json\n{\n "format": 1, "id": "vn.mystudio.cinema-hits", "version": "1.0.0", "kind": "sfx",\n "name": { "vi": "Cú đánh điện ảnh", "en": "Cinema hits" },\n "description": { "vi": "12 cú đánh trầm cho trailer", "en": "12 deep hits for trailers" },\n "author": { "name": "My Studio", "url": "https://mystudio.vn" },\n "sounds": [\n { "file": "sounds/hit-deep.wav", "name": { "vi": "Cú đánh trầm", "en": "Deep hit" }, "category": "impact", "tags": ["trailer", "boom"] },\n { "file": "sounds/room-tone.ogg", "name": { "vi": "Tiếng nền phòng", "en": "Room tone" }, "category": "ambience", "loop": true }\n ]\n}\n```\n\n- **Every file in `sounds/` must be listed** in `sounds[]` (one folder level, no sub-folders). `id` is optional (made from the\n file name); `category` is one of the Timeline SFX categories: `whoosh transition impact riser ui camera commerce foley cartoon\n glitch voice ambience nature human food vehicle scifi input motion pop alert fx music fun logo water machine care learn place`.\n `tags` (≤ 12, ≤ 30 characters) help search and the AI Editor ("door", "trailer", "keyboard"…). `loop: true` for beds.\n- **Formats:** WAV, MP3, OGG, FLAC, M4A (the extension must match the content). Deliver **48 kHz** (44.1 kHz is fine),\n 16- or 24-bit WAV or FLAC for the best result; mono or stereo. No video, no cover-art-only files.\n- **Length:** 0.05 – 30 s per sound; **up to 120 s** for loops (`loop: true`) and ambience / nature / water beds.\n- **Limits:** ≤ 200 sounds, ≤ 40 MB per file, pack ≤ **60 MB**.\n- **Edit tight:** cut silence at the start (the sound should hit on the frame it is placed), end with a short natural tail or\n fade; loops must be seamless (the last sample flows into the first).\n- **Loudness:** Clipoox levels every sound like its own SFX library (a mean level per category, around −15 to −22 dBFS,\n peaks limited to −1 dBFS) and stores it as stereo 48 kHz MP3 192 kb/s, so packs sit together in a mix. Do not limit or\n squash your files to make them "loud" — leave about −1 dBFS of headroom and let Clipoox level them.\n- **Names:** short, descriptive, in both languages ("Whoosh nhẹ" / "Soft whoosh"), file names without accents\n (`whoosh-soft.wav`).\n- **Licence:** you must **own or have the right to sell every sound** in the pack. Your own recordings, sounds you\n synthesised, or sounds whose licence lets you resell them as a pack. No sounds cut from films, games, songs or commercial\n libraries (BOOM, Artlist…). On platform.clipoox.com you confirm "I own or have the right to sell all the sounds in this pack".\n- **Store preview:** for a paid pack, buyers can listen to the **first 3 sounds** (≤ 5 s each, low quality) before they buy —\n put your best sounds first.\n- On install the server checks every file again (real decoding, not the file header): a non-audio file, a video, a silent or\n over-long sound refuses the pack with the sound\'s name.\n\nBuilding a pack without zip tools: on platform.clipoox.com → Submit a plug-in → **Sound pack** → drop your audio files,\nname / categorise them, and the page builds the package for you.\n\n## 13. Niche packs — one pack that covers a whole video niche\n\nA **niche pack** bundles many plug-ins (motion, Lottie, recipes) as one product: e.g. a real-estate pack with a project title, a price\ntag, amenities, a hotline and a "Listing tour" recipe that puts them all on a clip in one click. One installed pack = one of the 50 plug-ins.\n\n```\nbds-starter.clipoox-plugin (a zip file)\n├── manifest.json kind "pack", the item folders in "items"\n├── thumbnail.png (optional)\n├── project-title/ each folder is ONE complete plug-in\n│ ├── manifest.json "id" = the folder name, kind motion / lottie / recipe\n│ ├── main.js\n│ └── thumbnail.png (≤ 64 KB, optional)\n├── price-tag/ …\n└── listing-tour/\n ├── manifest.json\n └── recipe.json may use "usePlugin": "@self/<item>"\n```\n\n```json\n{ "format": 1, "id": "vn.yourcompany.estate", "version": "1.0.0", "kind": "pack",\n "name": { "vi": "Gói BĐS", "en": "Real-estate pack" }, "description": { "vi": "…", "en": "…" },\n "author": { "name": "Your name" }, "category": "Real estate", "permissions": [],\n "items": ["project-title", "price-tag", "listing-tour"] }\n```\n\n- A pack\'s manifest has **no** `entry` and no `params` — each item declares its own.\n- Folder names: lowercase letters, digits, hyphens, 3–40 characters; `pack id` + `/` + `item` ≤ 52 characters.\n- A recipe in a pack places a motion / Lottie item **of the same pack** with `usePlugin` + `@self/<item>` (no other plug-ins, no\n recipe inside a recipe).\n- On install Clipoox test-runs **every item** like a plug-in of its own; a failing item is named.\n- Customers: Plug-in tab → click the pack → the item grid → click an item to add it at the playhead (recipes run on the selected clip).\n- The customer\'s AI (Claude / ChatGPT through MCP, and Clipoox\'s AI Editor) **sees and places** installed items: `list_plugins`, then\n `edit_timeline` with `{"op":"usePlugin","pluginId":"<pack id>/<item>","params":{…}}` — customers make videos with your pack for free.\n\n| Niche pack | Limit |\n|---|---|\n| Whole package | ≤ 60 MB |\n| Items | ≤ 200 (each item within its kind\'s limits, §8) |\n| Item picture | ≤ 64 KB |\n| Per account | one pack = 1 of the 50 plug-ins |\n\n**Build a pack with Claude / ChatGPT**: download the **Plugin Dev Kit** (Plug-in tab → 📘 Guide → Dev Kit, or `/plugin-dev-kit.md`),\npaste it to your AI and describe the niche. It writes the folders, you zip them; with the Clipoox MCP connected it can\n`install_plugin` (test install), `usePlugin` on a timeline and `preview_timeline` to look — iterate, then submit for review (§11).\n\nHave fun! Send great plug-ins to the Clipoox team to be featured for the community.\n\n## 14. 3D kits — packs with assets (GLB, textures, sprites, LUTs)\n\nA **3D kit** is a niche pack (§13) with an `assets/` folder: GLB models, texture pictures, sprite sheets, image sequences and\n`.cube` LUTs. Item code reads them by name, for example `M3.asset(\'jet.glb\')`. **There is no network**: Clipoox hands the bytes\nto the sandbox before the first frame. The full sample is `hologram-studio.clipoox-plugin` (13 items, 9 assets); download it\nfrom the Plug-in tab.\n\n```\nmanifest.json kind "pack", "minAppVersion": 2, assets[], controls[], categories[]\nassets/jet.glb a model (a GLB with everything embedded, uncompressed)\nassets/holo-grid.png a texture\nassets/spark.png a sprite sheet (declare cols / rows)\nassets/pulse/0001.png an image sequence: a sub-folder of numbered frames\nassets/teal.cube a 3D LUT\nholo-globe/ a 3D motion item: manifest.json (+ "uses") + main.js (+ thumbnail)\njet-model/ a model item: manifest.json only (+ thumbnail)\nteal-orange/ a look item: manifest.json only (+ thumbnail)\n```\n\n**The pack\'s manifest.json** (added to §13):\n\n```json\n{\n "minAppVersion": 2,\n "assets": [\n { "name": "jet.glb" },\n { "name": "spark.png", "kind": "sprite", "sprite": { "cols": 4, "rows": 4, "frames": 16, "fps": 24 } },\n { "name": "pulse", "kind": "sequence", "fps": 24 },\n { "name": "teal.cube" }\n ],\n "controls": [\n { "key": "theme", "type": "color", "label": { "vi": "Màu chủ đạo", "en": "Theme colour" }, "default": "#3ee6ff" },\n { "key": "glow", "type": "number", "label": { "vi": "Độ phát sáng", "en": "Glow" }, "default": 1, "min": 0, "max": 2 }\n ],\n "categories": [ { "id": "hologram", "name": { "vi": "Hologram", "en": "Hologram" } } ]\n}\n```\n\n- `assets`: every file in `assets/` must be declared, and every declared name must have its file. A stray file refuses the\n whole pack.\n- `controls`: **kit-wide** controls; Clipoox draws their UI. An item param with `"link": "theme"` takes its value from that\n control. A customer changes the colour once and can apply it to every layer of the kit in their project.\n- `categories`: chips that group the items. An item\'s `category` must be one of these `id`s.\n\n**Three item kinds**:\n\n| Kind | manifest | When the customer clicks it |\n|---|---|---|\n| `motion` (engine `3d` or `2d`) + `"uses": ["jet.glb", …]` | as in §5 | a Motion layer; the assets in `uses` are copied into the customer\'s project |\n| `model` | `"model": {"asset": "jet.glb", "anim": "Fly", "move": "fly-in", "spin": {"y": 20}, "duration": 6}` | an ordinary Timeline 3D layer (camera, keys, MP4 export) |\n| `lut` | `"lut": "teal.cube"` | a colour look on the selected clip |\n\n`move` is one of `float`, `turntable`, `drop-bounce`, `flip`, `fly-in`, `hero-spin`, `tilt-to-camera`, `exit-spin`.\n`anim` must be the name of an animation in the GLB.\n\n**Reading assets in code** (every call is synchronous, because the assets are preloaded):\n\n```js\n// engine "3d"\nconst jet = M3.asset(\'jet.glb\') // a fresh copy of the GLB scene; jet.animations\nM3.play(jet, \'Fly\', t) // the pose is a pure function of t (scrubbing gives the same picture)\nconst grid = M3.texture(\'holo-grid.png\') // THREE.Texture\nconst sp = M3.sprite(\'spark.png\'); sp.frame(Math.floor(t * 12)) // sp.texture\nconst seq = M3.sequence(\'pulse\'); seq.at(t) // seq.texture\nconst look = M3.lut(\'teal.cube\') // {size, texture: Data3DTexture}\nconst mine = env.params.product ? M3.asset(\'@product\') : null // the customer\'s own GLB / picture (an "asset" param)\n\n// engine "2d"\nctx.drawImage(M.asset(\'logo.png\'), x, y, w, h)\nM.sprite(ctx, \'spark.png\', frame, x, y, w, h)\nconst img = M.sequence(\'pulse\', t) // the ImageBitmap of the frame at t\n```\n\n**The customer\'s own picture / GLB**: a param `{"key": "product", "type": "asset", "accept": "model" | "image"}` lets the\ncustomer pick a file from their Media. The code reads it with `M3.asset(\'@product\')` and should keep a fallback for when\nnothing has been picked yet.\n\n**Limits**:\n\n| | Max |\n|---|---|\n| Pack with assets | 200 MB (≤ 400 MB unzipped), 400 assets, 200 items |\n| GLB | 20 MB, **300,000 triangles** (meshes used several times count each time), 16 embedded pictures ≤ 4096², **no external links**, no Draco / meshopt / KTX2 compression |\n| Texture / sprite | PNG / WebP / JPEG, 8 MB, 4096 × 4096; sprites ≤ 256 frames |\n| Image sequence | 240 frames, each ≤ 1920 × 1080, 40 MB in all, every frame the same size |\n| LUT | 3D `.cube`, size ≤ 65, domain 0..1 |\n| One item (`uses`) | 60 MB of files, 256 MB of decoded pictures |\n\n**The file extension must match the bytes**: a `.png` must really be a PNG. The server re-checks everything when a customer\ninstalls and when Clipoox reviews; a failing asset is refused with its reason (for example "points to an outside file\ntextures/paint.png — embed everything in the GLB").\n\n**Only use content you may sell**: models you made, or ones whose licence allows resale inside a product. Never port a\ncommercial After Effects plug-in or someone else\'s copyrighted assets.\n\n## 15. Clip analyzers — example: auto zoom for screen recordings\n\nAn analyzer is your code that **reads one video clip** of the customer and returns edits for **that clip only**: zoom / position\nkeys, effects, crop, camera shake. The sample **Auto zoom (screen)** (`auto-zoom-screen`) finds where things happen (clicks, typing,\nmenus) and zooms into each, then back out — like professional screen-recording apps.\n\n**How customers use it**: select a clip on the timeline → click the plug-in. Clipoox reads the clip **on the customer\'s computer**\n(free), runs your code in the sandbox and applies the result (undo with ⌘Z). The customer\'s own AI (MCP / CLI) can run it too:\n`usePlugin {pluginId, clipId}`.\n\n```\nauto-zoom.clipoox-plugin\n├── manifest.json\n└── analyzer.js\n```\n\n`manifest.json` differs from Motion in three places:\n\n```json\n{\n "kind": "analyzer",\n "entry": "analyzer.js",\n "minAppVersion": 3,\n "permissions": ["footage"],\n "sample": { "fps": 4, "width": 160, "maxSeconds": 900 }\n}\n```\n\n- `permissions: ["footage"]` is **required** — customers see "reads small greyscale frames + the speech of the clip you pick, on this\n computer" before they install.\n- `sample`: how many frames per second you need (1–8), how wide in pixels (64–320, **greyscale**), the longest clip read (≤ 900 s).\n Fewer, smaller frames = faster. Screen recordings: 4 fps at 160 px wide is plenty.\n\n`analyzer.js` must define `analyze(input, env)`:\n\n```js\nfunction analyze(input, env) {\n // input.clip {duration, width, height} — the clip\'s seconds on the timeline, the source video size\n // input.frames {fps, width, height, count, at(i)} — at(i) = frame i (greyscale Uint8Array, 0..255)\n // input.words [{start, end, word}] — the speech (clip seconds), when the clip was transcribed\n // input.pauses [{start, end}] — silences\n // input.params the params the customer chose\n // env.diff(input.frames, i, j) → {amount 0..1, x, y}: how much changed between two frames and where (0..1 of the picture)\n // env.smooth(list, k), env.clamp(v, a, b), env.round(v)\n return {\n ops: [\n { op: \'setPropertyKeys\', property: \'zoom\', propertyKeys: [{ time: 2, value: 1 }, { time: 2.5, value: 1.6, ease: \'ease-in-out\' }] },\n ],\n summary: \'1 zoom\',\n }\n}\n```\n\n**Edits you may return** (applied to the clip being read — Clipoox fills `clipId` itself): `setPropertyKeys` (property `x`, `y`,\n`zoom`, `rot`, `opacity`…; `time` in clip seconds; up to 30 keys per property), `setEase`, `setEffect`, `setCrop`, `cameraShake`.\nAt most 100 edits. **Zoom into a point (fx, fy)** (0..1 of the picture) by `z`: `x = -(fx − 0.5) × z`, `y = -(fy − 0.5) × z`, and keep\n`|x|, |y| ≤ (z − 1) / 2` so no black edge shows.\n\n**An analyzer can NOT**: use the network, read the original video / other files / the Clipoox page, add or remove other clips, or use\npaid edits. It runs in the sandbox like Motion code; more than 60 s is stopped. On install Clipoox **test-runs it on a made-up 6 s\nscreen recording** — code that fails or returns invalid edits is refused.\n\n## 16. AI templates — example: a lesson kit from a recorded lecture\n\nAn AI template is **one prompt** of yours. The customer selects a clip with speech → **See price** → **Run** → Clipoox\'s AI reads the\nspeech and writes a document (Markdown or JSON): a summary, chapters, a quiz, a slide outline, a blog post… You need **no** API key or server.\n\n```\nlesson-kit.clipoox-plugin\n├── manifest.json kind "ai-template", entry "template.json", permissions ["transcript"], minAppVersion 3\n└── template.json\n```\n\n```json\n{\n "system": "You are an instructional designer… Never invent facts that are not in the transcript.",\n "prompt": "Lesson: {{title}} ({{duration}} s). Level: {{level}}.\\nTranscript:\\n{{transcript}}\\nWrite a summary, chapters and {{questions}} quiz questions.",\n "output": { "format": "markdown", "maxTokens": 2500 }\n}\n```\n\n- `{{transcript}}` is **required**. Also available: `{{title}}` (the clip name), `{{duration}}` (seconds), `{{language}}`, and every param in `params`.\n- `output.format`: `markdown` or `json` (JSON is extracted even when the AI wraps it in a ```json block). `maxTokens` 256–4000.\n- **Credits**: the customer sees the most it can cost first (from the speech length + `maxTokens`) and pays only what the AI really\n writes; if the AI fails, everything is refunded. No transcript yet: run **Transcript** on the clip first.\n- The result: shown in the Plug-in tab (Copy / Download .md / .json), saved on the account, and **sent to webhooks** (§17) — e.g. Make\n posts it to an LMS.\n- The customer\'s AI: `run_ai_template {plugin, project_id, clip_id, dry_run: true}` → the price → call again with `max_credits`.\n\n## 17. Webhooks — connect Make, Zapier, n8n\n\n**Plug-in tab → ⚡ Automation (Webhooks)** → paste the webhook link → **Add webhook** → **Send test**. Clipoox sends a JSON `POST` when:\n\n| Event | When | Main data |\n|---|---|---|\n| `export.done` | A video is exported | `export_id`, `project_id`, `download_url` (7 days, when exported through MCP / CLI), `seconds`, `width`, `height`, `from` |\n| `ai.document.ready` | An AI template finished | `doc_id`, `title`, `plugin`, `format`, `text`, `json?`, `credits` |\n| `plugin.analyzed` | An analyzer finished a clip | `project_id`, `clip_id`, `plugin`, `ops`, `summary` |\n\n```json\n{ "id": "whd_…", "event": "ai.document.ready", "created": 1793980000, "data": { "doc_id": "aid_…", "title": "Lesson 1", "format": "markdown", "text": "## Summary…" } }\n```\n\n**Check the signature** (the `whsec_…` secret is shown once when you add the webhook — keep it): header\n`X-Clipoox-Signature: t=<seconds>,v1=<hex>`, where `v1 = HMAC-SHA256(secret, t + "." + raw body)`. Ignore calls whose `t` is older\nthan 5 minutes. n8n / Node example:\n\n```js\nconst [t, v1] = header.match(/t=(\\d+),v1=([0-9a-f]+)/).slice(1)\nconst ok = crypto.createHmac(\'sha256\', secret).update(`${t}.${rawBody}`).digest(\'hex\') === v1 && Date.now() / 1000 - t < 300\n```\n\n**Make**: new scenario → **Webhooks › Custom webhook** → copy the link → paste it into Clipoox → **Send test** (Make learns the\nstructure) → add a **Router** on `event`: `export.done` → download `download_url` → upload to your LMS / Google Drive / YouTube;\n`ai.document.ready` → create the lesson / email students with `text`. **Zapier**: *Webhooks by Zapier › Catch Hook*. **n8n**: a *Webhook* node (POST).\n\nOnly public `https://` links (Clipoox blocks internal addresses). Up to 5 webhooks per account; the receiver must answer within 8 s\n(answer 2xx first, work after). Network errors / 5xx are retried once.\n\n## 18. Vibe-code: let an AI build the plug-in for you\n\nYou don\'t have to write the code yourself. Open Claude / ChatGPT / Cursor, **attach this guide** (the ⤓ button in the guide window) and\n**an unzipped sample** (`auto-zoom-screen`, `lesson-kit` or `lecture-studio` — download them in the Plug-in tab), then describe the idea. For example:\n\n> Read plugin-guide.en.md section 15 and the auto-zoom-screen sample. Write an analyzer plug-in `com.mycompany.focus-cursor`: software\n> tutorials, zoom 1.8× where the cursor area changes most, hold 2 s, ignore page switches (the whole screen changes). Add params\n> "Zoom" and "Hold (s)". Only setPropertyKeys x / y / zoom. Return manifest.json + analyzer.js.\n\n> Read section 16 and the lesson-kit sample. Write an AI template `com.mycompany.course-notes`: from the lecture, learning objectives,\n> 10 terms + definitions, 8 multiple-choice questions, JSON output {objectives, glossary, quiz}. Param: output language (vi / en).\n\n> Put both into a pack `com.mycompany.academy` (section 13) with a recipe "Polish a lecture" that runs @self/focus-cursor on the clip.\n\nThen zip the files into a `.clipoox-plugin` (or `npm run plugin:pack -- folder`) → **+ Add plug-in**. Clipoox test-runs it and reports\nexact errors — **paste the error back to the AI** to fix it. Repeat until it installs.\n\n**Test it with your own AI (MCP / CLI)**: connect Clipoox to Claude / ChatGPT (clipoox.com/mcp) or `npx clipoox login`, then:\n`install_plugin {url or upload_id}` (a test install, your account only) → `list_plugins` → `edit_timeline` with\n`{op: "usePlugin", pluginId: "…", clipId: "…"}` → `get_pending_jobs` (analyzers run while the Timeline is open) → `run_ai_template` →\n`webhooks {action: "add", url}` → `export_video`. Your AI edits the video and checks the result without clicking.\n\n## 19. Bringing a partner product to Clipoox (summary)\n\n1. **Idea → plug-ins**: "look at the video and decide" (zoom, highlights) → an **analyzer**; "write from the speech" (material,\n questions, summaries) → an **AI template**; "fixed editing steps" → a **recipe**; titles / cards / animations → **motion / Lottie**.\n2. **Bundle them in one pack** (§13) so customers install once.\n3. **Automate**: Make / Zapier / n8n receive `export.done` + `ai.document.ready` (§17).\n4. **Sell**: send the pack for Clipoox review and the Plug-in Store (§11).\n\nNever put code / assets you don\'t own the rights to in a pack. Work that must run on the customer\'s computer outside the browser\n(e.g. syncing a Zoom recordings folder automatically) belongs to the **Clipoox desktop app**, not a plug-in.\n\n';export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n='# Hướng dẫn làm plug-in cho Clipoox Timeline\n\nPlug-in giúp bạn mang hiệu ứng của mình vào Clipoox Timeline: người dùng thêm file `.clipoox-plugin` ở tab **Plug-in**,\nrồi bấm vào plug-in là nó xuất hiện trong video. Hướng dẫn này dành cho cả người không chuyên code.\n\n## 1. Có 7 loại plug-in\n\n| Loại | Bạn làm gì | Dành cho ai |\n|---|---|---|\n| **Motion** | Viết một hàm JavaScript vẽ từng khung hình (Canvas 2D hoặc 3D) | Người biết chút JavaScript |\n| **Lottie** | Xuất hoạt ảnh từ After Effects bằng Bodymovin (file `.json`) | Designer motion |\n| **Công thức** (recipe) | Liệt kê các bước chỉnh sửa có sẵn của Clipoox (zoom, màu, chữ, SFX…) | Editor muốn đóng gói "cách làm" của mình |\n| **Âm thanh** | Hiệu ứng âm thanh của bạn (WAV / MP3 / OGG / FLAC / M4A), không có code — xem §12 | Người làm âm thanh |\n| **Gói ngách** | Nhiều motion / Lottie / công thức trong một gói cho một ngách video (BĐS, spa, ô tô…) — xem §13 | Đối tác làm sản phẩm lớn |\n| **Phân tích clip** (analyzer) | Code đọc clip của khách (khung hình nhỏ đen trắng + lời thoại) rồi tự đặt zoom / key / hiệu ứng — ví dụ **tự zoom vào chỗ thao tác** khi quay màn hình — xem §15 | Đối tác làm công cụ thông minh |\n| **Mẫu AI** (ai-template) | Một prompt + định dạng kết quả; AI của Clipoox đọc lời thoại clip và viết tài liệu (tóm tắt, câu hỏi, dàn ý slide…) — xem §16 | Đối tác giáo dục, nội dung |\n\n**Plug-in không tốn credit** — trừ **Mẫu AI** (§16): AI của Clipoox viết tài liệu nên tính credit theo lượng thật sự dùng, và luôn **báo giá trước** để khách đồng ý.\n\nMọi plug-in có **tham số** (chữ, màu, số, bật/tắt, lựa chọn, ảnh với Lottie) mà người dùng sửa được trong tab Plug-in.\n\n## 2. Cách nhanh nhất: sửa từ mẫu\n\n1. Trong Clipoox, mở Timeline → tab **Plug-in** → **📘 Hướng dẫn plug-in** → tải 3 mẫu (Motion, Lottie, Công thức).\n2. Đổi đuôi file `.clipoox-plugin` thành `.zip` rồi giải nén (đây là file zip bình thường).\n3. Sửa `manifest.json` (đổi `id`, `name`…) và file chính.\n4. Chọn **các file bên trong** (hoặc cả thư mục) → nén thành `.zip` → đổi đuôi thành `.clipoox-plugin` (để `.zip` cũng được).\n5. Clipoox → tab **Plug-in** → **+ Thêm plug-in** → chọn file. Clipoox tự kiểm tra và **chạy thử**; có lỗi sẽ báo rõ lỗi gì.\n\n## 3. Bên trong một gói\n\n```\nmy-plugin.clipoox-plugin (file zip)\n├── manifest.json bắt buộc: thông tin + tham số\n├── main.js file chính (Motion) — hoặc animation.json (Lottie) / recipe.json (Công thức)\n└── thumbnail.png tuỳ chọn (PNG / WebP / JPG, ≤ 256 KB). Không có thì Clipoox tự chụp một khung.\n```\n\nChỉ được có các file trên (README.md / LICENSE được bỏ qua). Không để thư mục con, không dùng tên có `..`, `/`, `\\`.\n\n## 4. manifest.json\n\n```json\n{\n "format": 1,\n "id": "vn.tenban.lower-third",\n "version": "1.0.0",\n "kind": "motion",\n "name": { "vi": "Lower third của tôi", "en": "My lower third" },\n "description": { "vi": "Thanh tên trượt vào", "en": "A name bar slides in" },\n "author": { "name": "Tên bạn", "url": "https://trang-cua-ban.vn" },\n "entry": "main.js",\n "duration": 5,\n "params": [\n { "key": "name", "type": "text", "label": { "vi": "Tên", "en": "Name" }, "default": "Nguyễn An", "maxLength": 40 },\n { "key": "accent", "type": "color", "label": { "vi": "Màu nhấn", "en": "Accent" }, "default": "#c6f432" }\n ]\n}\n```\n\n| Trường | Ý nghĩa |\n|---|---|\n| `format` | Luôn là `1` |\n| `id` | Mã riêng, 3–40 ký tự thường, số, dấu chấm / gạch: `vn.tenban.ten-plugin`. Cùng `id` = bản cập nhật. |\n| `version` | Dạng `1.0.0`. Tăng lên mỗi lần sửa. |\n| `kind` | `motion`, `lottie` hoặc `recipe` |\n| `name`, `description` | Tiếng Việt + tiếng Anh (`vi`, `en`). Tên ≤ 60 ký tự, mô tả ≤ 300. |\n| `author` | `name` (bắt buộc), `url` (tuỳ chọn, phải là `https://`) |\n| `entry` | Tên file chính: `.js` cho Motion, `.json` cho Lottie / Công thức |\n| `engine` | Chỉ Motion: `2d` (mặc định) hoặc `3d` |\n| `duration` | Motion: độ dài lớp khi thêm (0.5–20 giây, bắt buộc). Lottie: tuỳ chọn. |\n| `loop` | Chỉ Lottie: chạy lặp khi clip dài hơn hoạt ảnh (mặc định `true`) |\n| `aspects` | Tuỳ chọn: khung hợp nhất — `16:9`, `9:16`, `1:1`, `4:5`, `any` |\n| `tags` | Tuỳ chọn, nên có: tối đa 12 từ (≤ 30 ký tự) nói plug-in dùng cho **video gì, chỗ nào** — để AI của khách gợi ý đúng (xem §11b). Ví dụ `["bất động sản", "cta", "sang trọng"]` |\n| `thumbnail` | Tuỳ chọn: tên file ảnh |\n| `minAppVersion` | Tuỳ chọn, mặc định `1` |\n| `permissions` | Để `[]`. Bản này không cấp quyền gì cho plug-in. |\n| `params` | Tối đa 24 tham số (xem dưới) |\n\n**Tham số** — mỗi tham số có `key` (chữ cái, số, `_`; không bắt đầu bằng số), `type`, `label` (`vi` + `en`), `default`:\n\n| `type` | Thêm | Ví dụ `default` | Dùng cho |\n|---|---|---|---|\n| `text` | `maxLength` (≤ 300), `multiline` | `"Xin chào"` | mọi loại |\n| `number` | `min`, `max`, `step` | `1.2` | Motion, Công thức |\n| `color` | — | `"#ff5b3a"` | mọi loại |\n| `boolean` | — | `true` | mọi loại |\n| `select` | `options`: `[{ "value": "left", "label": { "vi": "Trái", "en": "Left" } }]` | `"left"` | Motion, Công thức |\n| `image` | không có `default` | — | chỉ Lottie |\n\nTrường lạ trong manifest sẽ bị từ chối — viết đúng tên trường như bảng trên.\n\n## 5. Loại Motion\n\nFile `main.js` định nghĩa `function render(ctx, t, env)`. Clipoox gọi nó cho **mỗi khung hình**:\n\n- `ctx` — Canvas 2D để vẽ (đã xoá trong suốt sẵn).\n- `t` — giây tính từ đầu lớp.\n- `env` — `{ width, height, duration, fps, progress, params, fonts }`. `params` là giá trị người dùng đặt; `fonts` là tên phông có sẵn\n (đủ dấu tiếng Việt): `fonts.bevn` (Be Vietnam Pro 800/900), `fonts.mont` (Montserrat 900), `fonts.anton`, `fonts.oswald`,\n `fonts.play` (Playfair italic), `fonts.brico` (Bricolage Grotesque).\n- `M` — bộ trợ giúp: `M.range(t, a, b)` (0→1 trong khoảng a–b), `M.ease.outExpo / outBack / inOutCubic / outBounce…`,\n `M.lerp`, `M.mix(màu1, màu2, k)`, `M.rgba(màu, alpha)`, `M.noise(x, y)`, `M.rand(seed)`, `M.spring(t)`, `M.TAU`, và các hàm chữ\n `M.fit`, `M.safe`, `M.icon`.\n\nVí dụ nhỏ — một vòng tròn nảy vào giữa khung:\n\n```js\nfunction render(ctx, t, env) {\n const { width: W, height: H, params: p } = env\n const k = M.ease.outBack(M.range(t, 0, 0.8))\n ctx.fillStyle = p.accent\n ctx.beginPath(); ctx.arc(W / 2, H / 2, H * 0.2 * k, 0, M.TAU); ctx.fill()\n ctx.fillStyle = \'#ffffff\'\n ctx.font = \'900 \' + Math.round(H * 0.08) + \'px \' + env.fonts.bevn\n ctx.textAlign = \'center\'; ctx.globalAlpha = M.range(t, 0.4, 1)\n ctx.fillText(p.name, W / 2, H / 2 + H * 0.03)\n}\n```\n\n**Quy tắc để video xuất giống y Monitor:**\n\n- Mọi thứ phải tính từ `t` và `params`. **Không lưu biến giữa các khung** (ví dụ cộng dồn vị trí hạt) — Monitor vẽ khung theo thứ\n tự bất kỳ. Cần ngẫu nhiên thì dùng `M.rand(seed)` hoặc `Math.random()` (Clipoox cố định nó theo khung).\n- Vẽ theo `width` / `height` (đừng dùng số cứng) để chạy được cả 16:9, 9:16, 1:1.\n- Mỗi khung phải xong dưới 4 giây (nên dưới 50 ms). Vòng lặp vô hạn sẽ bị dừng.\n- Muốn 3D: đặt `"engine": "3d"` rồi viết `setup(THREE, scene, camera, env)` (chạy một lần) và `render(t, env)` (đặt vị trí theo `t`).\n\nThử nhanh code: tab **Text** → Motion Code → **Lớp code trống** → dán code vào ô Code của lớp → **Áp dụng code**. Đó chính là\nsandbox mà plug-in chạy trong.\n\n## 6. Loại Lottie (After Effects → Bodymovin)\n\n### Xuất từ After Effects\n\n1. Cài **Bodymovin** (miễn phí): trong Creative Cloud tìm "Bodymovin", hoặc tải từ aescripts / GitHub airbnb/lottie-web rồi cài\n bằng ZXP Installer. Hoặc dùng plug-in **LottieFiles for After Effects** (cũng xuất ra JSON Bodymovin).\n2. After Effects → **Edit → Preferences → Scripting & Expressions** → bật *Allow Scripts to Write Files and Access Network*.\n3. Mở **Window → Extensions → Bodymovin**. Tick composition cần xuất, chọn chỗ lưu.\n4. Bấm **Settings** của composition:\n - **Assets**: chọn *Include in json* để ảnh được nhúng vào file (Clipoox không tải ảnh từ link ngoài).\n - **Glyphs**: **tick** (bắt buộc với chữ không cho sửa — Clipoox vẽ chữ Lottie từ glyph). Chữ gắn tham số `text` thì\n Clipoox tự dựng lại glyph bằng phông của Clipoox (đủ dấu tiếng Việt): phông tên có "Anton" → Anton; kiểu Bold / Black /\n ExtraBold → Be Vietnam Pro ExtraBold; còn lại → Be Vietnam Pro Regular.\n - **Expressions**: Clipoox **không chạy expression** (vì an toàn). Trước khi xuất, chọn thuộc tính có expression →\n **Animation → Keyframe Assistant → Convert Expression to Keyframes**.\n5. Bấm **Render** → được file `data.json`. Đổi tên thành `animation.json`.\n\nMẹo: kích thước gọn (ví dụ 720×240 cho một nút CTA), 24–60 fps, dưới 5 MB. Hiệu ứng (Effects) của AE như Glow, Blur phần lớn\nkhông xuất được sang Lottie — dùng shape layer.\n\n### Gắn tham số vào hoạt ảnh\n\nTham số Lottie gắn theo **tên layer** (tên trong After Effects), nên hãy đặt tên layer rõ ràng:\n\n```json\n"params": [\n { "key": "label", "type": "text", "label": { "vi": "Chữ trên nút", "en": "Button text" }, "default": "ĐĂNG KÝ", "bind": { "layer": "Label" } },\n { "key": "button", "type": "color", "label": { "vi": "Màu nút", "en": "Button colour" }, "default": "#ff2d2d", "bind": { "layer": "Button", "target": "fill" } },\n { "key": "cursor", "type": "boolean", "label": { "vi": "Hiện con trỏ", "en": "Show cursor" }, "default": true, "bind": { "layer": "Cursor" } },\n { "key": "avatar", "type": "image", "label": { "vi": "Ảnh kênh", "en": "Channel picture" }, "bind": { "asset": "logo" } }\n]\n```\n\n- `text` → layer chữ (Text layer) tên đó: đổi nội dung chữ.\n- `color` → mọi màu tô (`fill`), viền (`stroke`) hoặc cả hai (`both`) trong layer đó. Muốn đổi riêng một phần thì tách thành layer riêng.\n- `boolean` → hiện / ẩn layer.\n- `image` → ảnh nhúng có `id` đó trong `assets` của file JSON (thường là `image_0`, mở file JSON tìm `"assets"`). Người dùng chọn\n ảnh PNG / JPG / WebP ≤ 1 MB; nên dùng ảnh cùng tỉ lệ với ảnh gốc.\n\nMỗi tham số phải tìm thấy layer / ảnh của nó, nếu không Clipoox báo "không gắn được".\n\n## 7. Loại Công thức (recipe)\n\n`recipe.json` là danh sách các bước chỉnh sửa — chính là các thao tác mà AI Editor của Clipoox dùng:\n\n```json\n{\n "ops": [\n { "op": "setMotion", "clipId": "{{clip}}", "preset": "push-in" },\n { "op": "setEffect", "clipId": "{{clip}}", "property": "vivid", "numberValue": 0.3 },\n { "op": "punchIn", "clipId": "{{clip}}", "at": "{{clipMid}}", "numberValue": "{{punch}}" },\n { "op": "addMotion", "motionPreset": "lower-third", "start": "{{clipStart}}", "duration": 5, "text": "{{name}}", "color": "{{accent}}" },\n { "op": "addSfx", "sfxId": "whoosh-up", "at": "{{clipStart}}" }\n ]\n}\n```\n\n- `{{tên_tham_số}}` được thay bằng giá trị người dùng nhập. Có sẵn: `{{clip}}` (clip đang chọn), `{{playhead}}`, `{{clipStart}}`,\n `{{clipMid}}`, `{{clipEnd}}` (giây). Nếu cả giá trị chỉ là một `{{…}}` thì giữ kiểu số / đúng sai.\n- Người dùng chọn clip → mở công thức → sửa tham số → **Chạy công thức**. Tất cả các bước là **một lần hoàn tác** (⌘Z / Ctrl+Z).\n- Bước nào không áp dụng được (ví dụ phụ đề khi chưa có lời thoại) sẽ được bỏ qua và báo lại.\n\nThao tác được dùng: `move`, `trim`, `split`, `delete`, `rippleDelete`, `rippleTrim`, `compact`, `setVolume`, `duplicateClip`,\n`setClipProperty`, `setSpeed`, `speedRamp`, `setCrop`, `setKeyframes`, `setPropertyKeys`, `setAnimation`, `setEase`, `setEasing`,\n`setMotion`, `setLayerOrder`, `setEffect`, `cameraShake`, `addSolid`, `addAdjustmentLayer`, `duckAudio`, `addSfx`, `punchIn`, `stagger`,\n`loopKeys`, `addBounce`, `applyPalette`, `alignLayers`, `addSubtitles`, `addSocialCaptions`, `cutPauses`, `removeRetakes`, `addMotion`\n(chỉ preset có sẵn), `addText`, `updateText`, `addShape`, `setShapeStyle`, `setReveal`, `addElement`, `setTransition`.\n\n**Preset Glow Pro** (glow kiểu Deep Glow): `setEffect` với `"property": "glow-pro"`, `numberValue` = cường độ 0–1 và `glow` =\n`{radius 4–400, threshold 0–1, soft 0–1, spread 0–1, tint 0–1, core 0–1 (1 = vật giữ màu, 0 = cộng sáng cháy), color "#RRGGBB"}` (đều không bắt buộc). Mỗi preset là một\ncông thức một thao tác, ví dụ `{ "op": "setEffect", "clipId": "{{clip}}", "property": "glow-pro", "numberValue": 0.7, "glow": { "radius": 90, "tint": 0.6, "color": "#29e6ff" } }`.\n\n**Preset Hạt** (bộ máy hạt kiểu Particular): `addMotion` với `"motionPreset": "particles"` (mọi thông số mặc định) hoặc một preset `pt-*`, và `particles` = các thông số muốn đổi: `emitter` (point/box/disc/line/ring/text), `ex`/`ey` 0–1, `esize`, `text`, `rate` 0–600 hạt/giây, `burst` 0–2000, `prerun` (giây chạy trước), `life` (giây), `speed`, `direction` (độ, −90 = lên), `spread`, `gravity`, `wind`, `drag` 0–6, `turbulence` 0–2, `shape` (dot/glow/streak/spark/smoke/square/star/heart/snow), `size`, `sizeEnd`, `color`/`colorEnd` (#RRGGBB), `opacity`, `blend` (add/normal), `seed`. Ví dụ công thức một thao tác: `{ "op": "addMotion", "motionPreset": "particles", "start": 0, "duration": 5, "particles": { "emitter": "ring", "esize": 0.4, "rate": 160, "life": 2, "speed": 60, "spread": 360, "turbulence": 1, "shape": "star", "size": 10, "color": "#e9d4ff", "colorEnd": "#33e0ff" } }`. Thông số sai bị từ chối khi kiểm gói.\n\nKhông được dùng: thao tác **tốn credit** (tạo B-roll / element bằng AI, Claude Motion), xuất video, đổi khung hình, các trường\n`code`, `html`, `prompt`, `url`. Trường của từng thao tác: xem tài liệu MCP của Clipoox (`get_timeline_guide`) — giống hệt.\n\nGói ngách (§13) còn dùng được thêm: bản đồ BĐS `addMap`, `updateMap`, `annotateMap`, `flyTo`, `reglueMap`, `setMapBounds`, chữ BĐS\n`estateText`, `lockup`, thẻ `addCard`, chớp `addFlash`, khung hình / camera `reframe`, `setCamera`, `setCameraKeys`, `cameraMove`,\nnối cảnh `makeSeamless`, `setJoin`, `joinCut`, `anchorMontage`, `muffleAudio`, `kineticEdit`, `parallax`, màu `colorGrade`, 3D / matte\n`set3DLayer`, `setTrackMatte`, `separateText`, người nói `speakerBubble`, `speakerLayout`, vẽ 2D `drawShape`, `addLibraryShape`,\n`applyStyle2d`, `animateShape`, `arrangeShape`, `physicsDrop` — và `usePlugin` để đặt **một mục motion / Lottie của chính gói**:\n\n```json\n{ "op": "usePlugin", "pluginId": "@self/price-tag", "start": "{{clipMid}}", "params": { "price": "{{price}}", "accent": "{{accent}}" } }\n```\n\n## 8. Giới hạn\n\n| | Giới hạn |\n|---|---|\n| Cả gói | ≤ 6 MB, ≤ 8 file |\n| `manifest.json` | ≤ 32 KB, tối đa 24 tham số |\n| Code Motion | ≤ 40 000 ký tự, mỗi khung ≤ 4 giây, lớp 0.5–20 giây |\n| Lottie | ≤ 5 MB sau khi làm sạch, ≤ 600 giây, ảnh nhúng PNG / JPG / WebP / GIF |\n| Công thức | ≤ 64 KB, ≤ 100 bước |\n| Thumbnail | ≤ 256 KB |\n| Mỗi tài khoản | 50 plug-in |\n| Gói ngách (§13) | ≤ 60 MB, ≤ 200 mục |\n\n## 9. Bảo mật — plug-in KHÔNG làm được gì\n\nClipoox chạy plug-in của người khác, nên khoá rất chặt:\n\n- Code Motion chạy trong **sandbox** riêng: không có mạng (`fetch`, XHR, WebSocket đều bị chặn), không đọc được trang Clipoox,\n cookie, token, `localStorage`, không mở cửa sổ, không gọi `parent`. Khung quá 4 giây bị dừng.\n- Lottie chỉ là dữ liệu: **expression bị xoá**, ảnh / phông tải từ link ngoài bị bỏ.\n- Công thức chỉ dùng được các thao tác miễn phí ở trên, và đi qua đúng bộ kiểm tra của AI Editor.\n- Plug-in không đụng tới ví / credit, không thấy video của người khác. Plug-in chỉ nằm trong tài khoản của người đã thêm.\n- Clipoox chạy thử plug-in lúc thêm: lỗi, quá chậm hoặc vẽ ra khác nhau giữa hai lần sẽ bị từ chối.\n\n## 10. Thử và sửa lỗi\n\n1. Thêm plug-in ở tab **Plug-in**: bảng kiểm tra hiện từng bước (đọc gói, chạy trong sandbox, tốc độ, xuất giống Monitor).\n2. Sửa xong: **tăng** `version`, nén lại, **Thêm plug-in** lần nữa → **Cập nhật plug-in**. Lớp đã có trong video vẫn giữ bản cũ;\n chọn lớp đó → **Cập nhật lớp** để dùng bản mới.\n3. Có bản mã nguồn Clipoox? Chạy `npm run plugin:pack -- ./thu-muc-plugin` để đóng gói và kiểm tra ngay trên máy.\n\nLỗi hay gặp:\n\n| Báo lỗi | Cách sửa |\n|---|---|\n| Gói có file không được phép | Chỉ nén `manifest.json`, file chính, thumbnail. Xoá file khác / thư mục con. |\n| manifest.json có trường lạ | Kiểm tra chính tả tên trường (bảng ở mục 4). |\n| Tham số không gắn được | Tên layer trong `bind` phải trùng tên layer trong After Effects. |\n| Code motion không chạy được | Phải có `function render(ctx, t, env)`. Thử code ở Motion Code trước. |\n| Hai lần vẽ cho kết quả khác nhau | Đừng giữ biến ngoài `render` giữa các khung; tính mọi thứ theo `t`. |\n| Thao tác tốn credit | Bỏ bước tạo bằng AI khỏi công thức. |\n\n## 11. Đưa plug-in lên Kho Plug-in (phải được duyệt)\n\nPlug-in chỉ **chính thức** khi đội Clipoox duyệt. Quy trình:\n\n1. **Làm và thử trên tài khoản của bạn**: tab Plug-in → **+ Thêm plug-in**, hoặc nhờ Claude / ChatGPT (MCP Clipoox) gọi\n `install_plugin` — bản cài này là **bản thử – chưa duyệt**: chỉ tài khoản bạn thấy, không lên Kho, không bán được.\n2. **Kiểm tra gói** trên platform.clipoox.com (chạy đúng bộ kiểm tra của Clipoox, không gửi đi) cho tới khi hết lỗi.\n3. **Gửi plug-in** trên platform.clipoox.com: file `.clipoox-plugin`, ảnh, mô tả, giá mong muốn, thông tin nhận tiền.\n4. **Admin duyệt**: kiểm tra lại toàn bộ (code, hoạt ảnh, công thức, từng mục của gói), đặt giá và tỉ lệ chia doanh thu, rồi xuất bản.\n5. Khách mua một lần trên clipoox.com (chuyển khoản VND hoặc thẻ quốc tế USD); phần của tác giả trả hằng tháng.\n\nĐối tác làm gói ngách đầu tiên có huy hiệu **★ Đối tác tiên phong** trong Kho và được xếp lên đầu.\n\n### 11b. Được AI gợi ý đúng video: trường `tags`\n\nKhi khách nhờ AI dựng video (Claude / ChatGPT qua MCP, CLI `clipoox`), công cụ `recommend_blocks` đọc kịch bản và phân tích\nfootage của khách, rồi **tự chọn plug-in phù hợp trong cả Kho**, kể cả gói khách chưa cài: gói miễn phí được cài ngay, gói trả\nphí thì gửi khách link mua. Clipoox tự hiểu plug-in của bạn từ `category`, `kind`, `aspects`, tên và mô tả. Thêm `tags` thì\nplug-in của bạn được chọn **đúng thể loại video và đúng chỗ** hơn.\n\nĐặt `tags` trên **manifest gói** (cả gói dùng cho video gì) và/hoặc **từng mục** (mục đó làm gì). Mỗi từ tự do, tiếng Việt hay\ntiếng Anh đều được. Từ nào trùng bộ từ vựng dưới đây thì thành thẻ; từ khác thành từ khoá tìm kiếm (`ô tô`, `drift`, `spa`).\n\n| Nhóm | Giá trị (viết được tiếng Việt / tiếng Anh) |\n|---|---|\n| Thể loại video | `talking-head` (người nói), `affiliate` (review / bán hàng), `course` (khoá học), `tvc` (quảng cáo), `real-estate` (bất động sản), `podcast`, `vlog` (du lịch, lifestyle, game), `explainer` (giải thích, số liệu) |\n| Vai trò trong video | `hook`, `title`, `intro`, `lower-third` (tên + chức danh), `step`, `stat` (con số, giá), `list`, `compare`, `proof` (đánh giá, chứng nhận), `quote`, `cta` (kêu gọi, hotline), `outro`, `logo`, `transition`, `background`, `overlay`, `caption`, `look` (màu), `sfx` |\n| Phong cách | `clean`, `minimal`, `bold`, `editorial`, `street`, `tech`, `luxury` (sang trọng), `playful`, `cinematic`, `corporate`, `retro`, `neon`, `soft` |\n| Năng lượng | `calm` (nhẹ nhàng), `medium`, `high` (sôi động) |\n\n```json\n// manifest.json của gói\n"category": "Bất động sản", "aspects": ["16:9", "9:16"], "tags": ["real-estate", "luxury"],\n// manifest.json của mục "hotline-cta"\n"category": "promo", "tags": ["cta", "hotline", "calm"]\n```\n\nMẹo:\n- Mỗi mục một vai trò rõ ràng (`cta`, `stat`, `transition`…). Một nút hotline mà gắn cả `stat` lẫn `cta` sẽ bị gợi ý nhầm cho câu nói về diện tích.\n- `aspects` chỉ một khung (ví dụ `["9:16"]`) = dựng riêng cho khung đó, được ưu tiên cho video dọc. Nhiều khung = co giãn.\n- Công thức dựng **cả video** thì ghi độ dài vào tên, ví dụ `"Dựng video BĐS (30 s)"`: nó được gợi ý như một công thức dựng trọn video.\n- Không cần `tags` để gói hợp lệ; nhưng gói có `tags` tốt thì được gợi ý nhiều hơn khi Kho có hàng nghìn gói.\n\n## 12. Gói âm thanh (Sound packs)\n\n**Gói âm thanh** là plug-in loại `sfx`: hiệu ứng âm thanh của chính bạn, không có code. Cài xong, âm thanh hiện trong mục\n**Hiệu ứng âm thanh (SFX)** của Timeline, nhóm **Plug-in** — nghe thử, bấm "+" hoặc kéo xuống track audio, xuất video — và\nAI Editor cùng AI riêng của khách (MCP) cũng chọn được. Bắt đầu từ mẫu: tab Plug-in → tải **Âm thanh ⤓** (8 âm thanh do\nClipoox tự tổng hợp).\n\n```\ngoi-am-thanh.clipoox-plugin (file zip)\n├── manifest.json\n├── thumbnail.png tuỳ chọn (không có thì hiện dạng sóng âm)\n└── sounds/\n ├── whoosh-soft.wav\n ├── pop.mp3\n └── room-tone.ogg\n```\n\n```json\n{\n "format": 1, "id": "vn.mystudio.cinema-hits", "version": "1.0.0", "kind": "sfx",\n "name": { "vi": "Cú đánh điện ảnh", "en": "Cinema hits" },\n "description": { "vi": "12 cú đánh trầm cho trailer", "en": "12 deep hits for trailers" },\n "author": { "name": "My Studio", "url": "https://mystudio.vn" },\n "sounds": [\n { "file": "sounds/hit-deep.wav", "name": { "vi": "Cú đánh trầm", "en": "Deep hit" }, "category": "impact", "tags": ["trailer", "boom"] },\n { "file": "sounds/room-tone.ogg", "name": { "vi": "Tiếng nền phòng", "en": "Room tone" }, "category": "ambience", "loop": true }\n ]\n}\n```\n\n- **Mọi file trong `sounds/` phải khai báo** trong `sounds[]` (một cấp thư mục, không thư mục con). `id` không bắt buộc (lấy từ\n tên file); `category` là một nhóm SFX của Timeline: `whoosh transition impact riser ui camera commerce foley cartoon glitch\n voice ambience nature human food vehicle scifi input motion pop alert fx music fun logo water machine care learn place`.\n `tags` (≤ 12 thẻ, ≤ 30 ký tự) giúp tìm kiếm và AI Editor ("cửa", "trailer", "bàn phím"…). `loop: true` cho âm nền lặp.\n- **Định dạng:** WAV, MP3, OGG, FLAC, M4A (đuôi file phải đúng nội dung). Nên xuất **48 kHz** (44,1 kHz cũng được), WAV hoặc\n FLAC 16/24-bit cho chất lượng tốt nhất; mono hoặc stereo. Không nhận video.\n- **Độ dài:** 0,05 – 30 giây mỗi âm; **tối đa 120 giây** cho âm lặp (`loop: true`) và âm nền (ambience / nature / water).\n- **Giới hạn:** ≤ 200 âm thanh, ≤ 40 MB mỗi file, cả gói ≤ **60 MB**.\n- **Cắt gọn:** bỏ khoảng lặng ở đầu (âm phải vang đúng khung hình được đặt), kết bằng đuôi tự nhiên ngắn hoặc fade; âm lặp\n phải nối liền (mẫu cuối chảy vào mẫu đầu).\n- **Âm lượng:** Clipoox cân bằng mọi âm như thư viện SFX của mình (mức trung bình theo nhóm, khoảng −15 đến −22 dBFS, đỉnh\n giới hạn −1 dBFS) và lưu dạng MP3 stereo 48 kHz 192 kb/s để các gói hoà âm đều nhau. Đừng nén / limit cho thật to — chừa\n khoảng −1 dBFS và để Clipoox cân bằng.\n- **Đặt tên:** ngắn, rõ, đủ hai thứ tiếng ("Whoosh nhẹ" / "Soft whoosh"); tên file không dấu (`whoosh-soft.wav`).\n- **Bản quyền:** bạn phải **sở hữu hoặc có quyền bán tất cả âm thanh** trong gói: tự thu, tự tổng hợp, hoặc âm có giấy phép\n cho phép bán lại dạng gói. Không cắt âm từ phim, game, bài hát hay thư viện thương mại (BOOM, Artlist…). Trên\n platform.clipoox.com bạn xác nhận "Tôi sở hữu hoặc có quyền bán tất cả âm thanh trong gói".\n- **Nghe thử trên Kho:** gói trả phí cho khách nghe **3 âm đầu tiên** (mỗi âm ≤ 5 giây, chất lượng thấp) trước khi mua — hãy\n xếp âm hay nhất lên đầu.\n- Khi cài, máy chủ kiểm tra lại từng file (giải mã thật, không tin phần đầu file): file không phải âm thanh, có video, im lặng\n hoặc dài quá sẽ làm gói bị từ chối, kèm tên âm bị lỗi.\n\nKhông có công cụ nén zip? Trên platform.clipoox.com → Gửi plug-in → **Gói âm thanh** → thả các file âm thanh vào, đặt tên /\nnhóm, trang sẽ tự đóng gói.\n\n## 13. Gói ngách (pack) — một gói "trùm" một ngách video\n\n**Gói ngách** gom nhiều plug-in (motion, Lottie, công thức) thành một sản phẩm: ví dụ gói Bất động sản có tên dự án, thẻ giá,\ntiện ích, hotline và công thức "Tour căn hộ" đặt tất cả lên clip trong một lần bấm. Khách cài một gói = một trong 50 plug-in.\n\n```\nbds-starter.clipoox-plugin (file zip)\n├── manifest.json kind "pack", danh sách thư mục ở "items"\n├── thumbnail.png (không bắt buộc)\n├── project-title/ mỗi thư mục là MỘT plug-in đầy đủ\n│ ├── manifest.json "id" = tên thư mục, kind motion / lottie / recipe\n│ ├── main.js\n│ └── thumbnail.png (≤ 64 KB, không bắt buộc)\n├── price-tag/ …\n└── listing-tour/\n ├── manifest.json\n └── recipe.json được dùng "usePlugin": "@self/<mục>"\n```\n\n```json\n{ "format": 1, "id": "vn.tencongty.bds", "version": "1.0.0", "kind": "pack",\n "name": { "vi": "Gói BĐS", "en": "Real-estate pack" }, "description": { "vi": "…", "en": "…" },\n "author": { "name": "Tên bạn" }, "category": "Bất động sản", "permissions": [],\n "items": ["project-title", "price-tag", "listing-tour"] }\n```\n\n- Manifest của gói **không có** `entry` hay `params` — mỗi mục tự khai tham số của nó.\n- Tên thư mục: chữ thường, số, gạch nối, 3–40 ký tự; `id gói` + `/` + `tên mục` ≤ 52 ký tự.\n- Công thức trong gói đặt mục motion / Lottie **của chính gói** bằng `usePlugin` + `@self/<mục>` (không gọi plug-in khác,\n không gọi công thức khác).\n- Lúc cài, Clipoox chạy thử **từng mục** như một plug-in riêng; mục nào lỗi thì báo đúng tên mục.\n- Khách dùng: tab Plug-in → bấm gói → lưới các mục → bấm mục để thêm vào playhead (công thức chạy trên clip đang chọn).\n- AI của khách (Claude / ChatGPT qua MCP, và AI Editor của Clipoox) **thấy và đặt được** các mục đã cài: `list_plugins` rồi\n `edit_timeline` với `{"op":"usePlugin","pluginId":"<id gói>/<mục>","params":{…}}` — khách làm video bằng gói của bạn, 0 đồng.\n\n| Gói ngách | Giới hạn |\n|---|---|\n| Cả gói | ≤ 60 MB |\n| Số mục | ≤ 200 (mỗi mục theo giới hạn của loại đó, §8) |\n| Ảnh mỗi mục | ≤ 64 KB |\n| Mỗi tài khoản | một gói = 1 trong 50 plug-in |\n\n**Làm gói cùng Claude / ChatGPT**: tải **Plugin Dev Kit** (tab Plug-in → 📘 Hướng dẫn → Dev Kit, hoặc\n`/plugin-dev-kit.md`), dán cho AI của bạn, mô tả ngách. AI viết các thư mục, bạn nén lại; nếu AI có MCP Clipoox thì nó tự\n`install_plugin` (bản thử), `usePlugin` lên một timeline và `preview_timeline` để xem — sửa tới khi đẹp rồi gửi duyệt (§11).\n\nChúc bạn làm plug-in vui! Gửi plug-in hay cho đội Clipoox để được giới thiệu tới cộng đồng.\n\n## 14. Bộ 3D — gói có tài nguyên (GLB, texture, sprite, LUT)\n\nMột **Bộ 3D** là gói ngách (§13) có thêm thư mục `assets/`: mô hình GLB, ảnh texture, sprite sheet, chuỗi ảnh, LUT `.cube`.\nCode của mục đọc tài nguyên bằng tên, ví dụ `M3.asset(\'jet.glb\')`. **Không có mạng**: Clipoox nạp sẵn bytes vào sandbox\ntrước khung hình đầu tiên. Mẫu đầy đủ: `hologram-studio.clipoox-plugin`, gồm 13 mục và 9 tài nguyên, tải ở tab Plug-in.\n\n```\nmanifest.json kind "pack", "minAppVersion": 2, assets[], controls[], categories[]\nassets/jet.glb mô hình (GLB nhúng mọi thứ, không nén)\nassets/holo-grid.png texture\nassets/spark.png sprite sheet (khai báo cols / rows)\nassets/pulse/0001.png chuỗi ảnh: một thư mục con, khung đánh số\nassets/teal.cube LUT 3D\nholo-globe/ mục motion 3D: manifest.json (+ "uses") + main.js (+ thumbnail)\njet-model/ mục model: chỉ có manifest.json (+ thumbnail)\nteal-orange/ mục look: chỉ có manifest.json (+ thumbnail)\n```\n\n**manifest.json của gói** (thêm vào §13):\n\n```json\n{\n "minAppVersion": 2,\n "assets": [\n { "name": "jet.glb" },\n { "name": "spark.png", "kind": "sprite", "sprite": { "cols": 4, "rows": 4, "frames": 16, "fps": 24 } },\n { "name": "pulse", "kind": "sequence", "fps": 24 },\n { "name": "teal.cube" }\n ],\n "controls": [\n { "key": "theme", "type": "color", "label": { "vi": "Màu chủ đạo", "en": "Theme colour" }, "default": "#3ee6ff" },\n { "key": "glow", "type": "number", "label": { "vi": "Độ phát sáng", "en": "Glow" }, "default": 1, "min": 0, "max": 2 }\n ],\n "categories": [ { "id": "hologram", "name": { "vi": "Hologram", "en": "Hologram" } } ]\n}\n```\n\n- `assets`: mỗi file trong `assets/` phải được khai báo, và mỗi tên đã khai báo phải có file. Có file lạ thì cả gói bị từ chối.\n- `controls`: các nút **chung cho cả bộ**, giao diện do Clipoox vẽ. Một tham số của mục ghi `"link": "theme"` để lấy giá trị\n từ nút chung. Khách đổi màu một lần là áp được cho mọi lớp của bộ trong dự án.\n- `categories`: dùng để nhóm mục thành chip. `category` của mục phải là một `id` có trong danh sách này.\n\n**Ba loại mục**:\n\n| Loại | manifest | Khi khách bấm |\n|---|---|---|\n| `motion` (engine `3d` hoặc `2d`) + `"uses": ["jet.glb", …]` | như §5 | lớp Motion; tài nguyên trong `uses` được chép vào dự án của khách |\n| `model` | `"model": {"asset": "jet.glb", "anim": "Fly", "move": "fly-in", "spin": {"y": 20}, "duration": 6}` | lớp 3D thường của Timeline (camera, keyframe, xuất MP4) |\n| `lut` | `"lut": "teal.cube"` | áp look màu lên clip đang chọn |\n\n`move` là một trong: `float`, `turntable`, `drop-bounce`, `flip`, `fly-in`, `hero-spin`, `tilt-to-camera`, `exit-spin`.\n`anim` phải là tên một animation có trong GLB.\n\n**Đọc tài nguyên trong code** (mọi hàm đều đồng bộ, vì tài nguyên đã nạp sẵn):\n\n```js\n// engine "3d"\nconst jet = M3.asset(\'jet.glb\') // một bản copy của scene GLB; jet.animations\nM3.play(jet, \'Fly\', t) // tư thế là hàm thuần của t (tua kiểu gì cũng ra cùng hình)\nconst grid = M3.texture(\'holo-grid.png\') // THREE.Texture\nconst sp = M3.sprite(\'spark.png\'); sp.frame(Math.floor(t * 12)) // sp.texture\nconst seq = M3.sequence(\'pulse\'); seq.at(t) // seq.texture\nconst look = M3.lut(\'teal.cube\') // {size, texture: Data3DTexture}\nconst mine = env.params.product ? M3.asset(\'@product\') : null // GLB / ảnh của chính khách (tham số "asset")\n\n// engine "2d"\nctx.drawImage(M.asset(\'logo.png\'), x, y, w, h)\nM.sprite(ctx, \'spark.png\', frame, x, y, w, h)\nconst img = M.sequence(\'pulse\', t) // ImageBitmap của khung lúc t\n```\n\n**Ảnh / GLB của khách**: một tham số `{"key": "product", "type": "asset", "accept": "model" | "image"}` cho khách chọn file\ntrong Media của họ. Code đọc file đó bằng `M3.asset(\'@product\')`, và nên có phương án dự phòng khi khách chưa chọn.\n\n**Giới hạn**:\n\n| | Tối đa |\n|---|---|\n| Gói có tài nguyên | 200 MB (giải nén ≤ 400 MB), 400 tài nguyên, 200 mục |\n| GLB | 20 MB, **300 000 tam giác** (tính cả mesh dùng lại nhiều lần), 16 ảnh nhúng ≤ 4096², **không link ngoài**, không nén Draco / meshopt / KTX2 |\n| Texture / sprite | PNG / WebP / JPEG, 8 MB, 4096 × 4096; sprite ≤ 256 khung |\n| Chuỗi ảnh | 240 khung, mỗi khung ≤ 1920 × 1080, tổng 40 MB, mọi khung cùng kích thước |\n| LUT | `.cube` 3D, kích thước ≤ 65, miền 0..1 |\n| Một mục (`uses`) | 60 MB file, 256 MB ảnh sau giải mã |\n\n**Đuôi file phải khớp nội dung**: file `.png` phải thật sự là PNG. Server kiểm lại toàn bộ khi khách cài và khi Clipoox\nduyệt; tài nguyên không đạt sẽ bị từ chối kèm lý do (ví dụ "trỏ ra file ngoài textures/paint.png — hãy nhúng mọi thứ vào GLB").\n\n**Chỉ dùng nội dung bạn có quyền bán**: mô hình bạn tự làm, hoặc có giấy phép cho phép bán lại trong một sản phẩm. Không port\nplug-in After Effects thương mại hay tài nguyên có bản quyền của người khác.\n\n## 15. Plug-in phân tích clip (analyzer) — ví dụ: tự zoom video quay màn hình\n\nAnalyzer là code của bạn **đọc một clip video** của khách rồi trả về các thao tác cho **chính clip đó**: key zoom / vị trí,\nhiệu ứng, crop, rung máy. Mẫu có sẵn: **Tự zoom màn hình** (`auto-zoom-screen`) — tìm chỗ có thao tác (bấm, gõ, mở menu) và\nzoom vào từng chỗ rồi ra, giống các app quay màn hình chuyên nghiệp.\n\n**Khách dùng thế nào**: chọn clip trên timeline → bấm plug-in. Clipoox đọc clip **ngay trên máy khách** (miễn phí), chạy code của\nbạn trong sandbox, rồi tự áp kết quả (hoàn tác bằng ⌘Z). AI của khách (MCP / CLI) cũng chạy được: `usePlugin {pluginId, clipId}`.\n\n```\nauto-zoom.clipoox-plugin\n├── manifest.json\n└── analyzer.js\n```\n\n`manifest.json` khác Motion ở 3 chỗ:\n\n```json\n{\n "kind": "analyzer",\n "entry": "analyzer.js",\n "minAppVersion": 3,\n "permissions": ["footage"],\n "sample": { "fps": 4, "width": 160, "maxSeconds": 900 }\n}\n```\n\n- `permissions: ["footage"]` **bắt buộc** — khách thấy dòng "đọc khung hình nhỏ + lời thoại của clip bạn chọn, ngay trên máy" trước khi cài.\n- `sample`: bạn cần bao nhiêu khung mỗi giây (1–8), rộng bao nhiêu pixel (64–320, ảnh **đen trắng**), clip dài nhất đọc (≤ 900 giây).\n Ít khung + ảnh nhỏ = chạy nhanh. Quay màn hình: 4 khung/giây, rộng 160 là đủ.\n\n`analyzer.js` phải có hàm `analyze(input, env)`:\n\n```js\nfunction analyze(input, env) {\n // input.clip {duration, width, height} — giây của clip trên timeline, cỡ video gốc\n // input.frames {fps, width, height, count, at(i)} — at(i) = khung thứ i (Uint8Array đen trắng, 0..255)\n // input.words [{start, end, word}] — lời thoại (giây trong clip), có khi clip đã Transcript\n // input.pauses [{start, end}] — khoảng lặng\n // input.params tham số khách chọn\n // env.diff(input.frames, i, j) → {amount 0..1, x, y}: thay đổi bao nhiêu giữa 2 khung và ở đâu (0..1 của hình)\n // env.smooth(list, k), env.clamp(v, a, b), env.round(v)\n return {\n ops: [\n { op: \'setPropertyKeys\', property: \'zoom\', propertyKeys: [{ time: 2, value: 1 }, { time: 2.5, value: 1.6, ease: \'ease-in-out\' }] },\n ],\n summary: \'1 zoom\',\n }\n}\n```\n\n**Thao tác được trả về** (chỉ áp cho clip đang đọc — `clipId` do Clipoox tự điền): `setPropertyKeys` (property `x`, `y`, `zoom`,\n`rot`, `opacity`…; `time` là giây trong clip; tối đa 30 key mỗi property), `setEase`, `setEffect`, `setCrop`, `cameraShake`.\nTối đa 100 thao tác. **Zoom vào điểm (fx, fy)** (0..1 của hình) với độ zoom `z`: `x = -(fx − 0.5) × z`, `y = -(fy − 0.5) × z`, và\ngiữ `|x|, |y| ≤ (z − 1) / 2` để không lộ viền đen.\n\n**Analyzer KHÔNG làm được**: gọi mạng, đọc video gốc / file khác / trang Clipoox, thêm hay xoá clip khác, dùng thao tác tốn credit.\nCode chạy trong sandbox như Motion; quá 60 giây bị dừng. Lúc cài, Clipoox **chạy thử trên một video màn hình giả 6 giây** — code\nlỗi hoặc trả về thao tác không hợp lệ sẽ bị từ chối.\n\n## 16. Mẫu AI (ai-template) — ví dụ: bộ bài học từ video giảng\n\nMẫu AI là **một prompt** của bạn. Khách chọn clip có lời thoại → bấm **Xem giá** → **Chạy** → AI của Clipoox đọc lời thoại và viết\ntài liệu (Markdown hoặc JSON): tóm tắt, chia chương, câu hỏi trắc nghiệm, dàn ý slide, bài blog… Bạn **không cần** API key hay server.\n\n```\nlesson-kit.clipoox-plugin\n├── manifest.json kind "ai-template", entry "template.json", permissions ["transcript"], minAppVersion 3\n└── template.json\n```\n\n```json\n{\n "system": "You are an instructional designer… Never invent facts that are not in the transcript.",\n "prompt": "Lesson: {{title}} ({{duration}} s). Level: {{level}}.\\nTranscript:\\n{{transcript}}\\nWrite a summary, chapters and {{questions}} quiz questions.",\n "output": { "format": "markdown", "maxTokens": 2500 }\n}\n```\n\n- `{{transcript}}` **bắt buộc**. Có sẵn: `{{title}}` (tên clip), `{{duration}}` (giây), `{{language}}`, và mọi tham số trong `params`.\n- `output.format`: `markdown` hoặc `json` (JSON được tách ra dù AI bọc trong khối ```json). `maxTokens` 256–4000.\n- **Tính credit**: khách thấy giá tối đa trước (theo độ dài lời thoại + `maxTokens`), chỉ trả theo lượng AI thật sự viết; AI lỗi thì hoàn\n toàn bộ. Khách chưa có lời thoại: bấm **Transcript** cho clip trước.\n- Kết quả: hiện trong tab Plug-in (Chép / Tải .md / .json), lưu trong tài khoản, và **gửi tới webhook** (§17) — ví dụ Make đưa lên LMS.\n- AI của khách: `run_ai_template {plugin, project_id, clip_id, dry_run: true}` → báo giá → gọi lại với `max_credits`.\n\n## 17. Webhook — nối Make, Zapier, n8n\n\nTab **Plug-in → ⚡ Tự động hoá (Webhook)** → dán link webhook → **Thêm webhook** → **Gửi thử**. Clipoox gửi `POST` JSON khi:\n\n| Sự kiện | Khi nào | Dữ liệu chính |\n|---|---|---|\n| `export.done` | Xuất video xong | `export_id`, `project_id`, `download_url` (7 ngày, khi xuất qua MCP / CLI), `seconds`, `width`, `height`, `from` |\n| `ai.document.ready` | Mẫu AI viết xong | `doc_id`, `title`, `plugin`, `format`, `text`, `json?`, `credits` |\n| `plugin.analyzed` | Analyzer chạy xong một clip | `project_id`, `clip_id`, `plugin`, `ops`, `summary` |\n\n```json\n{ "id": "whd_…", "event": "ai.document.ready", "created": 1793980000, "data": { "doc_id": "aid_…", "title": "Bài 1", "format": "markdown", "text": "## Tóm tắt…" } }\n```\n\n**Kiểm chữ ký** (khoá `whsec_…` chỉ hiện một lần khi thêm — lưu lại): header `X-Clipoox-Signature: t=<giây>,v1=<hex>`,\ntrong đó `v1 = HMAC-SHA256(khoá, t + "." + body gốc)`. Bỏ qua lời gọi có `t` cũ hơn 5 phút. Ví dụ n8n / Node:\n\n```js\nconst [t, v1] = header.match(/t=(\\d+),v1=([0-9a-f]+)/).slice(1)\nconst ok = crypto.createHmac(\'sha256\', secret).update(`${t}.${rawBody}`).digest(\'hex\') === v1 && Date.now() / 1000 - t < 300\n```\n\n**Make**: tạo scenario → module **Webhooks › Custom webhook** → chép link → dán vào Clipoox → **Gửi thử** (Make tự nhận cấu trúc)\n→ thêm **Router** theo `event`: `export.done` → tải `download_url` → upload lên LMS / Google Drive / YouTube; `ai.document.ready`\n→ tạo bài học / gửi email học viên bằng `text`. **Zapier**: *Webhooks by Zapier › Catch Hook*. **n8n**: node *Webhook* (POST).\n\nChỉ nhận link `https://` công khai (Clipoox chặn địa chỉ nội bộ). Mỗi tài khoản tối đa 5 webhook; nơi nhận phải trả lời trong 8 giây\n(trả 2xx trước, xử lý sau). Lỗi mạng / 5xx được gửi lại 1 lần.\n\n## 18. Vibe-code: nhờ AI làm plug-in cho bạn\n\nBạn không cần tự viết code. Mở Claude / ChatGPT / Cursor, **đính kèm hướng dẫn này** (nút ⤓ trong cửa sổ hướng dẫn) và **một gói\nmẫu đã giải nén** (`auto-zoom-screen`, `lesson-kit` hoặc `lecture-studio` — tải ở tab Plug-in), rồi nói rõ ý tưởng. Ví dụ:\n\n> Đọc plugin-guide.vi.md mục 15 và mẫu auto-zoom-screen. Viết plug-in analyzer `com.tencongty.focus-cursor`: video hướng dẫn phần\n> mềm, zoom 1.8× vào chỗ con trỏ thay đổi nhiều, giữ 2 giây, bỏ qua lúc chuyển trang (cả màn hình đổi). Thêm tham số "Độ zoom" và\n> "Giữ (giây)". Chỉ dùng thao tác setPropertyKeys x / y / zoom. Trả về manifest.json + analyzer.js.\n\n> Đọc mục 16 và mẫu lesson-kit. Viết mẫu AI `com.tencongty.course-notes`: từ lời giảng tạo mục tiêu bài học, 10 thuật ngữ + định nghĩa,\n> 8 câu trắc nghiệm, xuất JSON {objectives, glossary, quiz}. Tham số: ngôn ngữ đầu ra (vi / en).\n\n> Gộp 2 plug-in trên thành gói `com.tencongty.academy` (mục 13) với một công thức "Làm đẹp bài giảng" chạy @self/focus-cursor trên clip.\n\nRồi: nén các file thành `.clipoox-plugin` (hoặc `npm run plugin:pack -- thư-mục`) → **+ Thêm plug-in**. Clipoox chạy thử và báo\nlỗi cụ thể — **dán nguyên văn lỗi lại cho AI** để nó sửa. Lặp đến khi cài được.\n\n**Thử nhanh bằng AI của bạn (MCP / CLI)**: nối Clipoox vào Claude / ChatGPT (clipoox.com/mcp) hoặc `npx clipoox login`, rồi:\n`install_plugin {url hoặc upload_id}` (cài thử, chỉ tài khoản bạn) → `list_plugins` → `edit_timeline` với\n`{op: "usePlugin", pluginId: "…", clipId: "…"}` → `get_pending_jobs` (analyzer chạy khi Timeline đang mở) → `run_ai_template` →\n`webhooks {action: "add", url}` → `export_video`. AI của bạn tự sửa video và kiểm kết quả mà không cần bấm tay.\n\n## 19. Đưa sản phẩm của đối tác lên Clipoox (tóm tắt)\n\n1. **Ý tưởng → plug-in**: phần "nhìn video và quyết định" (zoom, điểm nổi bật) → **analyzer**; phần "viết từ lời giảng" (tài liệu,\n câu hỏi, tóm tắt) → **mẫu AI**; phần "các bước chỉnh sửa cố định" → **công thức**; tiêu đề / thẻ / hoạt ảnh → **motion / Lottie**.\n2. **Gộp thành một gói** (§13) để khách cài một lần.\n3. **Tự động hoá**: Make / Zapier / n8n nhận `export.done` + `ai.document.ready` (§17).\n4. **Bán**: gửi gói để Clipoox duyệt và đưa lên Kho Plug-in (§11).\n\nKhông đưa code / tài sản không thuộc quyền của bạn vào gói. Phần cần chạy trên máy khách ngoài trình duyệt (ví dụ tự đồng bộ thư mục\nZoom) là việc của **app Clipoox desktop**, không phải plug-in.\n\n';export{n as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{w as c}from"./api-BFN7blbw.js";import{g as i}from"./i18n-BJppIrtF.js";async function e(o,t={}){const a=await c(),r=await fetch(o,{...t,headers:{"Content-Type":"application/json","Accept-Language":i(),...a?{"X-Firebase-Token":a}:{},...t.headers||{}}}),s=await r.json().catch(()=>({}));if(!r.ok){const n=new Error(s.error||`${r.status}`);throw n.status=r.status,n.code=s.code,n.args=s.args,n.data=s,n}return s}const p=o=>e("/api/ai-templates/run",{method:"POST",body:JSON.stringify({...o,dry_run:!0,locale:i()})}),m=(o,t)=>e("/api/ai-templates/run",{method:"POST",body:JSON.stringify({...o,max_credits:t,locale:i()})}).then(a=>a.doc),b=()=>e("/api/webhooks"),k=(o,t)=>e("/api/webhooks",{method:"POST",body:JSON.stringify({url:o,events:t})}).then(a=>a.endpoint),l=o=>e(`/api/webhooks/${encodeURIComponent(o)}`,{method:"PATCH",body:JSON.stringify({rotate:!0})}).then(t=>t.endpoint),y=o=>e(`/api/webhooks/${encodeURIComponent(o)}`,{method:"DELETE"}),g=o=>e(`/api/webhooks/${encodeURIComponent(o)}/test`,{method:"POST"}),u=(o,t)=>e("/api/webhooks/emit",{method:"POST",body:JSON.stringify({event:o,data:t})}).catch(()=>({sent:0}));export{k as a,y as b,m as c,u as e,b as l,p,l as r,g as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as vt}from"./titleFrameBudget-X7HLSDre.js";import{u as _t}from"./store-GFMJzaWS.js";import{t as et}from"./i18n-BJppIrtF.js";import{S as Ft}from"./personHq-B1c0QVJT.js";import{E as Et,Y as Ot,_ as Tt,Q as Bt}from"./rigTrack-XaMj1yaH.js";import"./index-CKtv7gGE.js";import"./matteQuality-9X-jgJrH.js";import"./api-BFN7blbw.js";const Pt=Object.freeze({nose:0,earL:7,earR:8,shL:11,shR:12,elL:13,elR:14,wrL:15,wrR:16,hipL:23,hipR:24,knL:25,knR:26,anL:27,anR:28,toL:31,toR:32}),at=Object.freeze({frames:1800,people:2,seconds:60}),V=(l,s,h)=>l+(s-l)*h,st=l=>{const s=l.filter(Number.isFinite).sort((h,i)=>h-i);return s.length?s[Math.floor(s.length/2)]:NaN},dt=(l,s)=>Math.hypot(l[0]-s[0],l[1]-s[1]);function ut(l,s,{minCutoff:h=1.6,beta:i=.015,dCutoff:r=1}={}){const u=y=>{const O=1/(2*Math.PI*y),m=1/s;return 1/(1+O/m)},k=[];let w=l[0],f=0;for(let y=0;y<l.length;y++){if(y===0){k.push(w);continue}const O=(l[y]-w)*s,m=u(r);f=V(f,O,m);const R=u(h+i*Math.abs(f));w=V(w,l[y],R),k.push(w)}return k}function St(l){const s=l.slice(),h=s.length;let i=-1;for(let r=0;r<h;r++)if(s[r]){if(i<0)for(let u=0;u<r;u++)s[u]=s[r];else if(r-i>1)for(let u=i+1;u<r;u++){const k=(u-i)/(r-i);s[u]=[V(s[i][0],s[r][0],k),V(s[i][1],s[r][1],k),V(s[i][2]??0,s[r][2]??0,k)]}i=r}if(i>=0)for(let r=i+1;r<h;r++)s[r]=s[i];return s}function At(l,{rate:s=30,rect:h={x:0,y:0,w:1,h:1},W:i=1280,H:r=720,character:u="stickman",style:k={},place:w=null,minVisibility:f=.35}={}){if(!Array.isArray(l)||l.length<2)throw Error("Not enough of the person was seen in the video to follow (at least 2 frames)");const y=Math.min(l.length,at.frames),O=t=>[(h.x+t[0]*h.w)*i,(h.y+t[1]*h.h)*r,t[2]??0],m=Object.fromEntries(Object.entries(Pt).map(([t,n])=>[t,l.slice(0,y).map(c=>{const e=c?.lm?.[n];return e&&(e[3]??1)>=f&&Number.isFinite(e[0])&&Number.isFinite(e[1])?O(e):null})]));if(m.hipL.filter(Boolean).length+m.hipR.filter(Boolean).length<y*.3)throw Error("The person is hidden in most of the video — choose a clip where the whole body shows");const d={};for(const[t,n]of Object.entries(m)){const c=St(n);if(!c[0]){d[t]=null;continue}const e=ut(c.map(a=>a[0]),s),g=ut(c.map(a=>a[1]),s),o=c.map(a=>a[2]??0);d[t]=e.map((a,_)=>[a,g[_],o[_]])}for(const t of["shL","shR","hipL","hipR","anL","anR"])if(!d[t])throw Error("The whole body has to show in the video (shoulders, hips and feet)");const b=(t,n,c)=>[(d[t][c][0]+d[n][c][0])/2,(d[t][c][1]+d[n][c][1])/2];let B="L",j=0;const W=[];for(let t=0;t<y;t++){const n=d.shL[t][2]+d.hipL[t][2],c=d.shR[t][2]+d.hipR[t][2],e=n<=c?"L":"R";j=e===B?0:j+1,j>Math.round(s*.3)&&(B=e,j=0),W.push(B)}const x=(t,n)=>st(Array.from({length:y},(c,e)=>d[t]&&d[n]?dt(d[t][e],d[n][e]):NaN)),U=t=>b("hipL","hipR",t),D=t=>b("shL","shR",t),J=st(Array.from({length:y},(t,n)=>dt(U(n),D(n))))*1.12,I=(x("hipL","knL")+x("hipR","knR"))/2+(x("knL","anL")+x("knR","anR"))/2;if(!(J>4&&I>4))throw Error("The person is too small in the video to follow");const v=(J+I)/264,p={ua:(x("shL","elL")+x("shR","elR"))/2/v||56,fa:(x("elL","wrL")+x("elR","wrR"))/2/v||52,th:(x("hipL","knL")+x("hipR","knR"))/2/v,sh:(x("knL","anL")+x("knR","anR"))/2/v},P=Array.from({length:y},(t,n)=>Math.max(d.anL[n][1],d.anR[n][1])).sort((t,n)=>t-n),T=P[Math.floor(P.length*.8)],L=t=>[t[0]/v,(t[1]-T)/v],F=(t,n,c)=>{const e=[n[0]-t[0],n[1]-t[1]],g=Math.hypot(e[0],e[1])||1;return[t[0]+e[0]*c/g,t[1]+e[1]*c/g]},E=[];for(let t=0;t<y;t++){const n=W[t],c=n==="L"?"R":"L",e=$=>d[$]?L(d[$][t]):null,g=L(U(t)),o=L(D(t)),a=F(g,[o[0]+(o[0]-g[0])*.12,o[1]+(o[1]-g[1])*.12],108),_=d.earL&&d.earR?L(b("earL","earR",t)):e("nose")??[a[0],a[1]-21],z=F(a,_,21),G=e(`sh${n}`),K=e(`sh${c}`),A=e(`hip${n}`),Q=e(`hip${c}`),X=($,C,tt)=>[C[0]+($[0]-C[0])*tt,C[1]+($[1]-C[1])*tt],it=X(G,[a[0],a[1]+8],.22),ct=X(K,[a[0],a[1]+8],.22),lt=X(A,g,.35),ht=X(Q,g,.35),Y=($,C,tt,xt,Mt)=>{const ot=F($,C??$,xt),bt=F(ot,tt??ot,Mt);return[ot,bt]},[mt,ft]=Y(it,e(`el${n}`),e(`wr${n}`),p.ua,p.fa),[pt,wt]=Y(ct,e(`el${c}`),e(`wr${c}`),p.ua,p.fa),[yt,H]=Y(lt,e(`kn${n}`),e(`an${n}`),p.th,p.sh),[kt,Z]=Y(ht,e(`kn${c}`),e(`an${c}`),p.th,p.sh),Lt=e(`to${n}`)?F(H,e(`to${n}`),16):[H[0]+16,H[1]-2],gt=e(`to${c}`)?F(Z,e(`to${c}`),16):[Z[0]+16,Z[1]-2],Rt={pelvis:g,neck:a,head:z,shF:it,shB:ct,elF:mt,elB:pt,haF:ft,haB:wt,hiF:lt,hiB:ht,knF:yt,knB:kt,anF:H,anB:Z,toF:Lt,toB:gt,sides:{handL:n==="L"?"haF":"haB",handR:n==="L"?"haB":"haF",footL:n==="L"?"anF":"anB",footR:n==="L"?"anB":"anF"}};E.push({J:Rt,tt:(l[t]?.t??t/s)-(l[0]?.t??0),sh:[0,0]})}for(const t of E){const n={...t.J};let c=!1;for(const e of["anF","anB"])if(n[e][1]>0){const g=-n[e][1];n[e]=[n[e][0],0];const o=e==="anF"?"toF":"toB";n[o]=[n[o][0],n[o][1]+g],c=!0}c&&(t.J=Et(n,t.J))}Ot(E);const{ch:M,C:nt}=Tt(u,k);let S=[0,T],N=v;if(w){N=(w.size??.5)*r/300;const t=st(E.map(n=>n.J.pelvis[0]));S=[(w.x??.5)*i-t*N,(w.ground??.9)*r]}return{v:1,character:u,style:k,ch:M,C:nt,W:i,H:r,size:N*300/r,k:N,fs:1,base:S,fps:Math.round(s),trails:null,frames:E,skip:[],total:E.length/s}}const $t="https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task",jt=`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${Ft}/wasm`,It=512;let rt=null;async function Nt(){if(typeof window<"u"&&window.__poseTrackerStub)return{detect:window.__poseTrackerStub,close:()=>{}};const{FilesetResolver:l,PoseLandmarker:s}=await vt(async()=>{const{FilesetResolver:r,PoseLandmarker:u}=await import("./vision_bundle-9zIsgJJP.js");return{FilesetResolver:r,PoseLandmarker:u}},[]);rt??=l.forVisionTasks(jt).catch(r=>{throw rt=null,r});const h=await s.createFromOptions(await rt,{baseOptions:{modelAssetPath:$t,delegate:"CPU"},runningMode:"VIDEO",numPoses:at.people,minPoseDetectionConfidence:.5,minPosePresenceConfidence:.5,minTrackingConfidence:.5});let i=0;return{detect:(r,u)=>{i=Math.max(i+1,Math.round(u));const k=h.detectForVideo(r,i);return{landmarks:(k.landmarks??[]).map(w=>w.map(f=>[f.x,f.y,f.z,f.visibility??1])),world:(k.worldLandmarks??[]).map(w=>w.map(f=>[f.x,f.y,f.z]))}},close:()=>h.close()}}const q=448;async function zt({clip:l,url:s,from:h,duration:i,fps:r,person:u=1,signal:k,onProgress:w,focus:f}){const{detect:y,close:O}=await Nt(),m=Object.assign(document.createElement("video"),{muted:!0,playsInline:!0,preload:"auto",crossOrigin:"anonymous"});m.src=s;try{await new Promise((L,F)=>{m.onloadeddata=()=>L(),m.onerror=()=>F(Error(et("Không đọc được video để học chuyển động (CORS / định dạng)")))});const R=m.videoWidth||1280,d=m.videoHeight||720,b=Math.min(It,R),B=Math.max(2,Math.round(b*d/R)),j=Object.assign(document.createElement("canvas"),{width:b,height:B}),W=j.getContext("2d",{willReadFrequently:!0}),x=l.playbackRate||1,U=(l.inPoint||0)+h*x,D=Math.min(at.frames,Math.max(2,Math.round(i*r))),J=[],I=f?.crop&&!window.__poseTrackerStub?Object.assign(document.createElement("canvas"),{width:q,height:q}):null,v=I?.getContext("2d",{willReadFrequently:!0});let p=null,P=null;const T=L=>[(L[23][0]+L[24][0])/2,(L[23][1]+L[24][1])/2];for(let L=0;L<D;L++){if(k?.aborted)throw new DOMException("Đã huỷ","AbortError");const F=Math.max(0,Math.min(m.duration-1/60,U+L/r*x));Math.abs(m.currentTime-F)>1e-4&&await new Promise((o,a)=>{const _=window.setTimeout(()=>a(Error(et("Seek video quá lâu"))),8e3);m.onseeked=()=>{window.clearTimeout(_),o()},m.currentTime=F});const E=f?f(F):null;let M=null;if(E&&I){const o=E.box,a={cx:(o.x+o.w/2)*R,cy:(o.y+o.h/2)*d,s:Math.max(o.w*R,o.h*d,Math.min(R,d)*.25)*1.35};p=p?{cx:p.cx*.5+a.cx*.5,cy:p.cy*.5+a.cy*.5,s:Math.max(a.s,p.s*.85)}:a,M={sx:p.cx-p.s/2,sy:p.cy-p.s/2,s:p.s}}else p=null;const nt=M&&I&&v?I:j;M&&v?(v.fillStyle="#000",v.fillRect(0,0,q,q),v.drawImage(m,M.sx,M.sy,M.s,M.s,0,0,q,q)):W.drawImage(m,0,0,b,B);const S=y(nt,(L+1)*1e3/r),N=o=>M?o.map(a=>[(M.sx+a[0]*M.s)/R,(M.sy+a[1]*M.s)/d,a[2]*M.s/R,a[3]]):o,t=(Array.isArray(S)?S:S.landmarks).map(N),n=Array.isArray(S)?[]:S.world??[],c=t.filter(o=>Array.isArray(o)&&o.length>=33);let e=null;if(c.length&&E){const o=E.box,a=Math.max(o.w*.25,o.h*d/R*.5),_=o.x+o.w/2,z=o.y+o.h/2;let G=1/0;for(const K of c){const A=T(K);if(A[0]<o.x-a||A[0]>o.x+o.w+a||A[1]<o.y||A[1]>o.y+o.h)continue;const Q=Math.hypot(A[0]-_,A[1]-z);Q<G&&(G=Q,e=K)}e&&(P=T(e))}else if(c.length){if(P){let o=1/0;for(const a of c){const _=T(a),z=Math.hypot(_[0]-P[0],_[1]-P[1]);z<o&&(o=z,e=a)}o>.25&&(e=null)}else{const o=[...c].sort((a,_)=>T(a)[0]-T(_)[0]);e=o[Math.min(o.length-1,u-1)]}e&&(P=T(e))}const g=e?n[t.indexOf(e)]:null;J.push({t:L/r,lm:e,...g&&g.length>=33?{wl:g}:{}}),w?.(L+1,D)}return{frames:J,aspect:R/d}}finally{m.removeAttribute("src"),m.load(),O()}}function Ct(l,s,h="contain"){if(h==="cover"?l<s:l>s){const u=s/l;return{x:0,y:(1-u)/2,w:1,h:u}}const r=l/s;return{x:(1-r)/2,y:0,w:r,h:1}}async function Qt(l,s){const h=s.params??{},i=_t.getState().clips.find(b=>b.id===h.source);if(!i||i.kind!=="video")throw Error(et("Không tìm thấy clip video để học chuyển động"));const r=document.querySelector(`video[data-clip-media="${i.id}"]`)?.currentSrc||i.url,u=h.fps??30,k=h.W??1280,w=h.H??720,{frames:f,aspect:y}=await zt({clip:i,url:r,from:h.from??0,duration:h.duration??i.duration,fps:u,person:h.person??1}),O=At(f,{rate:u,rect:Ct(y,k/w,i.fit??"contain"),W:k,H:w,character:h.character??"stickman",style:h.style??{},place:h.place??null}),m=Bt(O),R=l.shape;if(!R?.items?.[0])throw Error(et("Lớp người que không còn"));const d=R.items.map((b,B)=>B?b:{...b,params:{...b.params,rig:m},opacity:1,span:[0,Math.round(m.n/m.fps*1e4)/1e4]});return{shape:{...R,items:d}}}export{$t as POSE_MODEL_URL,Ct as pictureRect,Qt as runPoseTrack,zt as trackPose};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/remote-DJd9xWjn.js","assets/index-CKtv7gGE.js","assets/i18n-BJppIrtF.js","assets/api-BFN7blbw.js","assets/titleFrameBudget-X7HLSDre.js","assets/three.module-Bx43vjkH.js","assets/gltfLoader-U0Eebg7v.js","assets/store-GFMJzaWS.js","assets/rotoMaskStore-DdpmT9C3.js","assets/sceneTrack-Bbov7zET.js","assets/timelineOps-afzSo188.js","assets/cameraTracker-BAQHuTV-.js","assets/textAnimators-BVXTl8bU.js","assets/timelineComp-Dx_kED5V.js","assets/rigTrack-XaMj1yaH.js","assets/clientJobs-CuuUyhEy.js","assets/exportGlb-BOdI9cVS.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as P}from"./titleFrameBudget-X7HLSDre.js";import{aK as C,aJ as X}from"./remote-DJd9xWjn.js";import"./index-CKtv7gGE.js";import"./i18n-BJppIrtF.js";import"./api-BFN7blbw.js";import"./three.module-Bx43vjkH.js";import"./gltfLoader-U0Eebg7v.js";import"./store-GFMJzaWS.js";import"./rotoMaskStore-DdpmT9C3.js";import"./sceneTrack-Bbov7zET.js";import"./timelineOps-afzSo188.js";import"./cameraTracker-BAQHuTV-.js";import"./textAnimators-BVXTl8bU.js";import"./timelineComp-Dx_kED5V.js";import"./rigTrack-XaMj1yaH.js";import"./clientJobs-CuuUyhEy.js";const V=(a,h,c)=>a<h?h:a>c?c:a,B=a=>{if(!a.length)return 0;const h=[...a].sort((c,b)=>c-b);return h[Math.floor(h.length/2)]};function J(a,{tolerance:h}={}){const{width:c,height:b,data:m}=a,n=c*b,u=new Uint8Array(n);let y=0;for(let t=0;t<n;t++)m[t*4+3]<250&&y++;if(y>n*.02){for(let t=0;t<n;t++)u[t]=m[t*4+3]>=128?1:0;return{mask:u,background:null}}const p=[[],[],[]],e=(t,g)=>{const k=(g*c+t)*4;p[0].push(m[k]),p[1].push(m[k+1]),p[2].push(m[k+2])};for(let t=0;t<c;t++)e(t,0),e(t,b-1);for(let t=0;t<b;t++)e(0,t),e(c-1,t);const l=p.map(B),x=Math.sqrt(p[0].reduce((t,g,k)=>t+(g-l[0])**2+(p[1][k]-l[1])**2+(p[2][k]-l[2])**2,0)/p[0].length),w=h??Math.min(40,Math.max(10,3*x+8)),s=w*w,_=t=>{const g=t*4,k=m[g]-l[0],I=m[g+1]-l[1],E=m[g+2]-l[2];return k*k+I*I+E*E<=s},U=(w*.6)**2,A=(t,g)=>{const k=t*4,I=g*4,E=m[k]-m[I],v=m[k+1]-m[I+1],R=m[k+2]-m[I+2];return E*E+v*v+R*R<=U},N=new Uint8Array(n),F=[],o=(t,g)=>{!N[t]&&_(t)&&(g<0||A(t,g))&&(N[t]=1,F.push(t))};for(let t=0;t<c;t++)o(t,-1),o((b-1)*c+t,-1);for(let t=0;t<b;t++)o(t*c,-1),o(t*c+c-1,-1);for(;F.length;){const t=F.pop(),g=t%c,k=t/c|0;g>0&&o(t-1,t),g<c-1&&o(t+1,t),k>0&&o(t-c,t),k<b-1&&o(t+c,t)}for(let t=0;t<n;t++)u[t]=N[t]?0:1;return{mask:u,background:l}}function K(a,h,c){const b=new Int32Array(c).fill(-1),m=new Int32Array(c).fill(-1);for(let n=0;n<c;n++){let u=0,y=-1,p=-1,e=0,l=0;for(let x=0;x<=h;x++)x<h&&a[n*h+x]?(e||(l=x),e++):e&&(e>u&&(u=e,y=l,p=x-1),e=0);b[n]=y,m[n]=p}return{L:b,R:m}}function j(a,{height_m:h=.15,rows:c=160,tolerance:b}={}){const{width:m,height:n,data:u}=a,{mask:y,background:p}=J(a,{tolerance:b}),{L:e,R:l}=K(y,m,n);let x=0;for(let r=0;r<n;r++)e[r]>=0&&(x=Math.max(x,l[r]-e[r]+1));if(x<4)return null;const w=r=>e[r]>=0&&l[r]-e[r]+1>=x*.015;let s=0,_=n-1;for(;s<n&&!w(s);)s++;for(;_>s&&!w(_);)_--;if(_-s<8)return null;const U=[];for(let r=s;r<=_;r++)w(r)&&U.push((e[r]+l[r]+1)/2);const A=B(U);let N=m,F=0;for(let r=s;r<=_;r++)w(r)&&(N=Math.min(N,e[r]),F=Math.max(F,l[r]+1));const o=_-s+1,t=o/h,g=new Float32Array(n);for(let r=s;r<=_;r++)g[r]=w(r)?(A-e[r]+(l[r]+1-A))/2:0;const k=[],I=Math.max(4,Math.round(o*.12)),E=g.slice(),v=new Uint8Array(n);for(let r=s;r<=_;r++){let d=1/0,f=1/0;for(let S=1;S<=I;S++)r-S>=s&&(d=Math.min(d,g[r-S])),r+S<=_&&(f=Math.min(f,g[r+S]));d<1/0&&f<1/0&&g[r]>1.25*Math.max(d,f)+2&&(v[r]=1)}for(let r=s;r<=_;r++){if(!v[r])continue;let d=r,f=r;for(;f+1<=_&&v[f+1];)f++;let S=1/0,O=1/0;for(let z=1;z<=I;z++)d-z>=s&&(S=Math.min(S,g[d-z])),f+z<=_&&(O=Math.min(O,g[f+z]));for(;d-1>s&&g[d-1]>S*1.04+1;)d--;for(;f+1<_&&g[f+1]>O*1.04+1;)f++;const D=g[Math.max(s,d-1)],T=g[Math.min(_,f+1)];let $=m,L=0;for(let z=d;z<=f;z++)E[z]=D+(T-D)*(z-d+1)/(f-d+2),$=Math.min($,e[z]),L=Math.max(L,l[z]+1);k.push({rect:[$,d,L,f+1],from_m:+((_-f)/t).toFixed(4),to_m:+((_+1-d)/t).toFixed(4),x_m:+((($+L)/2-A)/t).toFixed(4),width_m:+((L-$)/t).toFixed(4),z_m:+(Math.max(D,T)/t).toFixed(4)}),r=f}const R=r=>r>=s&&r<=_?E[r]:0,i=[],M=Math.max(8,Math.min(c,o));for(let r=0;r<=M;r++){const d=_+1-r/M*o,f=V(Math.floor(d-o/M/2),s,_),S=V(Math.ceil(d+o/M/2),s,_);let O=0;for(let D=f;D<=S;D++)O=Math.max(O,R(D));i.push([+(O/t).toFixed(5),+((_+1-d)/t).toFixed(5)])}for(let r=0;r<2;r++){const d=i.map(f=>f[0]);for(let f=2;f<i.length-2;f++){const S=(d[f-2]+d[f-1]+d[f]+d[f+1]+d[f+2])/5;Math.abs(S-d[f])<Math.max(1.5/t,d[f]*.02)&&(i[f][0]=+S.toFixed(5))}}return i[0][0]>0&&i.unshift([0,0]),i[i.length-1][0]>0&&i.push([0,i[i.length-1][1]]),{bbox:[N,s,F,_+1],axis:A,pxPerM:t,height_m:h,profile:i,segments:W(a,y,e,l,s,_,A,R,t),cards:k,background:p,size:[m,n]}}function W(a,h,c,b,m,n,u,y,p){const{width:e,data:l}=a,x=[];for(let o=m;o<=n;o++){const t=y(o);if(t<=0){x.push(null);continue}const g=Math.round(u-t*.7),k=Math.round(u+t*.7);let I=[0,0,0],E=[],v=0,R=0,i=-1;for(let d=Math.max(0,g);d<=Math.min(e-1,k);d++){const f=o*e+d;if(!h[f])continue;const S=f*4,O=.2126*l[S]+.7152*l[S+1]+.0722*l[S+2];I[0]+=l[S],I[1]+=l[S+1],I[2]+=l[S+2],E.push(O),i>=0&&(R+=Math.abs(O-i)),i=O,v++}if(!v){x.push(null);continue}const M=[...E].sort((d,f)=>d-f),r=M[Math.floor(v*.95)]-M[Math.floor(v*.05)];x.push({y:o,w:t,c:I.map(d=>d/v),spread:r,hi:M[Math.floor(v*.98)],rough:r>0?R/r:0})}const w=[];let s=null;const _=(o,t)=>Math.hypot(o[0]-t[0],o[1]-t[1],o[2]-t[2]);for(const o of x)if(o)if(s&&(_(o.c,s.c)>55||Math.abs(o.w-s.w)>Math.max(3,s.w*.12))&&(w.push(s),s=null),!s)s={y0:o.y,y1:o.y,c:[...o.c],n:1,spread:o.spread,hi:o.hi,w:o.w,rough:o.rough};else{s.y1=o.y,s.n++;for(let t=0;t<3;t++)s.c[t]+=(o.c[t]-s.c[t])/s.n;s.spread+=(o.spread-s.spread)/s.n,s.hi=Math.max(s.hi,o.hi),s.w+=(o.w-s.w)/s.n,s.rough+=(o.rough-s.rough)/s.n}s&&w.push(s);const U=Math.max(3,(n-m+1)*.02);for(let o=w.length-1;o>=0&&w.length>1;o--)if(w[o].y1-w[o].y0+1<U){const t=o>0?o-1:o+1;w[t].y0=Math.min(w[t].y0,w[o].y0),w[t].y1=Math.max(w[t].y1,w[o].y1),w.splice(o,1)}const A=w.map(o=>{const t=o.c.map(v=>Math.round(v)),g=Math.max(...t),k=Math.min(...t),I=g?(g-k)/g:0,E=o.spread>90&&o.hi>190&&o.rough<2.2;return{from_m:+((n+1-(o.y1+1))/p).toFixed(4),to_m:+((n+1-o.y0)/p).toFixed(4),color:"#"+t.map(v=>v.toString(16).padStart(2,"0")).join(""),material:E?I>.35&&t[0]>t[2]?"gold":"chrome":"printed"}}),N=(n+1-m)/p;for(const o of A)o.material!=="printed"&&o.to_m-o.from_m<N*.04&&(o.material="printed");A.sort((o,t)=>o.from_m-t.from_m);const F=[];for(const o of A){const t=F[F.length-1];t&&t.material===o.material?t.to_m=Math.max(t.to_m,o.to_m):F.push({...o})}return F.forEach((o,t)=>{t&&(o.from_m=F[t-1].to_m)}),F.length&&(F[0].from_m=0,F[F.length-1].to_m=+((n+1-m)/p).toFixed(4)),F}const Z=1600;function q(a){const h=/^https:\/\/storage\.googleapis\.com\/([^/?]+)\/([^?]+)\?.*X-Goog-Signature/.exec(a);return h?`gs://${h[1]}/${decodeURIComponent(h[2])}`:a}const Q={gold:"gold",chrome:"chrome",steel:"brushed_steel",printed:"plastic_glossy",plastic:"plastic_glossy",matte:"plastic_matte",glass:"glass_clear",frosted:"glass_frosted",paper:"paper",ceramic:"ceramic"};async function G(a){const h=await fetch(a,{mode:"cors"});if(!h.ok)throw new Error(`the image could not be loaded (HTTP ${h.status})`);const c=await createImageBitmap(await h.blob()),b=Math.min(1,Z/Math.max(c.width,c.height)),m=Math.max(1,Math.round(c.width*b)),n=Math.max(1,Math.round(c.height*b)),u=document.createElement("canvas");u.width=m,u.height=n;const y=u.getContext("2d",{willReadFrequently:!0});y.drawImage(c,0,0,m,n);const p=y.getImageData(0,0,m,n);return{img:{width:m,height:n,data:p.data},full:[c.width,c.height],k:b}}function H(a,h,c){const b=u=>{for(let y=1;y<a.length;y++){const p=a[y-1],e=a[y];if(p[1]<=u&&u<=e[1]&&e[1]>p[1]){const l=(u-p[1])/(e[1]-p[1]);return[+(p[0]+(e[0]-p[0])*l).toFixed(5),+u.toFixed(5)]}}return[0,u]},m=a[a.length-1][1],n=[];h<=1e-6&&n.push([0,0]),n.push(b(h));for(const u of a)u[1]>h+1e-6&&u[1]<c-1e-6&&u[0]>0&&n.push(u);return n.push(b(c)),c>=m-1e-6&&n.push([0,+m.toFixed(5)]),n.length>=2?n:[[0,h],[0,c]]}function Y(a,h,c={}){const b=(e,l)=>({url:q(l.url),axis:+(e.axis/l.k).toFixed(2),base:+(e.bbox[3]/l.k).toFixed(2),ppm:+(e.pxPerM/l.k).toFixed(2),size:l.full}),m=b(a,h),n=c.back?b(c.back.scan,c.back):void 0,u=a.segments.length?a.segments:[{from_m:0,to_m:a.height_m,color:"#888888",material:"printed"}],y=u.map((e,l)=>{const x=c.finishes?.[l]??e.material;return{name:l===u.length-1&&u.length>1?"cap":u.length===1?"body":`part ${l+1}`,shape:"lathe",profile:H(a.profile,e.from_m,e.to_m),material:Q[x]??"plastic_glossy",photo:{...m,...n?{back:n}:{}}}}),p=a.background?"#"+a.background.map(e=>Math.round(e).toString(16).padStart(2,"0")).join(""):void 0;return a.cards.forEach((e,l)=>y.push({name:`tag ${l+1}`,shape:"box",size:[e.width_m,+(e.to_m-e.from_m).toFixed(4),.0015],position:[e.x_m,e.from_m,+(e.z_m+.002).toFixed(4)],material:"paper",photo:{...m,...p?{keyout:p}:{}}})),(c.labels??[]).forEach((e,l)=>{const x=e.bottom+e.height,w=H(a.profile,Math.max(0,e.bottom),Math.min(a.height_m,x)).filter(_=>_[0]>0).map(([_,U])=>[+(_+4e-4).toFixed(5),U]);if(w.length<2)return;const s=e.width??e.height*(e.size[0]/e.size[1]);y.push({name:`label ${l+1}`,shape:"lathe",profile:w,wrap:{url:q(e.url),size:e.size,bottom:e.bottom,height:e.height,width:+s.toFixed(4),center:e.center??0,finish:e.finish??"matte"}})}),X({v:1,parts:y})}async function _t(a,h){const c=String(a.image??"").trim(),b=Number(a.height_m);if(!c)return{ok:!1,error:"image: the URL of a photo of the product (front, square-on, plain background)"};if(!(b>.005&&b<=5))return{ok:!1,error:"height_m: the real height of the product in metres (e.g. 0.12 for a 12 cm bottle)"};let m,n;try{m=await G(c),a.back_image&&(n=await G(String(a.back_image)))}catch(i){return{ok:!1,error:i.message}}const u=j(m.img,{height_m:b});if(!u)return{ok:!1,error:"no product found in the photo: use a photo of the product alone, square-on, on a plain background (or a transparent PNG)"};const y=n?j(n.img,{height_m:b}):null,p=Array.isArray(a.finishes)?a.finishes.map(String):void 0,e=[];for(const i of Array.isArray(a.labels)?a.labels:[]){const M=String(i?.image??"").trim(),r=Number(i?.bottom_m),d=Number(i?.height_m);if(!M||!(d>0)||!(r>=0))return{ok:!1,error:"labels: each needs image, bottom_m (height of its lower edge above the base) and height_m"};let f;try{f=(await G(M)).full}catch(S){return{ok:!1,error:`label ${M}: ${S.message}`}}e.push({url:M,size:f,bottom:r,height:d,...Number(i.width_m)>0?{width:Number(i.width_m)}:{},...i.center_deg!=null?{center:Number(i.center_deg)||0}:{},...["matte","gloss","foil"].includes(String(i.finish))?{finish:String(i.finish)}:{}})}let l;try{l=Y(u,{url:c,full:m.full,k:m.k},{...n&&y?{back:{url:String(a.back_image),scan:y,full:n.full,k:n.k}}:{},...p?{finishes:p}:{},labels:e})}catch(i){return{ok:!1,error:i.message}}const{makeItem:x,saveSetOf:w,onGround:s,GROUND_NOTE:_}=await P(async()=>{const{makeItem:i,saveSetOf:M,onGround:r,GROUND_NOTE:d}=await import("./remote-DJd9xWjn.js").then(f=>f.fO);return{makeItem:i,saveSetOf:M,onGround:r,GROUND_NOTE:d}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])),U=h.getStage(),A=String(a.name||"Sản phẩm").trim().slice(0,60)||"Sản phẩm",N=U.items.find(i=>i.kind==="set"&&i.name===A&&i.set),F=N?.set?.id??crypto.randomUUID();await w(h)(F,A,l),h.engine()?.cacheSet(F,l);const o=C(l),t={id:F,name:A,parts:l.parts.length,min:o.min,max:o.max},g=a.position!=null&&Array.isArray(a.position)?s(a.position.slice(0,3).map(Number)):null,k={...g?{position:g.position}:{},...a.yaw_deg!=null?{rotation:[0,Number(a.yaw_deg)||0,0]}:{}};let I=A,E=N?.id;if(N)h.setStage(i=>({...i,items:i.items.map(M=>M.id===N.id?{...M,...k,set:t}:M)}));else{const i=x(h.getStage(),{kind:"set",name:A,color:"#9aa3a8",set:t,...k});I=i.name,E=i.id,h.setStage(M=>({...M,items:[...M.items,i]}))}const v=2*Math.max(...u.profile.map(i=>i[0])),R=a.save_glb?await tt({name:I},h):null;return{ok:!0,name:I,id:E,rebuilt:!!N,size_m:o.size,height_m:b,diameter_m:+v.toFixed(4),parts:u.segments.map((i,M)=>({from_m:i.from_m,to_m:i.to_m,colour:i.color,finish:p?.[M]??i.material})),...g?.lifted?{note:_}:{},...R?{glb:R.ok?{url:R.url,gcsUri:R.gcsUri,file:R.file}:{error:R.error}}:{},...e.length?{labels:e.map(i=>({bottom_m:i.bottom,height_m:i.height,width_m:+(i.width??i.height*(i.size[0]/i.size[1])).toFixed(4),center_deg:i.center??0}))}:{},hint:"seen from the front (+Z) the model shows the photo itself; put the camera square-on for a pack shot. finishes: one per part (gold, chrome, steel, printed, matte, glass, frosted, paper, ceramic) to correct a guess."}}async function tt(a,h){const{findItem:c}=await P(async()=>{const{findItem:e}=await import("./remote-DJd9xWjn.js").then(l=>l.fN);return{findItem:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])),{loadSetOf:b}=await P(async()=>{const{loadSetOf:e}=await import("./remote-DJd9xWjn.js").then(l=>l.fO);return{loadSetOf:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]));let m;try{m=c(h.getStage(),String(a.name??""))}catch(e){return{ok:!1,error:e.message}}if(m.kind!=="set"||!m.set)return{ok:!1,error:`'${m.name}' is not a modelled object (a product, a kit model or a built set); a GLB library model is already a .glb`};let n=h.engine()?.setRecipe(m.set.id)??null;try{n||(n=await b(h)(m.set.id))}catch(e){return{ok:!1,error:e.message}}if(!n)return{ok:!1,error:"the model could not be loaded"};const{recipeGlb:u}=await P(async()=>{const{recipeGlb:e}=await import("./exportGlb-BOdI9cVS.js");return{recipeGlb:e}},__vite__mapDeps([16,4,0,1,2,3,5,6,7,8,9,10,11,12,13,14,15]));let y;try{y=await u(n)}catch(e){return{ok:!1,error:`export failed: ${e.message}`}}const p=`${(String(a.file_name||m.name).trim()||"model").replace(/[^\p{L}\p{N} _.-]+/gu,"").slice(0,60)||"model"}.glb`;try{const l=await(h.uploadFile??(async x=>(await P(async()=>{const{uploadFile:w}=await import("./api-BFN7blbw.js").then(s=>s.bV);return{uploadFile:w}},__vite__mapDeps([3,4,2,1]))).uploadFile(x)))(new File([y],p,{type:"model/gltf-binary"}));return{ok:!0,name:m.name,file:p,bytes:y.size,url:l.url,gcsUri:l.gcsUri,note:"saved in My assets (Models); it can be downloaded or added to any scene from there"}}catch(e){return{ok:!1,error:`upload failed: ${e.message}`,bytes:y.size}}}export{q as durableUrl,G as loadPixels,_t as modelProduct,Y as productRecipe,tt as saveGlb};
|