`).map((E)=>E.trim()).filter(Boolean),C=[],F={cuda:"nvenc",qsv:"qsv",vaapi:"vaapi",videotoolbox:"videotoolbox",v4l2m2m:"v4l2",dxva2:"amf"};for(let E of u){let A=F[E];if(A)C.push({accelerator:A})}return C}async function WD(D){let u=["-v","error","-f","lavfi","-i","testsrc=size=320x240:rate=1","-frames:v","1","-an","-c:v",D,"-f","null","-"];return new Promise((C)=>{let F=g("ffmpeg",u);F.on("error",()=>C(!1)),F.on("close",(E)=>C(E===0))})}async function ND(D,u){let C=["-v","error"];if(D==="nvenc")C.push("-hwaccel","cuda","-hwaccel_output_format","cuda");else if(D==="qsv")C.push("-hwaccel","qsv");else if(D==="vaapi")C.push("-hwaccel","vaapi","-vaapi_device","/dev/dri/renderD128");else if(D==="videotoolbox")C.push("-hwaccel","videotoolbox");else if(D==="v4l2")C.push("-hwaccel","v4l2m2m");else if(D==="amf")return!1;return C.push("-i",u,"-frames:v","1","-f","null","-"),new Promise((F)=>{let E=g("ffmpeg",C);E.on("error",()=>F(!1)),E.on("close",(A)=>F(A===0))})}async function d(D,u,C){let E=`
${X}`))}})})}import{spawn as tF}from"node:child_process";async function DD(D){return new Promise((u,C)=>{let F=tF("ffprobe",["-v","error","-show_entries","stream=width,height,duration,r_frame_rate,codec_name,codec_type,bit_rate","-show_entries","format=duration","-of","json",D]),E="";F.stdout.on("data",(A)=>{E+=A.toString()}),F.on("error",(A)=>{C(Error(`ffprobeerror:${A.message}`))}),F.on("close",(A)=>{if(A!==0){C(Error(`ffprobefailedwithexitcode${A}`));return}try{let B=JSON.parse(E),$=B.streams.find((J)=>J.codec_type==="video"),K=B.streams.find((J)=>J.codec_type==="audio"),X=B.format;if(!$){C(Error("No video stream found in input file"));return}let G=30;if($.r_frame_rate){let[J,N]=$.r_frame_rate.split("/").map(Number);if(J&&N&&N!==0)G=J/N}let Y=parseFloat($.duration||X.duration||"0"),Z=B.streams.find((J)=>J.codec_type==="audio"&&J.bit_rate),k=Z?.bit_rate?Math.round(parseInt(Z.bit_rate)/1000):void 0,_=$.bit_rate?Math.round(parseInt($.bit_rate)/1000):void 0;u({width:$.width,height:$.height,duration:Y,fps:G,codec:$.codec_name,hasAudio:Boolean(K),audioBitrate:k,videoBitrate:_})}catch(B){C(Error(`Failedtoparseffprobeoutput:${B}`))}})})}function kD(D,u=256){if(!D)return`${u}k`;let F=Math.max(D,64),E=Math.min(F,u);if(E<=64)return"64k";if(E<=96)return"96k";if(E<=128)return"128k";if(E<=192)return"192k";return"256k"}function QD(D){let u=Math.floor(D/3600),C=Math.floor(D%3600/60),F=D%60;return`${String(u).padStart(2,"0")}:${String(C).padStart(2,"0")}:${F.toFixed(3).padStart(6,"0")}`}import{mkdir as eF,access as D8,constants as u8}from"node:fs/promises";async function n(D){try{await D8(D,u8.F_OK)}catch{await eF(D,{recursive:!0})}}function C8(D,u){let C=D*u;if(C<=230400)return 0.08;if(C<=409920)return 0.075;if(C<=921600)return 0.07;if(C<=2073600)return 0.065;if(C<=3686400)return 0.06;return 0.055}function v(D,u,C=30,F){let E=C8(D,u),A=Math.round(D*u*C*E/1000);if(F&&A>F)A=F;return`${A}k`}var vD=[{name:"360p",width:640,height:360,videoBitrate:v(640,360,30),audioBitrate:"192k"},{name:"480p",width:854,height:480,videoBitrate:v(854,480,30),audioBitrate:"192k"},{name:"720p",width:1280,height:720,videoBitrate:v(1280,720,30),audioBitrate:"192k"},{name:"1080p",width:1920,height:1080,videoBitrate:v(1920,1080,30),audioBitrate:"256k"},{name:"1440p",width:2560,height:1440,videoBitrate:v(2560,1440,30),audioBitrate:"256k"},{name:"2160p",width:3840,height:2160,videoBitrate:v(3840,2160,30),audioBitrate:"256k"}];function KD(D,u,C=30,F){let E=[],A=vD.filter((B)=>{return B.height<=u});for(let B of A)E.push({...B,videoBitrate:v(B.width,B.height,30,F),fps:30});return E}function B8(D,u,C){return{...D,name:`${D.name}-${u}`,videoBitrate:v(D.width,D.height,u,C),fps:u}}function Wu(D){let C=D.trim().match(/^(\d+)p?(?:[@-](\d+))?$/i);if(!C)return null;let F=C[1]+"p",E=C[2]?parseInt(C[2]):30;return{resolution:F,fps:E}}function Nu(D,u=30,C){let F=vD.find((E)=>E.name===D);if(!F)return null;if(u===30)return{...F,videoBitrate:v(F.width,F.height,30,C),fps:30};return B8(F,u,C)}function A8(D,u,C,F){let E=Wu(D);if(!E)return{error:`Invalidprofileformat:${D}.Useformatlike:360,720@60,1080-60`};let A=Nu(E.resolution,E.fps);if(!A)return{error:`Unknownresolution:${E.resolution}.Available:360,480,720,1080,1440,2160`};if(A.height>C)return{error:`Sourceheight(${C}px)islowerthanrequested${D}height(${A.height}px)`};let B=120,$=E.fps,K;if(E.fps>F)$=Math.min(F,B),K=`Requested${E.fps}FPSin${D},butsourceis${F}FPS.Using${$}FPSinstead`;else if(E.fps>B)$=B,K=`Requested${E.fps}FPSin${D}exceedsmaximum${B}FPS.Using${$}FPSinstead`;return K?{warning:K,adjustedFps:$}:{}}function _D(D,u,C,F,E){let A=[],B=[],$=[];for(let K of D){let X=A8(K,u,C,F);if(X.error){B.push(X.error);continue}if(X.warning)$.push(X.warning);let G=Wu(K);if(!G)continue;let Y=X.adjustedFps!==void 0?X.adjustedFps:G.fps,Z=Nu(G.resolution,Y,E);if(Z)A.push(Z)}return{profiles:A,errors:B,warnings:$}}import{join as m}from"node:path";import{readdir as Z8,unlink as ku,rmdir as $8,writeFile as Qu}from"node:fs/promises";async function _u(D,u,C="00:00:00"){let F=m(u,"poster
`;for(let F of D){let E=u?"avc1.4D4020,mp4a.40.2":"avc1.4D4020";if(C+=`#EXT-X-STREAM-INF:BANDWIDTH=${F.bandwidth},CODECS="${E}",RESOLUTION=${F.resolution},FRAME-RATE=${F.fps}`,u)C+=',AUDIO="audio"';C+=`
`}return C}async function Y8(D,u,C,F,E,A){let B=L(u,"manifest.mpd"),$=E.length>1,K=["-dash",String(F*1000),"-frag",String(F*1000),"-rap","-segment-timeline","-segment-name","$RepresentationID$_$Number$","-out",B],X=!0;for(let[G,Y]of D.entries())for(let Z of C){let k=Y.get(Z.name);if(!k)throw Error(`MP4filenotfoundforprofile:${Z.name},codec:${G}`);let _=$?`${Z.name}-${G}`:Z.name;if(K.push(`${k}#video:id=${_}`),X&&A)K.push(`${k}#audio:id=audio`),X=!1}if(await bD(K),await G8(u,C,E,A),await Hu(B),$)await xu(B);return await Vu(B),B}async function G8(D,u,C,F){let{readdir:E,rename:A,mkdir:B}=await import("node:fs/promises"),$=C.length>1,K=[];for(let Y of C)for(let Z of u){let k=$?`${Z.name}-${Y}`:Z.name;K.push(k);let _=L(D,k);await B(_,{recursive:!0})}let X=L(D,"audio");if(F)await B(X,{recursive:!0});let G=await E(D);for(let Y of G){if(Y==="manifest.mpd")continue;if(F&&(Y.startsWith("audio_")||Y==="audio_init.m4s")){let Z=L(D,Y),k=L(X,Y);await A(Z,k);continue}for(let Z of K)if(Y.startsWith(`${Z}_`)){let k=L(D,Y),_=L(D,Z,Y);await A(k,_);break}}}async function Lu(D,u,C,F,E,A,B){let $,K,X=A.length>0,G=A.includes("dash"),Y=A.includes("hls");if(X){if($=await Y8(D,u,C,F,E,B),!G)$=void 0}if(Y)K=await U8(u,C,F,E.length>1,B);return{manifestPath:$,hlsManifestPath:K}}async function U8(D,u,C,F,E){let A=L(D,"master.m3u8"),B=[];for(let G of u){let Y=F?`${G.name}-h264`:G.name,Z=L(D,Y),k=await Ou(Z),_=k.filter((z)=>z.endsWith(".m4s")).sort((z,j)=>{let O=parseInt(z.match(/_(\d+)\.m4s$/)?.[1]||"0"),x=parseInt(j.match(/_(\d+)\.m4s$/)?.[1]||"0");return O-x}),J=k.find((z)=>z.endsWith("_.mp4"));if(!J||_.length===0)continue;let N=fD(_,J,C),U=L(Z,"playlist.m3u8");await gD(U,N,"utf-8");let W=parseInt(G.videoBitrate)*1000;B.push({path:`${Y}/playlist.m3u8`,bandwidth:W,resolution:`${G.width}x${G.height}`,fps:G.fps||30})}let $,K=[];if(E){let G=L(D,"audio"),Y=[];try{Y=await Ou(G)}catch{Y=[]}if(K=Y.filter((Z)=>Z.endsWith(".m4s")).sort((Z,k)=>{let _=parseInt(Z.match(/_(\d+)\.m4s$/)?.[1]||"0"),J=parseInt(k.match(/_(\d+)\.m4s$/)?.[1]||"0");return _-J}),$=Y.find((Z)=>Z.endsWith("_.mp4")),$&&K.length>0){let Z=fD(K,$,C);await gD(L(G,"playlist.m3u8"),Z,"utf-8")}}let X=Mu(B,E&&$!==void 0&&K.length>0);return await gD(A,X,"utf-8"),A}async function mD(D){let{input:u,outputDir:C,segmentDuration:F=2,profiles:E,customProfiles:A,codec:B=["h264"],formats:$=["dash","hls"],hardwareDecoder:K,hardwareAccelerator:X,quality:G,generateThumbnails:Y=!0,thumbnailConfig:Z={},generatePoster:k=!0,posterTimecode:_="00:00:00",parallel:J=!0,muted:N=!1,onProgress:U}=D,W=zD("/tmp",`dash-converter-${W8()}`);await n(W);let z=ju(u,Tu(u)),j=zD(C,z);await n(j);let O=zD(j,"conversion.log");SD(O);let{writeFile:x}=await import("node:fs/promises"),T=`===========================================
`,"utf-8")}catch(p){}try{await wu(W,{recursive:!0,force:!0})}catch(p){console.warn(`Warning:Failedtocleanuptempdirectory:${W}`)}}}async function N8(D,u,C,F,E,A,B,$,K,X,G,Y,Z,k,_,J,N,U){if(!await r())throw Error("FFmpeg is not installed or not in PATH");if(!await o())throw Error("MP4Box is not installed or not in PATH. Install gpac package.");let W=(q,V,TD,wD)=>{if(U)U({stage:q,percent:V,message:TD,currentProfile:wD})};W("analyzing",0,"Analyzing input video...");let z=await DD(D),j=!N&&z.hasAudio,O=z.duration,x=Math.max(1,Math.ceil(O/F)),T=O/x,l=K&&K!=="auto"?K:"auto",p=await t(),OD=await e(),LD=p.some((q)=>q.av1Encoder),AD=Array.isArray(B)?B:[B],ZD=AD.includes("h264"),RD=AD.includes("av1"),{selected:YD,h264Encoder:SF,av1Encoder:bF,warnings:Cu}=k8(p,l,ZD,RD);if(Cu.length>0)for(let q of Cu)console.warn(`⚠️${q}`);let{selected:GD}=Q8(OD,X||"auto");if(RD&&!LD)console.warn("⚠️ AV1 hardware encoder not detected. AV1 will use CPU encoder (slow).");let P=[];if(ZD)P.push("h264");if(RD)P.push("av1");if(P.length===0)P.push("h264");let Bu=$&&$.length>0?Array.from(new Set($)):["dash","hls"],R;if(A&&A.length>0){let q=_D(A,z.width,z.height,z.fps,z.videoBitrate);if(q.errors.length>0){console.warn(`
`);var xF=await r(),MF=await o(),OF=await t(),a8=await e(),i8=OF.some((D)=>D.av1Encoder),HD={nvenc:100,qsv:90,amf:80,vaapi:70,videotoolbox:65,v4l2:60,cpu:1},r8={nvenc:"h264_nvenc",qsv:"h264_qsv",amf:"h264_amf",vaapi:"h264_vaapi",videotoolbox:"h264_videotoolbox",v4l2:"h264_v4l2m2m",cpu:"libx264"},o8=Array.from(new Set([...OF.map((D)=>D.accelerator),"cpu"])),t8=Array.from(new Set([...a8.map((D)=>D.accelerator),"cpu"]));async function e8(){let D=[];for(let u of o8){if(u==="amf")continue;let C=r8[u]||"libx264";if(await WD(C))D.push(u)}return D}async function D3(){let D=[];for(let u of t8){if(u==="cpu"){D.push("cpu");continue}if(await ND(u,a))D.push(u)}return D}var LF=await e8(),RF=await D3(),CD=LF.slice().sort((D,u)=>(HD[u]||0)-(HD[D]||0))[0],BD=RF.slice().sort((D,u)=>(HD[u]||0)-(HD[D]||0))[0];console.log(`FFmpeg:${xF?"✅":"❌"}`);console.log(`MP4Box:${MF?"✅":"❌"}`);var QF=Array.from(new Set(LF.map((D)=>D.toUpperCase()))),_F=Array.from(new Set(RF.map((D)=>D.toUpperCase()))),zF=FD?FD.toUpperCase():CD&&CD.toUpperCase()||"CPU",jF=QF.length>0?QF:["CPU"],qF=ED?ED.toUpperCase():BD&&BD.toUpperCase()||"CPU",TF=_F.length>0?_F:["CPU"];console.log(`Encoder:${zF==="AUTO"?CD&&CD.toUpperCase()||"CPU":zF}(${jF.join(", ")})`);console.log(`Decoder:${qF==="AUTO"?BD&&BD.toUpperCase()||"CPU":qF}(${TF.join(", ")})`);console.log("");if(!xF)console.error("❌ FFmpeg not found. Please install FFmpeg first."),process.exit(1);if(!MF)console.error("❌ MP4Box not found. Please install: sudo pacman -S gpac"),process.exit(1);var Eu=VD&&VD.length>0?VD:["h264"],xD=Eu.includes("h264"),MD=Eu.includes("av1");if(!xD)console.warn("⚠️ H.264 is mandatory for compatibility. Adding H.264."),xD=!0;if(MD&&!i8)console.error("⚠️ AV1 requested but no hardware AV1 encoder found."),console.error(" CPU-based AV1 encoding (libsvtav1) will be VERY slow."),console.error(`Considerusing--codech264forfasterencoding.