video-frames
Version:
Client-side video frames extraction as base64 encoded images
1 lines • 1.8 kB
JavaScript
module.exports=async a=>{var h,i,j;let p=0,o=!1,q,k=!1,r=[],l=a=>+a+""==a+"",m=a=>l(a)&& +a>=0&& +a<=b.duration,c=(b,c)=>{a[b]=n.call(a,b)?a[b]:c},n={}.hasOwnProperty,b=document.createElement("video");for(b.src=a.url,b.crossOrigin="anonymous",b.onseeked=async()=>{q&&q()},b.onerror=()=>{o=!0};(b.duration===1/0||isNaN(b.duration))&&b.readyState<2&&(await new Promise(a=>setTimeout(a,100)),b.currentTime=1e7*Math.random(),!o););(b.currentTime=b.duration/2,await new Promise(a=>{q=a}),c("format","image/png"),c("offsets",[]),c("startTime",0),c("endTime",b.duration),c("count",1),c("onLoad",!1),c("onProgress",!1),h=Array,a.offsets instanceof h)?a.offsets=a.offsets.filter(a=>m(a)):a.offsets=[],0!==a.offsets.length&&(k=!0),m(a.startTime)||(a.startTime=0),m(a.endTime)||(a.endTime=b.duration),a.startTime=+a.startTime,a.endTime=+a.endTime,a.startTime>=a.endTime&&(a.startTime=a.endTime,a.count=1),a.count=Math.abs(~~a.count),0===a.count&&(a.count=1),k&&(a.count=a.offsets.length);let s=(a.endTime-a.startTime)/a.count,d=n.call(a,"width"),e=n.call(a,"height"),f=b.videoWidth/b.videoHeight;d&&!l(a.width)&&(d=!1),e&&!l(a.height)&&(e=!1),d||e?d&&!e?a.height=a.width/f:!d&&e&&(a.width=a.height*f):(a.width=128,a.height=a.width/f),a.width=+a.width,a.height=+a.height,i=Function,a.onLoad instanceof i||(a.onLoad=!1),j=Function,a.onProgress instanceof j||(a.onProgress=!1),a.onLoad&&a.onLoad();let g=document.createElement("canvas"),t=g.getContext("2d");g.width=a.width,g.height=a.height;let u=async c=>{for(;p<a.count;)b.currentTime=k?a.offsets[p]:a.startTime+p*s,await new Promise(a=>{q=a}),t.clearRect(0,0,g.width,g.height),t.drawImage(b,0,0,g.width,g.height),r.push({offset:b.currentTime,image:g.toDataURL(a.format)}),p++,a.onProgress&&a.onProgress(p,a.count);c(r)};return new Promise(a=>{o&&a([]),u(a)})}