Skip to content

The free and privacy-friendly screen recorder with no limits 🎥

WebCodecs implementation

Alyssa Xc9b5d8e3225a
diff --git a/package-lock.json b/package-lock.json
index 693643e..da713f6 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -36,8 +36,10 @@
"dotenv": "^17.0.1",
"fabric": "^5.3.0",
"fix-webm-duration": "^1.0.5",
+ "gif.js": "^0.2.0",
"jszip": "^3.10.1",
"localforage": "^1.10.0",
+ "mediabunny": "^1.24.4",
"patch-package": "^8.0.0",
"plyr": "3.7.8",
"plyr-react": "^5.3.0",
@@ -3910,6 +3912,19 @@
"@types/node": "*"
}
},
+ "node_modules/@types/dom-mediacapture-transform": {
+ "version": "0.1.11",
+ "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.11.tgz",
+ "integrity": "sha512-Y2p+nGf1bF2XMttBnsVPHUWzRRZzqUoJAKmiP10b5umnO6DDrWI0BrGDJy1pOHoOULVmGSfFNkQrAlC5dcj6nQ==",
+ "dependencies": {
+ "@types/dom-webcodecs": "*"
+ }
+ },
+ "node_modules/@types/dom-webcodecs": {
+ "version": "0.1.13",
+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
+ "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ=="
+ },
"node_modules/@types/eslint": {
"version": "9.6.1",
"resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz",
@@ -6787,6 +6802,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/gif.js": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/gif.js/-/gif.js-0.2.0.tgz",
+ "integrity": "sha512-bYxCoT8OZKmbxY8RN4qDiYuj4nrQDTzgLRcFVovyona1PTWNePzI4nzOmotnlOFIzTk/ZxAHtv+TfVLiBWj/hw==",
+ "license": "MIT"
+ },
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
@@ -7881,6 +7902,22 @@
"node": ">= 0.6"
}
},
+ "node_modules/mediabunny": {
+ "version": "1.24.4",
+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.24.4.tgz",
+ "integrity": "sha512-dpWYBPTtMg152yNLXZQ7xb6hsXdYbKp9EuK8qq4npS+SZ08FVc1XHlXYhrOm31T+tUVJKgm95Yaqy69wTpZP9Q==",
+ "workspaces": [
+ "packages/*"
+ ],
+ "dependencies": {
+ "@types/dom-mediacapture-transform": "^0.1.11",
+ "@types/dom-webcodecs": "0.1.13"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://github.com/sponsors/Vanilagy"
+ }
+ },
"node_modules/memfs": {
"version": "3.5.3",
"resolved": "https://registry.npmjs.org/memfs/-/memfs-3.5.3.tgz",
diff --git a/package.json b/package.json
index 5e8570e..5036f02 100755
--- a/package.json
+++ b/package.json
@@ -42,8 +42,10 @@
"dotenv": "^17.0.1",
"fabric": "^5.3.0",
"fix-webm-duration": "^1.0.5",
+ "gif.js": "^0.2.0",
"jszip": "^3.10.1",
"localforage": "^1.10.0",
+ "mediabunny": "^1.24.4",
"patch-package": "^8.0.0",
"plyr": "3.7.8",
"plyr-react": "^5.3.0",
diff --git a/src/assets/vendor/gif.js/gif.worker.js b/src/assets/vendor/gif.js/gif.worker.js
new file mode 100644
index 0000000..269624e
--- /dev/null
+++ b/src/assets/vendor/gif.js/gif.worker.js
@@ -0,0 +1,3 @@
+// gif.worker.js 0.2.0 - https://github.com/jnordberg/gif.js
+(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){var NeuQuant=require("./TypedNeuQuant.js");var LZWEncoder=require("./LZWEncoder.js");function ByteArray(){this.page=-1;this.pages=[];this.newPage()}ByteArray.pageSize=4096;ByteArray.charMap={};for(var i=0;i<256;i++)ByteArray.charMap[i]=String.fromCharCode(i);ByteArray.prototype.newPage=function(){this.pages[++this.page]=new Uint8Array(ByteArray.pageSize);this.cursor=0};ByteArray.prototype.getData=function(){var rv="";for(var p=0;p<this.pages.length;p++){for(var i=0;i<ByteArray.pageSize;i++){rv+=ByteArray.charMap[this.pages[p][i]]}}return rv};ByteArray.prototype.writeByte=function(val){if(this.cursor>=ByteArray.pageSize)this.newPage();this.pages[this.page][this.cursor++]=val};ByteArray.prototype.writeUTFBytes=function(string){for(var l=string.length,i=0;i<l;i++)this.writeByte(string.charCodeAt(i))};ByteArray.prototype.writeBytes=function(array,offset,length){for(var l=length||array.length,i=offset||0;i<l;i++)this.writeByte(array[i])};function GIFEncoder(width,height){this.width=~~width;this.height=~~height;this.transparent=null;this.transIndex=0;this.repeat=-1;this.delay=0;this.image=null;this.pixels=null;this.indexedPixels=null;this.colorDepth=null;this.colorTab=null;this.neuQuant=null;this.usedEntry=new Array;this.palSize=7;this.dispose=-1;this.firstFrame=true;this.sample=10;this.dither=false;this.globalPalette=false;this.out=new ByteArray}GIFEncoder.prototype.setDelay=function(milliseconds){this.delay=Math.round(milliseconds/10)};GIFEncoder.prototype.setFrameRate=function(fps){this.delay=Math.round(100/fps)};GIFEncoder.prototype.setDispose=function(disposalCode){if(disposalCode>=0)this.dispose=disposalCode};GIFEncoder.prototype.setRepeat=function(repeat){this.repeat=repeat};GIFEncoder.prototype.setTransparent=function(color){this.transparent=color};GIFEncoder.prototype.addFrame=function(imageData){this.image=imageData;this.colorTab=this.globalPalette&&this.globalPalette.slice?this.globalPalette:null;this.getImagePixels();this.analyzePixels();if(this.globalPalette===true)this.globalPalette=this.colorTab;if(this.firstFrame){this.writeLSD();this.writePalette();if(this.repeat>=0){this.writeNetscapeExt()}}this.writeGraphicCtrlExt();this.writeImageDesc();if(!this.firstFrame&&!this.globalPalette)this.writePalette();this.writePixels();this.firstFrame=false};GIFEncoder.prototype.finish=function(){this.out.writeByte(59)};GIFEncoder.prototype.setQuality=function(quality){if(quality<1)quality=1;this.sample=quality};GIFEncoder.prototype.setDither=function(dither){if(dither===true)dither="FloydSteinberg";this.dither=dither};GIFEncoder.prototype.setGlobalPalette=function(palette){this.globalPalette=palette};GIFEncoder.prototype.getGlobalPalette=function(){return this.globalPalette&&this.globalPalette.slice&&this.globalPalette.slice(0)||this.globalPalette};GIFEncoder.prototype.writeHeader=function(){this.out.writeUTFBytes("GIF89a")};GIFEncoder.prototype.analyzePixels=function(){if(!this.colorTab){this.neuQuant=new NeuQuant(this.pixels,this.sample);this.neuQuant.buildColormap();this.colorTab=this.neuQuant.getColormap()}if(this.dither){this.ditherPixels(this.dither.replace("-serpentine",""),this.dither.match(/-serpentine/)!==null)}else{this.indexPixels()}this.pixels=null;this.colorDepth=8;this.palSize=7;if(this.transparent!==null){this.transIndex=this.findClosest(this.transparent,true)}};GIFEncoder.prototype.indexPixels=function(imgq){var nPix=this.pixels.length/3;this.indexedPixels=new Uint8Array(nPix);var k=0;for(var j=0;j<nPix;j++){var index=this.findClosestRGB(this.pixels[k++]&255,this.pixels[k++]&255,this.pixels[k++]&255);this.usedEntry[index]=true;this.indexedPixels[j]=index}};GIFEncoder.prototype.ditherPixels=function(kernel,serpentine){var kernels={FalseFloydSteinberg:[[3/8,1,0],[3/8,0,1],[2/8,1,1]],FloydSteinberg:[[7/16,1,0],[3/16,-1,1],[5/16,0,1],[1/16,1,1]],Stucki:[[8/42,1,0],[4/42,2,0],[2/42,-2,1],[4/42,-1,1],[8/42,0,1],[4/42,1,1],[2/42,2,1],[1/42,-2,2],[2/42,-1,2],[4/42,0,2],[2/42,1,2],[1/42,2,2]],Atkinson:[[1/8,1,0],[1/8,2,0],[1/8,-1,1],[1/8,0,1],[1/8,1,1],[1/8,0,2]]};if(!kernel||!kernels[kernel]){throw"Unknown dithering kernel: "+kernel}var ds=kernels[kernel];var index=0,height=this.height,width=this.width,data=this.pixels;var direction=serpentine?-1:1;this.indexedPixels=new Uint8Array(this.pixels.length/3);for(var y=0;y<height;y++){if(serpentine)direction=direction*-1;for(var x=direction==1?0:width-1,xend=direction==1?width:0;x!==xend;x+=direction){index=y*width+x;var idx=index*3;var r1=data[idx];var g1=data[idx+1];var b1=data[idx+2];idx=this.findClosestRGB(r1,g1,b1);this.usedEntry[idx]=true;this.indexedPixels[index]=idx;idx*=3;var r2=this.colorTab[idx];var g2=this.colorTab[idx+1];var b2=this.colorTab[idx+2];var er=r1-r2;var eg=g1-g2;var eb=b1-b2;for(var i=direction==1?0:ds.length-1,end=direction==1?ds.length:0;i!==end;i+=direction){var x1=ds[i][1];var y1=ds[i][2];if(x1+x>=0&&x1+x<width&&y1+y>=0&&y1+y<height){var d=ds[i][0];idx=index+x1+y1*width;idx*=3;data[idx]=Math.max(0,Math.min(255,data[idx]+er*d));data[idx+1]=Math.max(0,Math.min(255,data[idx+1]+eg*d));data[idx+2]=Math.max(0,Math.min(255,data[idx+2]+eb*d))}}}}};GIFEncoder.prototype.findClosest=function(c,used){return this.findClosestRGB((c&16711680)>>16,(c&65280)>>8,c&255,used)};GIFEncoder.prototype.findClosestRGB=function(r,g,b,used){if(this.colorTab===null)return-1;if(this.neuQuant&&!used){return this.neuQuant.lookupRGB(r,g,b)}var c=b|g<<8|r<<16;var minpos=0;var dmin=256*256*256;var len=this.colorTab.length;for(var i=0,index=0;i<len;index++){var dr=r-(this.colorTab[i++]&255);var dg=g-(this.colorTab[i++]&255);var db=b-(this.colorTab[i++]&255);var d=dr*dr+dg*dg+db*db;if((!used||this.usedEntry[index])&&d<dmin){dmin=d;minpos=index}}return minpos};GIFEncoder.prototype.getImagePixels=function(){var w=this.width;var h=this.height;this.pixels=new Uint8Array(w*h*3);var data=this.image;var srcPos=0;var count=0;for(var i=0;i<h;i++){for(var j=0;j<w;j++){this.pixels[count++]=data[srcPos++];this.pixels[count++]=data[srcPos++];this.pixels[count++]=data[srcPos++];srcPos++}}};GIFEncoder.prototype.writeGraphicCtrlExt=function(){this.out.writeByte(33);this.out.writeByte(249);this.out.writeByte(4);var transp,disp;if(this.transparent===null){transp=0;disp=0}else{transp=1;disp=2}if(this.dispose>=0){disp=dispose&7}disp<<=2;this.out.writeByte(0|disp|0|transp);this.writeShort(this.delay);this.out.writeByte(this.transIndex);this.out.writeByte(0)};GIFEncoder.prototype.writeImageDesc=function(){this.out.writeByte(44);this.writeShort(0);this.writeShort(0);this.writeShort(this.width);this.writeShort(this.height);if(this.firstFrame||this.globalPalette){this.out.writeByte(0)}else{this.out.writeByte(128|0|0|0|this.palSize)}};GIFEncoder.prototype.writeLSD=function(){this.writeShort(this.width);this.writeShort(this.height);this.out.writeByte(128|112|0|this.palSize);this.out.writeByte(0);this.out.writeByte(0)};GIFEncoder.prototype.writeNetscapeExt=function(){this.out.writeByte(33);this.out.writeByte(255);this.out.writeByte(11);this.out.writeUTFBytes("NETSCAPE2.0");this.out.writeByte(3);this.out.writeByte(1);this.writeShort(this.repeat);this.out.writeByte(0)};GIFEncoder.prototype.writePalette=function(){this.out.writeBytes(this.colorTab);var n=3*256-this.colorTab.length;for(var i=0;i<n;i++)this.out.writeByte(0)};GIFEncoder.prototype.writeShort=function(pValue){this.out.writeByte(pValue&255);this.out.writeByte(pValue>>8&255)};GIFEncoder.prototype.writePixels=function(){var enc=new LZWEncoder(this.width,this.height,this.indexedPixels,this.colorDepth);enc.encode(this.out)};GIFEncoder.prototype.stream=function(){return this.out};module.exports=GIFEncoder},{"./LZWEncoder.js":2,"./TypedNeuQuant.js":3}],2:[function(require,module,exports){var EOF=-1;var BITS=12;var HSIZE=5003;var masks=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function LZWEncoder(width,height,pixels,colorDepth){var initCodeSize=Math.max(2,colorDepth);var accum=new Uint8Array(256);var htab=new Int32Array(HSIZE);var codetab=new Int32Array(HSIZE);var cur_accum,cur_bits=0;var a_count;var free_ent=0;var maxcode;var clear_flg=false;var g_init_bits,ClearCode,EOFCode;function char_out(c,outs){accum[a_count++]=c;if(a_count>=254)flush_char(outs)}function cl_block(outs){cl_hash(HSIZE);free_ent=ClearCode+2;clear_flg=true;output(ClearCode,outs)}function cl_hash(hsize){for(var i=0;i<hsize;++i)htab[i]=-1}function compress(init_bits,outs){var fcode,c,i,ent,disp,hsize_reg,hshift;g_init_bits=init_bits;clear_flg=false;n_bits=g_init_bits;maxcode=MAXCODE(n_bits);ClearCode=1<<init_bits-1;EOFCode=ClearCode+1;free_ent=ClearCode+2;a_count=0;ent=nextPixel();hshift=0;for(fcode=HSIZE;fcode<65536;fcode*=2)++hshift;hshift=8-hshift;hsize_reg=HSIZE;cl_hash(hsize_reg);output(ClearCode,outs);outer_loop:while((c=nextPixel())!=EOF){fcode=(c<<BITS)+ent;i=c<<hshift^ent;if(htab[i]===fcode){ent=codetab[i];continue}else if(htab[i]>=0){disp=hsize_reg-i;if(i===0)disp=1;do{if((i-=disp)<0)i+=hsize_reg;if(htab[i]===fcode){ent=codetab[i];continue outer_loop}}while(htab[i]>=0)}output(ent,outs);ent=c;if(free_ent<1<<BITS){codetab[i]=free_ent++;htab[i]=fcode}else{cl_block(outs)}}output(ent,outs);output(EOFCode,outs)}function encode(outs){outs.writeByte(initCodeSize);remaining=width*height;curPixel=0;compress(initCodeSize+1,outs);outs.writeByte(0)}function flush_char(outs){if(a_count>0){outs.writeByte(a_count);outs.writeBytes(accum,0,a_count);a_count=0}}function MAXCODE(n_bits){return(1<<n_bits)-1}function nextPixel(){if(remaining===0)return EOF;--remaining;var pix=pixels[curPixel++];return pix&255}function output(code,outs){cur_accum&=masks[cur_bits];if(cur_bits>0)cur_accum|=code<<cur_bits;else cur_accum=code;cur_bits+=n_bits;while(cur_bits>=8){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}if(free_ent>maxcode||clear_flg){if(clear_flg){maxcode=MAXCODE(n_bits=g_init_bits);clear_flg=false}else{++n_bits;if(n_bits==BITS)maxcode=1<<BITS;else maxcode=MAXCODE(n_bits)}}if(code==EOFCode){while(cur_bits>0){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}flush_char(outs)}}this.encode=encode}module.exports=LZWEncoder},{}],3:[function(require,module,exports){var ncycles=100;var netsize=256;var maxnetpos=netsize-1;var netbiasshift=4;var intbiasshift=16;var intbias=1<<intbiasshift;var gammashift=10;var gamma=1<<gammashift;var betashift=10;var beta=intbias>>betashift;var betagamma=intbias<<gammashift-betashift;var initrad=netsize>>3;var radiusbiasshift=6;var radiusbias=1<<radiusbiasshift;var initradius=initrad*radiusbias;var radiusdec=30;var alphabiasshift=10;var initalpha=1<<alphabiasshift;var alphadec;var radbiasshift=8;var radbias=1<<radbiasshift;var alpharadbshift=alphabiasshift+radbiasshift;var alpharadbias=1<<alpharadbshift;var prime1=499;var prime2=491;var prime3=487;var prime4=503;var minpicturebytes=3*prime4;function NeuQuant(pixels,samplefac){var network;var netindex;var bias;var freq;var radpower;function init(){network=[];netindex=new Int32Array(256);bias=new Int32Array(netsize);freq=new Int32Array(netsize);radpower=new Int32Array(netsize>>3);var i,v;for(i=0;i<netsize;i++){v=(i<<netbiasshift+8)/netsize;network[i]=new Float64Array([v,v,v,0]);freq[i]=intbias/netsize;bias[i]=0}}function unbiasnet(){for(var i=0;i<netsize;i++){network[i][0]>>=netbiasshift;network[i][1]>>=netbiasshift;network[i][2]>>=netbiasshift;network[i][3]=i}}function altersingle(alpha,i,b,g,r){network[i][0]-=alpha*(network[i][0]-b)/initalpha;network[i][1]-=alpha*(network[i][1]-g)/initalpha;network[i][2]-=alpha*(network[i][2]-r)/initalpha}function alterneigh(radius,i,b,g,r){var lo=Math.abs(i-radius);var hi=Math.min(i+radius,netsize);var j=i+1;var k=i-1;var m=1;var p,a;while(j<hi||k>lo){a=radpower[m++];if(j<hi){p=network[j++];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}if(k>lo){p=network[k--];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}}}function contest(b,g,r){var bestd=~(1<<31);var bestbiasd=bestd;var bestpos=-1;var bestbiaspos=bestpos;var i,n,dist,biasdist,betafreq;for(i=0;i<netsize;i++){n=network[i];dist=Math.abs(n[0]-b)+Math.abs(n[1]-g)+Math.abs(n[2]-r);if(dist<bestd){bestd=dist;bestpos=i}biasdist=dist-(bias[i]>>intbiasshift-netbiasshift);if(biasdist<bestbiasd){bestbiasd=biasdist;bestbiaspos=i}betafreq=freq[i]>>betashift;freq[i]-=betafreq;bias[i]+=betafreq<<gammashift}freq[bestpos]+=beta;bias[bestpos]-=betagamma;return bestbiaspos}function inxbuild(){var i,j,p,q,smallpos,smallval,previouscol=0,startpos=0;for(i=0;i<netsize;i++){p=network[i];smallpos=i;smallval=p[1];for(j=i+1;j<netsize;j++){q=network[j];if(q[1]<smallval){smallpos=j;smallval=q[1]}}q=network[smallpos];if(i!=smallpos){j=q[0];q[0]=p[0];p[0]=j;j=q[1];q[1]=p[1];p[1]=j;j=q[2];q[2]=p[2];p[2]=j;j=q[3];q[3]=p[3];p[3]=j}if(smallval!=previouscol){netindex[previouscol]=startpos+i>>1;for(j=previouscol+1;j<smallval;j++)netindex[j]=i;previouscol=smallval;startpos=i}}netindex[previouscol]=startpos+maxnetpos>>1;for(j=previouscol+1;j<256;j++)netindex[j]=maxnetpos}function inxsearch(b,g,r){var a,p,dist;var bestd=1e3;var best=-1;var i=netindex[g];var j=i-1;while(i<netsize||j>=0){if(i<netsize){p=network[i];dist=p[1]-g;if(dist>=bestd)i=netsize;else{i++;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist<bestd){a=p[2]-r;if(a<0)a=-a;dist+=a;if(dist<bestd){bestd=dist;best=p[3]}}}}if(j>=0){p=network[j];dist=g-p[1];if(dist>=bestd)j=-1;else{j--;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist<bestd){a=p[2]-r;if(a<0)a=-a;dist+=a;if(dist<bestd){bestd=dist;best=p[3]}}}}}return best}function learn(){var i;var lengthcount=pixels.length;var alphadec=30+(samplefac-1)/3;var samplepixels=lengthcount/(3*samplefac);var delta=~~(samplepixels/ncycles);var alpha=initalpha;var radius=initradius;var rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(i=0;i<rad;i++)radpower[i]=alpha*((rad*rad-i*i)*radbias/(rad*rad));var step;if(lengthcount<minpicturebytes){samplefac=1;step=3}else if(lengthcount%prime1!==0){step=3*prime1}else if(lengthcount%prime2!==0){step=3*prime2}else if(lengthcount%prime3!==0){step=3*prime3}else{step=3*prime4}var b,g,r,j;var pix=0;i=0;while(i<samplepixels){b=(pixels[pix]&255)<<netbiasshift;g=(pixels[pix+1]&255)<<netbiasshift;r=(pixels[pix+2]&255)<<netbiasshift;j=contest(b,g,r);altersingle(alpha,j,b,g,r);if(rad!==0)alterneigh(rad,j,b,g,r);pix+=step;if(pix>=lengthcount)pix-=lengthcount;i++;if(delta===0)delta=1;if(i%delta===0){alpha-=alpha/alphadec;radius-=radius/radiusdec;rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(j=0;j<rad;j++)radpower[j]=alpha*((rad*rad-j*j)*radbias/(rad*rad))}}}function buildColormap(){init();learn();unbiasnet();inxbuild()}this.buildColormap=buildColormap;function getColormap(){var map=[];var index=[];for(var i=0;i<netsize;i++)index[network[i][3]]=i;var k=0;for(var l=0;l<netsize;l++){var j=index[l];map[k++]=network[j][0];map[k++]=network[j][1];map[k++]=network[j][2]}return map}this.getColormap=getColormap;this.lookupRGB=inxsearch}module.exports=NeuQuant},{}],4:[function(require,module,exports){var GIFEncoder,renderFrame;GIFEncoder=require("./GIFEncoder.js");renderFrame=function(frame){var encoder,page,stream,transfer;encoder=new GIFEncoder(frame.width,frame.height);if(frame.index===0){encoder.writeHeader()}else{encoder.firstFrame=false}encoder.setTransparent(frame.transparent);encoder.setRepeat(frame.repeat);encoder.setDelay(frame.delay);encoder.setQuality(frame.quality);encoder.setDither(frame.dither);encoder.setGlobalPalette(frame.globalPalette);encoder.addFrame(frame.data);if(frame.last){encoder.finish()}if(frame.globalPalette===true){frame.globalPalette=encoder.getGlobalPalette()}stream=encoder.stream();frame.data=stream.pages;frame.cursor=stream.cursor;frame.pageSize=stream.constructor.pageSize;if(frame.canTransfer){transfer=function(){var i,len,ref,results;ref=frame.data;results=[];for(i=0,len=ref.length;i<len;i++){page=ref[i];results.push(page.buffer)}return results}();return self.postMessage(frame,transfer)}else{return self.postMessage(frame)}};self.onmessage=function(event){return renderFrame(event.data)}},{"./GIFEncoder.js":1}]},{},[4]);
+//# sourceMappingURL=gif.worker.js.map
diff --git a/src/manifest.json b/src/manifest.json
index 8226816..549f00c 100755
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -3,7 +3,7 @@
"name": "__MSG_extName__",
"description": "__MSG_extDesc__",
"default_locale": "en",
- "version": "4.0.5",
+ "version": "4.1.0",
"background": {
"service_worker": "background.bundle.js"
},
@@ -41,7 +41,8 @@
"region.html",
"waveform.html",
"playground.html",
- "editorfallback.html",
+ "editorwebcodecs.html",
+ "editorviewer.html",
"download.html",
"*"
],
diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.js
index 6d44d8c..38e7e18 100644
--- a/src/pages/Background/messaging/handlers.js
+++ b/src/pages/Background/messaging/handlers.js
@@ -94,8 +94,8 @@ export const setupHandlers = () => {
registerMessage("start-recording", (message) => startRecording(message));
registerMessage("restarted", (message) => restartActiveTab(message));
- registerMessage("new-chunk", (message) => {
- newChunk(message);
+ registerMessage("new-chunk", (message, sender, sendResponse) => {
+ newChunk(message, sendResponse);
return true;
});
@@ -104,9 +104,11 @@ export const setupHandlers = () => {
async (message, sender) => await handleGetStreamingData(message, sender)
);
registerMessage("cancel-recording", (message) => cancelRecording(message));
- registerMessage("stop-recording-tab", (message) =>
- handleStopRecordingTab(message)
- );
+ registerMessage("stop-recording-tab", (message, sendResponse) => {
+ handleStopRecordingTab(message);
+ sendResponse({ ok: true });
+ return true;
+ });
registerMessage("restart-recording-tab", (message) =>
handleRestartRecordingTab(message)
);
@@ -214,10 +216,11 @@ export const setupHandlers = () => {
);
registerMessage("get-platform-info", async () => await getPlatformInfo());
registerMessage("restore-recording", (message) => restoreRecording(message));
- registerMessage(
- "check-restore",
- async (sendResponse) => await checkRestore(sendResponse)
- );
+ registerMessage("check-restore", async (message, sender, sendResponse) => {
+ const response = await checkRestore();
+ sendResponse(response);
+ return true;
+ });
registerMessage(
"check-capture-permissions",
async (message, sender, sendResponse) => {
@@ -892,4 +895,20 @@ export const setupHandlers = () => {
return { success: false, message: "Cloud features disabled" };
return await loginWithWebsite();
});
+ registerMessage("sync-recording-state", async (message, sendResponse) => {
+ const { recording, paused, recordingStartTime, pendingRecording } =
+ await chrome.storage.local.get([
+ "recording",
+ "paused",
+ "recordingStartTime",
+ "pendingRecording",
+ ]);
+ sendResponse({
+ recording: Boolean(recording),
+ paused: Boolean(paused),
+ recordingStartTime: recordingStartTime || null,
+ pendingRecording: Boolean(pendingRecording),
+ });
+ return true;
+ });
};
diff --git a/src/pages/Background/recording/chunkHandler.js b/src/pages/Background/recording/chunkHandler.js
index 4b39a9e..111cdbb 100644
--- a/src/pages/Background/recording/chunkHandler.js
+++ b/src/pages/Background/recording/chunkHandler.js
@@ -8,16 +8,17 @@ localforage.config({
version: 1,
});
-export const chunksStore = localforage.createInstance({
- name: "chunks",
-});
-
+export const chunksStore = localforage.createInstance({ name: "chunks" });
export const localDirectoryStore = localforage.createInstance({
name: "localDirectory",
});
export const clearAllRecordings = async () => {
- chunksStore.clear();
+ try {
+ await chunksStore.clear();
+ } catch (err) {
+ console.error("Failed to clear chunksStore", err);
+ }
};
export const handleChunks = async (chunks, override = false) => {
@@ -28,92 +29,98 @@ export const handleChunks = async (chunks, override = false) => {
"bannerSupport",
]);
- if (sendingChunks) {
- console.warn("Chunks are already being sent, skipping...");
- return;
- }
+ if (sendingChunks) return;
await chrome.storage.local.set({ sendingChunks: true });
- if (chunks.length === 0) {
- await chrome.storage.local.set({ sendingChunks: false });
- sendMessageTab(sandboxTab, { type: "make-video-tab", override });
- return;
- }
+ try {
+ if (chunks.length === 0) {
+ sendMessageTab(sandboxTab, { type: "make-video-tab", override });
+ return;
+ }
- chunks.sort((a, b) => a.timestamp - b.timestamp);
+ chunks.sort((a, b) => {
+ if (a.index == null) return -1;
+ if (b.index == null) return 1;
+ return a.index - b.index;
+ });
- const batchSize = 10;
- const maxRetries = 3;
- const retryDelay = 1000;
- const chunksCount = chunks.length;
- let currentIndex = 0;
+ const batchSize = 10;
+ const maxRetries = 3;
+ const retryDelay = 1000;
- sendMessageTab(sandboxTab, {
- type: "chunk-count",
- count: chunksCount,
- override,
- });
+ sendMessageTab(sandboxTab, {
+ type: "chunk-count",
+ count: chunks.length,
+ override,
+ });
- if (bannerSupport) {
- sendMessageTab(sandboxTab, { type: "banner-support" });
- }
+ if (bannerSupport) {
+ sendMessageTab(sandboxTab, { type: "banner-support" });
+ }
- const sendBatch = async (batch, retryCount = 0) => {
- try {
- const response = await sendMessageTab(sandboxTab, {
- type: "new-chunk-tab",
- chunks: batch,
- });
+ const delay = (ms) => new Promise((res) => setTimeout(res, ms));
- if (!response) {
- throw new Error("No response or failed response from tab.");
+ const sendBatch = async (batch) => {
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
+ try {
+ const response = await sendMessageTab(sandboxTab, {
+ type: "new-chunk-tab",
+ chunks: batch,
+ });
+ if (response) return true;
+ } catch (err) {}
+ await delay(retryDelay);
}
- } catch (error) {
- if (retryCount < maxRetries) {
- console.error(
- `Sending batch failed, retrying... Attempt ${retryCount + 1}`,
- error
- );
- setTimeout(() => sendBatch(batch, retryCount + 1), retryDelay);
- } else {
- console.error("Maximum retry attempts reached for this batch.", error);
+ return false;
+ };
+
+ let currentIndex = 0;
+
+ while (currentIndex < chunks.length) {
+ const end = Math.min(currentIndex + batchSize, chunks.length);
+ const rawBatch = chunks.slice(currentIndex, end);
+
+ const batch = await Promise.all(
+ rawBatch.map(async (chunk) => {
+ try {
+ const base64 = await blobToBase64(chunk.chunk);
+ return { chunk: base64, index: chunk.index };
+ } catch {
+ return null;
+ }
+ })
+ );
+
+ const filtered = batch.filter(Boolean);
+ if (filtered.length > 0) {
+ const ok = await sendBatch(filtered);
+ if (!ok) return;
}
- }
- };
- while (currentIndex < chunksCount) {
- const end = Math.min(currentIndex + batchSize, chunksCount);
- const batch = await Promise.all(
- chunks.slice(currentIndex, end).map(async (chunk, index) => {
- try {
- const base64 = await blobToBase64(chunk.chunk);
- return { chunk: base64, index: currentIndex + index };
- } catch (error) {
- console.error("Error converting chunk to Base64", error);
- return null;
- }
- })
- );
-
- const filteredBatch = batch.filter((chunk) => chunk !== null);
- if (filteredBatch.length > 0) {
- await sendBatch(filteredBatch);
+ currentIndex += batchSize;
}
- currentIndex += batchSize;
- }
- await chrome.storage.local.set({ sendingChunks: false });
- sendMessageTab(sandboxTab, { type: "make-video-tab", override });
+ sendMessageTab(sandboxTab, { type: "make-video-tab", override });
+ } finally {
+ await chrome.storage.local.set({ sendingChunks: false });
+ }
};
-export const newChunk = async (request) => {
- const { sandboxTab } = await chrome.storage.local.get(["sandboxTab"]);
- sendMessageTab(sandboxTab, {
- type: "new-chunk-tab",
- chunk: request.chunk,
- index: request.index,
- });
+export const newChunk = async (request, sender, sendResponse) => {
+ try {
+ const { sandboxTab } = await chrome.storage.local.get(["sandboxTab"]);
+
+ await sendMessageTab(sandboxTab, {
+ type: "new-chunk-tab",
+ chunk: request.chunk,
+ index: request.index,
+ });
+
+ sendResponse({ status: "ok" });
+ } catch (err) {
+ sendResponse({ status: "error", error: err.message });
+ }
- sendResponse({ status: "ok" });
+ return true;
};
diff --git a/src/pages/Background/recording/restartRecording.js b/src/pages/Background/recording/restartRecording.js
index eff6765..317fcff 100644
--- a/src/pages/Background/recording/restartRecording.js
+++ b/src/pages/Background/recording/restartRecording.js
@@ -9,20 +9,5 @@ export const handleRestart = async () => {
};
export const handleRestartRecordingTab = async (request) => {
- // Check if Chrome version is 109 or below
- if (navigator.userAgent.includes("Chrome/")) {
- const version = parseInt(navigator.userAgent.match(/Chrome\/([0-9]+)/)[1]);
- if (version <= 109) {
- editor_url = "editorfallback.html";
- }
- }
-
- // Check if recording tab is open
- // FLAG: Not sure why we need to close the tab here?
- // const { recordingTab } = await chrome.storage.local.get(["recordingTab"]);
- // if (recordingTab) {
- // removeTab(recordingTab);
- // }
-
sendMessageRecord({ type: "restart-recording-tab" });
};
diff --git a/src/pages/Background/recording/restoreRecording.js b/src/pages/Background/recording/restoreRecording.js
index 6ff798c..a6bd337 100644
--- a/src/pages/Background/recording/restoreRecording.js
+++ b/src/pages/Background/recording/restoreRecording.js
@@ -1,39 +1,40 @@
import { sendMessageTab } from "../tabManagement";
import { chunksStore } from "./chunkHandler";
-import { sendChunks } from "./sendChunks";
+import { supportsWebCodecs } from "../utils/featureDetection";
-export const checkRestore = async (sendResponse) => {
+export const checkRestore = async () => {
const chunks = [];
await chunksStore.iterate((value, key) => {
chunks.push(value);
});
if (chunks.length === 0) {
- sendResponse({ restore: false, chunks: [] });
- return;
+ return { restore: false, chunks: [] };
}
- sendResponse({ restore: true });
+ return { restore: true };
};
export const restoreRecording = async () => {
- let editorUrl = "editorfallback.html";
+ const hasWebCodecs = supportsWebCodecs();
- // Check if Chrome version is 109 or below
- if (navigator.userAgent.includes("Chrome/")) {
- const version = parseInt(navigator.userAgent.match(/Chrome\/([0-9]+)/)[1]);
- if (version > 109) {
- editorUrl = "editor.html";
- }
+ let editorUrl, messageType;
+
+ if (hasWebCodecs) {
+ editorUrl = "editorwebcodecs.html";
+ messageType = "restore-recording";
+ } else {
+ editorUrl = "editorviewer.html";
+ messageType = "viewer-recording";
}
- // Retrieve stored chunks
const chunks = [];
await chunksStore.iterate((value) => {
chunks.push(value);
});
- // If there are no chunks, return early
- if (chunks.length === 0) return;
+ if (chunks.length === 0) {
+ return;
+ }
// Create the editor tab
chrome.tabs.create(
@@ -49,13 +50,14 @@ export const restoreRecording = async () => {
await new Promise((resolve) => {
chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
if (info.status === "complete" && tabId === tab.id) {
- sendMessageTab(tab.id, {
- type: "restore-recording",
- });
+ chrome.tabs.onUpdated.removeListener(listener);
- // Send stored chunks
- sendChunks();
- resolve();
+ setTimeout(() => {
+ sendMessageTab(tab.id, {
+ type: messageType,
+ });
+ resolve();
+ }, 2000);
}
});
});
diff --git a/src/pages/Background/recording/stopRecording.js b/src/pages/Background/recording/stopRecording.js
index 7e11931..1939146 100644
--- a/src/pages/Background/recording/stopRecording.js
+++ b/src/pages/Background/recording/stopRecording.js
@@ -3,6 +3,7 @@ import { discardOffscreenDocuments } from "../offscreen/discardOffscreenDocument
import { sendMessageRecord } from "./sendMessageRecord";
import { sendChunks } from "./sendChunks";
import { waitForContentScript } from "../utils/waitForContentScript";
+import { supportsWebCodecs } from "../utils/featureDetection";
export const stopRecording = async () => {
chrome.action.setIcon({ path: "assets/icon-34.png" });
@@ -27,12 +28,43 @@ export const stopRecording = async () => {
chrome.storage.local.set({ recordingStartTime: 0 });
+ // Check if browser supports WebCodecs for Mediabunny
+ const hasWebCodecs = supportsWebCodecs();
+
if (isSubscribed) {
chrome.alarms.clear("recording-alarm");
discardOffscreenDocuments();
+ } else if (hasWebCodecs) {
+ // Use Mediabunny (editorwebcodecs.html) when WebCodecs is supported
+ chrome.tabs.create({ url: "editorwebcodecs.html", active: true }, (tab) => {
+ chrome.tabs.onUpdated.addListener(function _(
+ tabId,
+ changeInfo,
+ updatedTab
+ ) {
+ if (tabId === tab.id && changeInfo.status === "complete") {
+ chrome.tabs.onUpdated.removeListener(_);
+ chrome.storage.local.set({ sandboxTab: tab.id });
+ waitForContentScript(tab.id)
+ .then(() => {
+ // Use fallback-recording for WebCodecs flow
+ sendMessageTab(tab.id, { type: "fallback-recording" });
+ })
+ .catch((err) => {
+ console.error(
+ "❌ Failed to wait for content script:",
+ err.message
+ );
+ });
+ }
+ });
+ });
+
+ chrome.runtime.sendMessage({ type: "turn-off-pip" });
} else if (duration > maxDuration) {
- // Open fallback editor
- chrome.tabs.create({ url: "editorfallback.html", active: true }, (tab) => {
+ // Fallback for large recordings without WebCodecs - use viewer mode
+
+ chrome.tabs.create({ url: "editorviewer.html", active: true }, (tab) => {
chrome.tabs.onUpdated.addListener(function _(
tabId,
changeInfo,
@@ -43,7 +75,7 @@ export const stopRecording = async () => {
chrome.storage.local.set({ sandboxTab: tab.id });
waitForContentScript(tab.id)
.then(() => {
- sendMessageTab(tab.id, { type: "large-recording" });
+ sendMessageTab(tab.id, { type: "viewer-recording" });
})
.catch((err) => {
console.error(
@@ -57,7 +89,7 @@ export const stopRecording = async () => {
chrome.runtime.sendMessage({ type: "turn-off-pip" });
} else {
- // Open normal editor
+ // Use FFmpeg (editor.html) for browsers without WebCodecs
chrome.tabs.create({ url: "editor.html", active: true }, (tab) => {
chrome.tabs.onUpdated.addListener(function _(
tabId,
diff --git a/src/pages/Background/utils/featureDetection.js b/src/pages/Background/utils/featureDetection.js
new file mode 100644
index 0000000..2e01850
--- /dev/null
+++ b/src/pages/Background/utils/featureDetection.js
@@ -0,0 +1,73 @@
+export const supportsWebCodecsUA = () => {
+ try {
+ const ua = navigator.userAgent;
+ const chromeMatch = ua.match(/Chrom(?:e|ium|iumWebview)\/([0-9]+)/);
+ if (chromeMatch) return parseInt(chromeMatch[1], 10) >= 94;
+
+ const safariMatch = ua.match(/Version\/([0-9]+\.[0-9]+).*Safari/);
+ if (safariMatch && !chromeMatch) return parseFloat(safariMatch[1]) >= 16.4;
+
+ const operaMatch = ua.match(/OPR\/([0-9]+)/);
+ if (operaMatch) return parseInt(operaMatch[1], 10) >= 80;
+
+ const edgeMatch = ua.match(/Edg\/([0-9]+)/);
+ if (edgeMatch) return parseInt(edgeMatch[1], 10) >= 94;
+
+ return false;
+ } catch {
+ return false;
+ }
+};
+
+export const getBrowserCapabilities = () => {
+ const ua = navigator.userAgent;
+ let browserName = "Unknown";
+ let browserVersion = "Unknown";
+
+ const chromeMatch = ua.match(/Chrom(?:e|ium)\/([0-9]+)/);
+ if (chromeMatch) {
+ browserName = "Chrome";
+ browserVersion = chromeMatch[1];
+ }
+
+ const safariMatch = ua.match(/Version\/([0-9]+\.[0-9]+).*Safari/);
+ if (safariMatch && !chromeMatch) {
+ browserName = "Safari";
+ browserVersion = safariMatch[1];
+ }
+
+ const firefoxMatch = ua.match(/Firefox\/([0-9]+)/);
+ if (firefoxMatch) {
+ browserName = "Firefox";
+ browserVersion = firefoxMatch[1];
+ }
+
+ const operaMatch = ua.match(/OPR\/([0-9]+)/);
+ if (operaMatch) {
+ browserName = "Opera";
+ browserVersion = operaMatch[1];
+ }
+
+ const edgeMatch = ua.match(/Edg\/([0-9]+)/);
+ if (edgeMatch) {
+ browserName = "Edge";
+ browserVersion = edgeMatch[1];
+ }
+
+ return {
+ webCodecsUA: supportsWebCodecsUA(),
+ browser: browserName,
+ version: browserVersion,
+ userAgent: ua,
+ };
+};
+
+export const supportsWebCodecs = async () => {
+ const { realWebCodecsSupport } = await chrome.storage.local.get(
+ "realWebCodecsSupport"
+ );
+
+ if (realWebCodecsSupport === true) return true;
+
+ return supportsWebCodecsUA();
+};
diff --git a/src/pages/Camera/messaging/handlers.js b/src/pages/Camera/messaging/handlers.js
index 075b9e2..799e157 100644
--- a/src/pages/Camera/messaging/handlers.js
+++ b/src/pages/Camera/messaging/handlers.js
@@ -77,7 +77,7 @@ export const setupHandlers = ({ setLoading }) => {
console.log("Preparing Picture in Picture request");
waitForVideoRef((videoEl) => {
- surfaceHandler(message, { current: videoEl }); // ✅ FIXED
+ surfaceHandler(message, { current: videoEl });
});
});
registerMessage("camera-toggled-toolbar", cameraToggledToolbar);
diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsx
index 3e18850..448e4e5 100644
--- a/src/pages/CloudRecorder/CloudRecorder.jsx
+++ b/src/pages/CloudRecorder/CloudRecorder.jsx
@@ -307,6 +307,18 @@ const CloudRecorder = () => {
const restartRecording = async () => {
isRestarting.current = true;
await dismissRecording(true);
+ await stopAllRecorders();
+ screenChunks.current = [];
+ cameraChunks.current = [];
+ audioChunks.current = [];
+ index.current = 0;
+ lastTimecode.current = 0;
+
+ if (IS_IFRAME_CONTEXT && !target.current) {
+ sendRecordingError("No crop target for restart.");
+ return;
+ }
+
uploadersInitialized.current = await initializeUploaders();
if (!uploadersInitialized.current) {
sendRecordingError("Failed to re-initialize uploaders on restart.");
@@ -352,6 +364,9 @@ const CloudRecorder = () => {
if (cameraStream.current) {
cameraUploader.current = new BunnyTusUploader();
const track = cameraStream.current.getVideoTracks()[0];
+ if (track?.readyState === "ended") {
+ throw new Error("Camera track has ended");
+ }
const { width, height } = track.getSettings();
await cameraUploader.current.initialize(projectId, {
title: "Camera Recording",
@@ -489,6 +504,11 @@ const CloudRecorder = () => {
if (uploadersInitialized.current && screenUploader.current) {
try {
if (screenUploader.current?.isPaused) return;
+ if (screenUploader.current.queuedBytes > 15 * 1024 * 1024) {
+ await screenUploader.current
+ .waitForPendingUploads?.()
+ .catch(() => {});
+ }
await screenUploader.current.write(blob);
consecutiveScreenFailures.current = 0; // Reset on success
} catch (uploadErr) {
@@ -799,6 +819,24 @@ const CloudRecorder = () => {
}
};
+ useEffect(() => {
+ const onHide = () => {
+ // Only finalize if an active recording really exists
+ const hasActiveRecorder =
+ screenRecorder.current?.state === "recording" ||
+ cameraRecorder.current?.state === "recording" ||
+ audioRecorder.current?.state === "recording";
+
+ if (hasActiveRecorder && !sentLast.current) {
+ console.warn("⚠️ Recorder page hiding — finalizing");
+ stopRecording(true);
+ }
+ };
+
+ window.addEventListener("pagehide", onHide);
+ return () => window.removeEventListener("pagehide", onHide);
+ }, []);
+
const createSceneOrHandleMultiMode = async (
uploadMeta,
durations,
diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.js
index aab2221..8fae54b 100644
--- a/src/pages/CloudRecorder/bunnyTusUploader.js
+++ b/src/pages/CloudRecorder/bunnyTusUploader.js
@@ -10,9 +10,26 @@ export async function getThumbnailFromBlob(blob, seekTo = 0.1) {
const url = URL.createObjectURL(blob);
video.src = url;
+ let timeoutId = setTimeout(() => {
+ URL.revokeObjectURL(url);
+ reject(new Error("Thumbnail timed out"));
+ }, 2000);
+
+ const cleanup = () => {
+ clearTimeout(timeoutId);
+ URL.revokeObjectURL(url);
+ };
+
+ video.onerror = () => {
+ cleanup();
+ reject(new Error("Failed to load video for thumbnail"));
+ };
+
video.onloadedmetadata = () => {
+ if (video.duration === Infinity) {
+ video.currentTime = 0;
+ }
const targetTime = Math.min(seekTo, video.duration - 0.01);
-
video.currentTime = targetTime;
};
@@ -26,22 +43,14 @@ export async function getThumbnailFromBlob(blob, seekTo = 0.1) {
canvas.toBlob(
(thumbnailBlob) => {
- URL.revokeObjectURL(url);
- if (thumbnailBlob) {
- resolve(thumbnailBlob);
- } else {
- reject(new Error("Failed to create thumbnail blob"));
- }
+ cleanup();
+ if (thumbnailBlob) resolve(thumbnailBlob);
+ else reject(new Error("Failed to create thumbnail blob"));
},
"image/jpeg",
0.8
);
};
-
- video.onerror = (err) => {
- URL.revokeObjectURL(url);
- reject(new Error("Failed to load video for thumbnail"));
- };
});
}
@@ -233,8 +242,8 @@ export default class BunnyTusUploader {
}
// Wait for current queue to finish processing these chunks
- if (this.queueProcessingPromise) {
- await this.queueProcessingPromise;
+ if (this.queuedBytes > 10 * 1024 * 1024) {
+ await this.waitForPendingUploads();
}
if (!this._hasExtractedMeta && chunk.size > 128 * 1024) {
@@ -242,7 +251,17 @@ export default class BunnyTusUploader {
const blob = new Blob([chunk], { type: "video/webm" });
if (this.metadata.type === "screen") {
- this.metaThumbnail = await getThumbnailFromBlob(blob);
+ const thumbPromise = getThumbnailFromBlob(blob);
+
+ // Add timeout safety
+ const safeThumbnail = await Promise.race([
+ thumbPromise,
+ new Promise((_, reject) =>
+ setTimeout(() => reject("thumbnail-timeout"), 1500)
+ ),
+ ]);
+
+ this.metaThumbnail = safeThumbnail;
}
this._hasExtractedMeta = true;
@@ -257,16 +276,21 @@ export default class BunnyTusUploader {
const now = Math.floor(Date.now() / 1000);
if (this.expires - now < this.TOKEN_REFRESH_THRESHOLD) {
await this.refreshTusAuth();
+
+ if (this.isProcessingQueue) {
+ this.pause();
+ this.resume();
+ }
}
}
-
async uploadChunk(chunk) {
+ if (this.isFinalizing) return;
const data = new Uint8Array(await chunk.arrayBuffer());
for (let attempt = 0; attempt <= this.MAX_RETRIES; attempt++) {
try {
- // Use current offset atomically to prevent race conditions
const currentOffset = this.offset;
+ this.offset += data.length;
const res = await fetch(this.uploadUrl, {
method: "PATCH",
@@ -331,9 +355,7 @@ export default class BunnyTusUploader {
const serverOffset = parseInt(
headRes.headers.get("Upload-Offset") || "0"
);
- console.log(
- `📊 Server offset: ${serverOffset}, Local offset was: ${this.offset}`
- );
+
this.offset = serverOffset;
// Retry with corrected offset
diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsx
index 2afb205..5294722 100644
--- a/src/pages/Content/context/ContentState.jsx
+++ b/src/pages/Content/context/ContentState.jsx
@@ -106,7 +106,7 @@ const ContentState = (props) => {
// This cannot be triggered from here because the user might not have the page focused
//chrome.runtime.sendMessage({ type: "start-recording" });
- }, [contentStateRef.current]);
+ }, []);
const restartRecording = useCallback(() => {
chrome.storage.local.set({ recording: false, restarting: true });
@@ -137,7 +137,26 @@ const ContentState = (props) => {
paused: false,
}));
}, 100);
- }, [contentStateRef.current]);
+ }, []);
+
+ useEffect(() => {
+ (async () => {
+ let realSupport = false;
+
+ if ("VideoEncoder" in window) {
+ try {
+ const support = await VideoEncoder.isConfigSupported({
+ codec: "vp8",
+ width: 16,
+ height: 16,
+ });
+ realSupport = support.supported;
+ } catch {}
+ }
+
+ chrome.storage.local.set({ realWebCodecsSupport: realSupport });
+ })();
+ }, []);
const stopRecording = useCallback(() => {
chrome.runtime.sendMessage({ type: "clear-recording-alarm" });
@@ -166,7 +185,14 @@ const ContentState = (props) => {
element.classList.remove("screenity-blur");
});
setTimer(0);
- chrome.runtime.sendMessage({ type: "stop-recording-tab" });
+ chrome.runtime.sendMessage({ type: "stop-recording-tab" }, (res) => {
+ if (!res || res.ok !== true) {
+ console.warn("Stop command not acknowledged, retrying…");
+ setTimeout(() => {
+ chrome.runtime.sendMessage({ type: "stop-recording-tab" });
+ }, 200);
+ }
+ });
// Play beep sound at 50% volume
const audio = new Audio(chrome.runtime.getURL("/assets/sounds/beep.mp3"));
audio.volume = 0.5;
@@ -839,6 +865,13 @@ const ContentState = (props) => {
audio.play();
};
+ useEffect(() => {
+ chrome.runtime.sendMessage({ type: "sync-recording-state" }, (state) => {
+ if (!state) return;
+ setContentState((prev) => ({ ...prev, ...state }));
+ });
+ }, []);
+
useEffect(() => {
if (!CLOUD_FEATURES_ENABLED) return;
if (!contentState.isLoggedIn || !contentState.isSubscribed) return;
diff --git a/src/pages/Content/context/messaging/handlers.js b/src/pages/Content/context/messaging/handlers.js
index a76bc45..e26170b 100644
--- a/src/pages/Content/context/messaging/handlers.js
+++ b/src/pages/Content/context/messaging/handlers.js
@@ -12,9 +12,14 @@ import { checkAuthStatus } from "../utils/checkAuthStatus";
const CLOUD_FEATURES_ENABLED =
process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";
+const getState = () => contentStateRef.current;
+
export const setupHandlers = () => {
// Initialize message router
- messageRouter();
+ if (!window.__screenityHandlersInitialized) {
+ messageRouter();
+ window.__screenityHandlersInitialized = true;
+ }
// Register content message handlers
registerMessage("time", (message) => {
@@ -45,7 +50,9 @@ export const setupHandlers = () => {
pendingRecording: true,
}));
- if (contentStateRef.current.countdown) {
+ const state = getState();
+
+ if (state.countdown) {
// Start countdown
setContentState((prev) => ({
...prev,
@@ -55,14 +62,15 @@ export const setupHandlers = () => {
}));
} else {
// Start recording immediately if countdown is disabled
- if (!contentStateRef.current.countdownCancelled) {
- contentStateRef.current.startRecordingAfterCountdown();
+ if (!state.countdownCancelled) {
+ state.startRecordingAfterCountdown();
}
}
});
registerMessage("stop-recording-tab", () => {
- if (!contentStateRef.current.recording) return;
+ const state = getState();
+ if (!state.recording) return;
chrome.storage.local.set({ recording: false });
setContentState((prev) => ({
@@ -75,10 +83,11 @@ export const setupHandlers = () => {
});
registerMessage("recording-ended", () => {
+ const state = getState();
if (
- !contentStateRef.current.showPopup
+ !state.showPopup
// &&
- // !contentStateRef.current.pendingRecording
+ // !state.pendingRecording
) {
setContentState((prev) => ({
...prev,
@@ -100,7 +109,15 @@ export const setupHandlers = () => {
});
registerMessage("start-stream", () => {
- if (contentStateRef.current.recording) return;
+ const state = getState();
+ if (
+ state.preparingRecording ||
+ state.pendingRecording ||
+ state.recording ||
+ state.pipEnded
+ ) {
+ return;
+ }
setContentState((prev) => ({
...prev,
@@ -108,13 +125,10 @@ export const setupHandlers = () => {
showPopup: true,
}));
- if (contentStateRef.current.recordingType !== "camera") {
- contentStateRef.current.startStreaming();
- } else if (
- contentStateRef.current.defaultVideoInput !== "none" &&
- contentStateRef.current.cameraActive
- ) {
- contentStateRef.current.startStreaming();
+ if (state.recordingType !== "camera") {
+ state.startStreaming();
+ } else if (state.defaultVideoInput !== "none" && state.cameraActive) {
+ state.startStreaming();
}
});
@@ -136,14 +150,16 @@ export const setupHandlers = () => {
});
registerMessage("cancel-recording", () => {
- contentStateRef.current.dismissRecording();
+ const state = getState();
+ state.dismissRecording();
});
registerMessage("pause-recording", () => {
- if (contentStateRef.current.paused) {
- contentStateRef.current.resumeRecording();
+ const state = getState();
+ if (state.paused) {
+ state.resumeRecording();
} else {
- contentStateRef.current.pauseRecording();
+ state.pauseRecording();
}
});
@@ -155,10 +171,8 @@ export const setupHandlers = () => {
});
registerMessage("pip-ended", () => {
- if (
- contentStateRef.current.recording ||
- contentStateRef.current.pendingRecording
- ) {
+ const state = getState();
+ if (state.recording || state.pendingRecording) {
setContentState((prev) => ({
...prev,
pipEnded: true,
@@ -167,10 +181,8 @@ export const setupHandlers = () => {
});
registerMessage("pip-started", () => {
- if (
- contentStateRef.current.recording ||
- contentStateRef.current.pendingRecording
- ) {
+ const state = getState();
+ if (state.recording || state.pendingRecording) {
setContentState((prev) => ({
...prev,
pipEnded: false,
@@ -194,31 +206,33 @@ export const setupHandlers = () => {
});
registerMessage("stream-error", () => {
- contentStateRef.current.openModal(
+ const state = getState();
+ state.openModal(
chrome.i18n.getMessage("streamErrorModalTitle"),
chrome.i18n.getMessage("streamErrorModalDescription"),
chrome.i18n.getMessage("permissionsModalDismiss"),
null,
() => {
- contentStateRef.current.dismissRecording();
+ state.dismissRecording();
},
() => {
- contentStateRef.current.dismissRecording();
+ state.dismissRecording();
}
);
});
registerMessage("backup-error", () => {
- contentStateRef.current.openModal(
+ const state = getState();
+ state.openModal(
chrome.i18n.getMessage("backupPermissionFailTitle"),
chrome.i18n.getMessage("backupPermissionFailDescription"),
chrome.i18n.getMessage("permissionsModalDismiss"),
null,
() => {
- contentStateRef.current.dismissRecording();
+ state.dismissRecording();
},
() => {
- contentStateRef.current.dismissRecording();
+ state.dismissRecording();
}
);
});
@@ -231,11 +245,10 @@ export const setupHandlers = () => {
setTimer(time);
}
+ const state = getState();
+
if (!message.force) {
- if (
- !contentStateRef.current.showExtension &&
- !contentStateRef.current.recording
- ) {
+ if (!state.showExtension && !state.recording) {
updateFromStorage(true, sender.id);
}
} else {
@@ -265,11 +278,9 @@ export const setupHandlers = () => {
updateFromStorage(false, message.senderId);
setTimeout(() => {
- if (contentStateRef.current.openToast) {
- contentStateRef.current.openToast(
- chrome.i18n.getMessage("addedToMultiToast"),
- () => {}
- );
+ const state = getState();
+ if (state.openToast) {
+ state.openToast(chrome.i18n.getMessage("addedToMultiToast"), () => {});
}
}, 1000);
});
@@ -288,41 +299,51 @@ export const setupHandlers = () => {
updateFromStorage(false, message.senderId);
setTimeout(() => {
- contentStateRef.current.openToast(
- chrome.i18n.getMessage("readyRecordSceneToast"),
- () => {}
- );
+ const state = getState();
+ if (state.openToast) {
+ state.openToast(
+ chrome.i18n.getMessage("readyRecordSceneToast"),
+ () => {}
+ );
+ }
}, 1000);
});
registerMessage("time-warning", () => {
// Only trigger when actively recording
- if (contentStateRef.current.recording && !contentStateRef.current.paused) {
+ const state = getState();
+
+ if (state.recording && !state.paused) {
setContentState((prev) => ({
...prev,
timeWarning: true,
}));
- contentStateRef.current.openToast(
- chrome.i18n.getMessage("reachingRecordingLimitToast"),
- () => {},
- 5000
- );
+ if (state.openToast) {
+ state.openToast(
+ chrome.i18n.getMessage("reachingRecordingLimitToast"),
+ () => {},
+ 5000
+ );
+ }
}
});
registerMessage("time-stopped", () => {
+ const state = getState();
// Only trigger when actively recording
- if (contentStateRef.current.recording && !contentStateRef.current.paused) {
+ if (state.recording && !state.paused) {
setContentState((prev) => ({
...prev,
timeWarning: false,
}));
- contentStateRef.current.openToast(
- chrome.i18n.getMessage("recordingLimitReachedToast"),
- () => {},
- 5000
- );
+ if (state.openToast) {
+ state.openToast(
+ chrome.i18n.getMessage("recordingLimitReachedToast"),
+ () => {},
+ 5000
+ );
+ }
}
});
diff --git a/src/pages/Editor/Sandbox.jsx b/src/pages/Editor/Sandbox.jsx
index dcab371..61ab577 100644
--- a/src/pages/Editor/Sandbox.jsx
+++ b/src/pages/Editor/Sandbox.jsx
@@ -6,9 +6,6 @@ import base64ToBlob from "./utils/base64toBlob";
import blobToArrayBuffer from "./utils/blobToArrayBuffer";
import cropVideo from "./utils/cropVideo";
import cutVideo from "./utils/cutVideo";
-import fetchFile from "./utils/fetchFile";
-import generateThumbstrips from "./utils/generateThumbstrips";
-import getAudio from "./utils/getAudio";
import getFrame from "./utils/getFrame";
import hasAudio from "./utils/hasAudio";
import muteVideo from "./utils/muteVideo";
@@ -35,7 +32,16 @@ const Sandbox = () => {
// Initialize ffmpeg.js
ffmpegInstance.current = createFFmpeg({
log: false,
- progress: (params) => {},
+ progress: (params) => {
+ // Send progress updates to parent window
+ if (params.ratio && params.ratio >= 0) {
+ const percentage = Math.min(Math.round(params.ratio * 100), 100);
+ sendMessage({
+ type: "ffmpeg-progress",
+ progress: percentage,
+ });
+ }
+ },
corePath: "assets/vendor/ffmpeg-core.js",
});
await ffmpegInstance.current.load();
@@ -94,7 +100,7 @@ const Sandbox = () => {
message.replaceAudio
);
const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
+ sendMessage({ type: "updated-blob", base64: base64, topLevel: true });
} catch (error) {
sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
}
@@ -102,7 +108,7 @@ const Sandbox = () => {
try {
const blob = await base64ToBlob(ffmpegInstance.current, message.base64);
const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
+ sendMessage({ type: "updated-blob", base64: base64, topLevel: true });
} catch (error) {
sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
}
@@ -125,8 +131,8 @@ const Sandbox = () => {
height: message.height,
});
const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- sendMessage({ type: "crop-update" });
+ sendMessage({ type: "updated-blob", base64: base64, topLevel: true });
+ //sendMessage({ type: "crop-update" });
} catch (error) {
sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
}
@@ -150,33 +156,6 @@ const Sandbox = () => {
} catch (error) {
sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
}
- } else if (message.type === "fetch-file") {
- try {
- const blob = await fetchFile(message.url);
- const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "generate-thumbstrips") {
- try {
- const blob = await generateThumbstrips(
- ffmpegInstance.current,
- message.blob
- );
- const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "get-audio") {
- try {
- const blob = await getAudio(ffmpegInstance.current, message.video);
- const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
} else if (message.type === "get-frame") {
try {
const blob = await getFrame(
@@ -221,7 +200,7 @@ const Sandbox = () => {
message.duration
);
const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
+ sendMessage({ type: "updated-blob", base64: base64, topLevel: true });
} catch (error) {
sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
}
diff --git a/src/pages/Editor/utils/fetchFile.js b/src/pages/Editor/utils/fetchFile.js
deleted file mode 100644
index 89126ba..0000000
--- a/src/pages/Editor/utils/fetchFile.js
+++ /dev/null
@@ -1,6 +0,0 @@
-async function fetchFile(url) {
- const response = await fetch(url);
- return new Uint8Array(await response.arrayBuffer());
-}
-
-export default fetchFile;
diff --git a/src/pages/Editor/utils/generateThumbstrips.js b/src/pages/Editor/utils/generateThumbstrips.js
deleted file mode 100644
index 3779653..0000000
--- a/src/pages/Editor/utils/generateThumbstrips.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* generateThumbstrips.js */
-async function generateThumbstrips(videoBlob, ffmpeg, frames = 5) {
- // Read video data
- const videoData = new Uint8Array(await videoBlob.arrayBuffer());
-
- // Write video data to the virtual file system
- ffmpeg.FS("writeFile", "input.mp4", videoData);
-
- const thumbstrips = [];
-
- const duration = ffmpeg.getInfo("duration");
- const interval = duration / frames;
-
- for (let i = 0; i < frames; i++) {
- const time = i * interval;
- const outputFileName = `output${i.toString().padStart(3, "0")}.jpg`;
-
- // Use FFmpeg to extract a frame as a JPEG image
- await ffmpeg.run(
- "-i",
- "input.mp4",
- "-ss",
- time.toString(),
- "-frames:v",
- "1",
- "-q:v",
- "3",
- outputFileName
- );
-
- // Read the generated thumbnail image
- const thumbnailData = ffmpeg.FS("readFile", outputFileName);
-
- // Create a Blob from the thumbnail data
- const thumbnailBlob = new Blob([thumbnailData.buffer], {
- type: "image/jpeg",
- });
-
- thumbstrips.push(thumbnailBlob);
- }
-
- return thumbstrips;
-}
-
-export default generateThumbstrips;
diff --git a/src/pages/Editor/utils/getAudio.js b/src/pages/Editor/utils/getAudio.js
deleted file mode 100644
index 9446447..0000000
--- a/src/pages/Editor/utils/getAudio.js
+++ /dev/null
@@ -1,33 +0,0 @@
-async function getAudio(ffmpeg, videoBlob) {
- try {
- // Set the input video file name
- ffmpeg.FS("writeFile", "input.mp4", videoBlob);
-
- // Define the output audio file name
- const outputAudioFileName = "output-audio.wav";
-
- // Run FFmpeg to extract audio from the video
- await ffmpeg.run(
- "-i",
- "input.mp4",
- "-q:a",
- "0",
- "-map",
- "a",
- outputAudioFileName
- );
-
- // Get the extracted audio data
- const audioData = ffmpeg.FS("readFile", outputAudioFileName);
-
- // Create a Blob from the audio data
- const audioBlob = new Blob([audioData.buffer], { type: "audio/wav" });
-
- // Return the audio Blob
- return audioBlob;
- } catch (error) {
- console.error("Error extracting audio from video:", error);
- }
-}
-
-export default getAudio;
diff --git a/src/pages/EditorFallback/Sandbox.jsx b/src/pages/EditorFallback/Sandbox.jsx
deleted file mode 100644
index ae394c9..0000000
--- a/src/pages/EditorFallback/Sandbox.jsx
+++ /dev/null
@@ -1,230 +0,0 @@
-import React, { useEffect, useRef } from "react";
-
-// Import all the utils
-import addAudioToVideo from "./utils/addAudioToVideo";
-import base64ToBlob from "./utils/base64toBlob";
-import blobToArrayBuffer from "./utils/blobToArrayBuffer";
-import cropVideo from "./utils/cropVideo";
-import cutVideo from "./utils/cutVideo";
-import fetchFile from "./utils/fetchFile";
-import generateThumbstrips from "./utils/generateThumbstrips";
-import getAudio from "./utils/getAudio";
-import getFrame from "./utils/getFrame";
-import hasAudio from "./utils/hasAudio";
-import muteVideo from "./utils/muteVideo";
-import reencodeVideo from "./utils/reencodeVideo";
-import toGIF from "./utils/toGIF";
-
-const Sandbox = () => {
- const iframeRef = useRef(null);
- const triggerLoad = useRef(false);
- const ffmpegInstance = useRef(null);
-
- const sendMessage = (message) => {
- iframeRef.current.contentWindow.postMessage(message, "*");
- };
-
- const loadFfmpeg = async () => {
- sendMessage({ type: "ffmpeg-load-error", fallback: true });
- };
-
- const toBase64 = (blob) => {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.readAsDataURL(blob);
- reader.onloadend = () => {
- resolve(reader.result);
- };
- reader.onerror = reject;
- });
- };
-
- const onMessage = async (message) => {
- if (message.type === "load-ffmpeg") {
- triggerLoad.current = true;
- loadFfmpeg();
- } else if (message.type === "add-audio-to-video") {
- try {
- const blob = await addAudioToVideo(
- ffmpegInstance.current,
- message.blob,
- message.audio,
- message.duration,
- message.volume,
- message.replaceAudio
- );
- const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "base64-to-blob") {
- try {
- const blob = await base64ToBlob(ffmpegInstance.current, message.base64);
- const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "blob-to-array-buffer") {
- try {
- const arrayBuffer = await blobToArrayBuffer(
- ffmpegInstance.current,
- message.blob
- );
- sendMessage({ type: "updated-array-buffer", arrayBuffer: arrayBuffer });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "crop-video") {
- try {
- const blob = await cropVideo(ffmpegInstance.current, message.blob, {
- x: message.x,
- y: message.y,
- width: message.width,
- height: message.height,
- });
- const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- sendMessage({ type: "crop-update" });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "cut-video") {
- try {
- const blob = await cutVideo(
- ffmpegInstance.current,
- message.blob,
- message.startTime,
- message.endTime,
- message.cut,
- message.duration,
- message.encode
- );
- const base64 = await toBase64(blob);
- sendMessage({
- type: "updated-blob",
- base64: base64,
- addToHistory: true,
- });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "fetch-file") {
- try {
- const blob = await fetchFile(message.url);
- const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "generate-thumbstrips") {
- try {
- const blob = await generateThumbstrips(
- ffmpegInstance.current,
- message.blob
- );
- const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "get-audio") {
- try {
- const blob = await getAudio(ffmpegInstance.current, message.video);
- const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "get-frame") {
- try {
- const blob = await getFrame(
- ffmpegInstance.current,
- message.blob,
- message.time
- );
- sendMessage({ type: "new-frame", frame: blob });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "has-audio") {
- try {
- const audio = await hasAudio(ffmpegInstance.current, message.video);
- sendMessage({ type: "updated-has-audio", hasAudio: audio });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "mute-video") {
- try {
- const blob = await muteVideo(
- ffmpegInstance.current,
- message.blob,
- message.startTime,
- message.endTime,
- message.duration
- );
- const base64 = await toBase64(blob);
- sendMessage({
- type: "updated-blob",
- base64: base64,
- addToHistory: true,
- });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "reencode-video") {
- try {
- const blob = await reencodeVideo(
- ffmpegInstance.current,
- message.blob,
- message.duration
- );
- const base64 = await toBase64(blob);
- sendMessage({ type: "updated-blob", base64: base64 });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- } else if (message.type === "to-gif") {
- try {
- const blob = await toGIF(ffmpegInstance.current, message.blob);
- const base64 = await toBase64(blob);
- sendMessage({ type: "download-gif", base64: base64 });
- } catch (error) {
- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
- }
- }
- };
-
- useEffect(() => {
- window.addEventListener("message", (event) => {
- onMessage(event.data);
- });
-
- return () => {
- window.removeEventListener("message", (event) => {
- onMessage(event.data);
- });
- };
- }, []);
-
- return (
- <div>
- <iframe
- ref={iframeRef}
- src="sandbox.html"
- allowFullScreen={true}
- style={{
- width: "100%",
- border: "none",
- height: "100vh",
- position: "absolute",
- top: 0,
- left: 0,
- }}
- ></iframe>
- </div>
- );
-};
-
-export default Sandbox;
diff --git a/src/pages/EditorFallback/utils/addAudioToVideo.js b/src/pages/EditorFallback/utils/addAudioToVideo.js
deleted file mode 100644
index 80cd717..0000000
--- a/src/pages/EditorFallback/utils/addAudioToVideo.js
+++ /dev/null
@@ -1,78 +0,0 @@
-async function addAudioToVideo(
- ffmpeg,
- videoBlob,
- audioBlob,
- videoDuration,
- audioVolume = 1.0,
- replaceAudio = false
-) {
- const videoData = new Uint8Array(await videoBlob.arrayBuffer());
- const audioData = new Uint8Array(await audioBlob.arrayBuffer());
-
- // Set the input video and audio file names
- ffmpeg.FS("writeFile", "input-video.mp4", videoData);
- ffmpeg.FS("writeFile", "input-audio.mp3", audioData);
-
- // Set the output video file name
- const outputFileName = "output-with-audio.mp4";
-
- // Build FFmpeg command for merging video and audio with volume adjustment
- let ffmpegCommand = [
- "-i",
- "input-video.mp4",
- "-i",
- "input-audio.mp3",
- "-filter_complex",
- `[0:a]volume=1[a];[1:a]volume=${audioVolume}[b];[a][b]amix=inputs=2:duration=first:dropout_transition=2[v]`,
- "-map",
- "0:v", // Map the original video stream
- "-map",
- "[v]", // Map the merged audio
- "-c:v",
- "copy",
- "-c:a",
- "aac",
- "-strict",
- "experimental",
- "-shortest",
- outputFileName,
- ];
-
- if (replaceAudio) {
- // Remove the original audio stream and replace it with the audio from the audio blob
- ffmpegCommand = [
- "-i",
- "input-video.mp4",
- "-i",
- "input-audio.mp3",
- "-filter_complex",
- "[0:a]volume=0[a];[1:a]volume=1[b];[a][b]amix=inputs=2:duration=first:dropout_transition=2[v]",
- "-map",
- "0:v", // Map the original video stream
- "-map",
- "[v]", // Map the merged audio
- "-c:v",
- "copy",
- "-c:a",
- "aac",
- "-strict",
- "experimental",
- "-shortest",
- outputFileName,
- ];
- }
-
- // Run FFmpeg to merge video and audio with volume adjustment
- await ffmpeg.run(...ffmpegCommand);
-
- // Get the merged video data
- const data = ffmpeg.FS("readFile", outputFileName);
-
- // Create a Blob from the merged video data
- const videoWithAudioBlob = new Blob([data.buffer], { type: "video/mp4" });
-
- // Return the video with merged audio Blob
- return videoWithAudioBlob;
-}
-
-export default addAudioToVideo;
diff --git a/src/pages/EditorFallback/utils/base64toBlob.js b/src/pages/EditorFallback/utils/base64toBlob.js
deleted file mode 100644
index 29486b7..0000000
--- a/src/pages/EditorFallback/utils/base64toBlob.js
+++ /dev/null
@@ -1,44 +0,0 @@
-function base64ToUint8Array(base64) {
- const dataURLRegex = /^data:.+;base64,/;
- if (dataURLRegex.test(base64)) {
- base64 = base64.replace(dataURLRegex, "");
- }
-
- const binary_string = window.atob(base64);
- const len = binary_string.length;
- const bytes = new Uint8Array(len);
-
- for (let i = 0; i < len; i++) {
- bytes[i] = binary_string.charCodeAt(i);
- }
-
- return bytes;
-}
-
-async function base64ToBlob(ffmpeg, base64) {
- const input = base64ToUint8Array(base64);
- ffmpeg.FS("writeFile", "input.webm", input);
-
- await ffmpeg.run(
- "-i",
- "input.webm",
- "-max_muxing_queue_size",
- "512",
- "-preset",
- "superfast",
- "-threads",
- "0",
- "-r",
- "30",
- "-tune",
- "fastdecode",
- "output.mp4"
- );
-
- const data = ffmpeg.FS("readFile", "output.mp4");
- const videoBlob = new Blob([data.buffer], { type: "video/mp4" });
-
- return videoBlob;
-}
-
-export default base64ToBlob;
diff --git a/src/pages/EditorFallback/utils/cropVideo.js b/src/pages/EditorFallback/utils/cropVideo.js
deleted file mode 100644
index b9405fe..0000000
--- a/src/pages/EditorFallback/utils/cropVideo.js
+++ /dev/null
@@ -1,42 +0,0 @@
-async function cropVideo(ffmpeg, videoBlob, cropParameters) {
- const videoData = new Uint8Array(await videoBlob.arrayBuffer());
-
- // Set the input video file name
- ffmpeg.FS("writeFile", "input.mp4", videoData);
-
- // Set the output video file name
- const outputFileName = "output-cropped.mp4";
-
- // Build FFmpeg command for cropping
- const ffmpegCommand = [
- "-i",
- "input.mp4",
- "-vf",
- `crop=${cropParameters.width}:${cropParameters.height}:${cropParameters.x}:${cropParameters.y}`,
- "-c:a",
- "copy",
- "-preset",
- "superfast",
- "-threads",
- "0",
- "-r",
- "30",
- "-tune",
- "fastdecode",
- outputFileName,
- ];
-
- // Run FFmpeg to crop the video
- await ffmpeg.run(...ffmpegCommand);
-
- // Get the cropped video data
- const data = ffmpeg.FS("readFile", outputFileName);
-
- // Create a Blob from the cropped video data
- const croppedVideoBlob = new Blob([data.buffer], { type: "video/mp4" });
-
- // Return the cropped video Blob
- return croppedVideoBlob;
-}
-
-export default cropVideo;
diff --git a/src/pages/EditorFallback/utils/cutVideo.js b/src/pages/EditorFallback/utils/cutVideo.js
deleted file mode 100644
index 3c2f278..0000000
--- a/src/pages/EditorFallback/utils/cutVideo.js
+++ /dev/null
@@ -1,143 +0,0 @@
-async function cutVideo(ffmpeg, videoBlob, start, end, cut, duration, encode) {
- const videoData = new Uint8Array(await videoBlob.arrayBuffer());
-
- // Set the input video file name
- ffmpeg.FS("writeFile", "input.mp4", videoData);
-
- // Set the output video file name
- const outputFileName = cut ? "output-cut.mp4" : "output-trimmed.mp4";
- let encodeOptions = [
- "-c:v",
- "copy",
- "-c:a",
- "copy",
- "-reset_timestamps",
- "1",
- ];
- if (encode) {
- encodeOptions = [
- "-preset",
- "superfast",
- "-threads",
- "0",
- "-r",
- "30",
- "-tune",
- "fastdecode",
- ];
- }
-
- if (cut) {
- if (start > 0 && end < duration) {
- await ffmpeg.run(
- "-ss",
- "0",
- "-i",
- "input.mp4",
- "-to",
- start.toString(),
- ...encodeOptions,
- "part1.mp4"
- );
-
- // Then, cut the video from the end time to the end
- await ffmpeg.run(
- "-ss",
- end.toString(),
- "-i",
- "input.mp4",
- "-to",
- duration.toString(),
- ...encodeOptions,
- "part2.mp4"
- );
-
- // Create a text file with the list of input videos
- ffmpeg.FS("writeFile", "input.txt", "file 'part1.mp4'\nfile 'part2.mp4'");
-
- // Concatenate the two remaining parts
- await ffmpeg.run(
- "-f",
- "concat",
- "-safe",
- "0",
- "-i",
- "input.txt",
- "-c",
- "copy",
- outputFileName
- );
-
- // Get the edited video data
- const data = ffmpeg.FS("readFile", outputFileName);
-
- // Create a Blob from the edited video data
- const editedVideoBlob = new Blob([data.buffer], { type: "video/mp4" });
-
- // Return the edited video Blob
- return editedVideoBlob;
- } else if (start == 0 && end < duration) {
- await ffmpeg.run(
- "-ss",
- end.toString(),
- "-i",
- "input.mp4",
- "-to",
- duration.toString(),
- ...encodeOptions,
- outputFileName
- );
-
- // Get the edited video data
- const data = ffmpeg.FS("readFile", outputFileName);
-
- // Create a Blob from the edited video data
- const editedVideoBlob = new Blob([data.buffer], { type: "video/mp4" });
-
- // Return the edited video Blob
- return editedVideoBlob;
- } else if (start > 0 && end == duration) {
- await ffmpeg.run(
- "-ss",
- "0",
- "-i",
- "input.mp4",
- "-to",
- start.toString(),
- ...encodeOptions,
- outputFileName
- );
-
- // Get the edited video data
- const data = ffmpeg.FS("readFile", outputFileName);
-
- // Create a Blob from the edited video data
- const editedVideoBlob = new Blob([data.buffer], { type: "video/mp4" });
-
- // Return the edited video Blob
- return editedVideoBlob;
- }
- } else {
- await ffmpeg.run(
- "-ss",
- start.toString(),
- "-i",
- "input.mp4",
- "-t",
- (end - start).toString(),
- ...encodeOptions,
- outputFileName
- );
-
- // Get the edited video data
- const data = ffmpeg.FS("readFile", outputFileName);
-
- // Create a Blob from the edited video data
- const editedVideoBlob = new Blob([data.buffer], { type: "video/mp4" });
-
- // Return the edited video Blob
- return editedVideoBlob;
- }
-}
-
-export default cutVideo;
diff --git a/src/pages/EditorFallback/utils/fetchFile.js b/src/pages/EditorFallback/utils/fetchFile.js
deleted file mode 100644
index 89126ba..0000000
--- a/src/pages/EditorFallback/utils/fetchFile.js
+++ /dev/null
@@ -1,6 +0,0 @@
-async function fetchFile(url) {
- const response = await fetch(url);
- return new Uint8Array(await response.arrayBuffer());
-}
-
-export default fetchFile;
diff --git a/src/pages/EditorFallback/utils/generateThumbstrips.js b/src/pages/EditorFallback/utils/generateThumbstrips.js
deleted file mode 100644
index 3779653..0000000
--- a/src/pages/EditorFallback/utils/generateThumbstrips.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* generateThumbstrips.js */
-async function generateThumbstrips(videoBlob, ffmpeg, frames = 5) {
- // Read video data
- const videoData = new Uint8Array(await videoBlob.arrayBuffer());
-
- // Write video data to the virtual file system
- ffmpeg.FS("writeFile", "input.mp4", videoData);
-
- const thumbstrips = [];
-
- const duration = ffmpeg.getInfo("duration");
- const interval = duration / frames;
-
- for (let i = 0; i < frames; i++) {
- const time = i * interval;
- const outputFileName = `output${i.toString().padStart(3, "0")}.jpg`;
-
- // Use FFmpeg to extract a frame as a JPEG image
- await ffmpeg.run(
- "-i",
- "input.mp4",
- "-ss",
- time.toString(),
- "-frames:v",
- "1",
- "-q:v",
- "3",
- outputFileName
- );
-
- // Read the generated thumbnail image
- const thumbnailData = ffmpeg.FS("readFile", outputFileName);
-
- // Create a Blob from the thumbnail data
- const thumbnailBlob = new Blob([thumbnailData.buffer], {
- type: "image/jpeg",
- });
-
- thumbstrips.push(thumbnailBlob);
- }
-
- return thumbstrips;
-}
-
-export default generateThumbstrips;
diff --git a/src/pages/EditorFallback/utils/getAudio.js b/src/pages/EditorFallback/utils/getAudio.js
deleted file mode 100644
index 9446447..0000000
--- a/src/pages/EditorFallback/utils/getAudio.js
+++ /dev/null
@@ -1,33 +0,0 @@
-async function getAudio(ffmpeg, videoBlob) {
- try {
- // Set the input video file name
- ffmpeg.FS("writeFile", "input.mp4", videoBlob);
-
- // Define the output audio file name
- const outputAudioFileName = "output-audio.wav";
-
- // Run FFmpeg to extract audio from the video
- await ffmpeg.run(
- "-i",
- "input.mp4",
- "-q:a",
- "0",
- "-map",
- "a",
- outputAudioFileName
- );
-
- // Get the extracted audio data
- const audioData = ffmpeg.FS("readFile", outputAudioFileName);
-
- // Create a Blob from the audio data
- const audioBlob = new Blob([audioData.buffer], { type: "audio/wav" });
-
- // Return the audio Blob
- return audioBlob;
- } catch (error) {
- console.error("Error extracting audio from video:", error);
- }
-}
-
-export default getAudio;
diff --git a/src/pages/EditorFallback/utils/getFrame.js b/src/pages/EditorFallback/utils/getFrame.js
deleted file mode 100644
index 2d605bf..0000000
--- a/src/pages/EditorFallback/utils/getFrame.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* getFrame.js */
-async function getFrame(ffmpeg, videoBlob, time = 0) {
- const videoData = new Uint8Array(await videoBlob.arrayBuffer());
- // Write video data to a file
- ffmpeg.FS("writeFile", "input.mp4", videoData);
-
- const outputFileName = "output.jpg";
-
- // Use FFmpeg to extract a frame as a JPEG image
- await ffmpeg.run(
- "-i",
- "input.mp4",
- "-ss",
- time.toString(),
- "-frames:v",
- "1",
- "-preset",
- "superfast",
- "-threads",
- "0",
- "-r",
- "30",
- "-tune",
- "fastdecode",
- outputFileName
- );
-
- // Read the generated frame image
- const frameData = ffmpeg.FS("readFile", outputFileName);
-
- // Create a Blob from the frame data
- const frameBlob = new Blob([frameData.buffer], {
- type: "image/jpeg",
- });
-
- // Clean up
- ffmpeg.FS("unlink", "input.mp4");
- ffmpeg.FS("unlink", outputFileName);
-
- return frameBlob;
-}
-
-export default getFrame;
diff --git a/src/pages/EditorFallback/utils/hasAudio.js b/src/pages/EditorFallback/utils/hasAudio.js
deleted file mode 100644
index f6e3bad..0000000
--- a/src/pages/EditorFallback/utils/hasAudio.js
+++ /dev/null
@@ -1,47 +0,0 @@
-const hasAudio = async (videoBlob) => {
- const videoElement = document.createElement("video");
- videoElement.src = URL.createObjectURL(videoBlob);
-
- return new Promise(async (resolve, reject) => {
- try {
- videoElement.addEventListener("loadedmetadata", async () => {
- try {
- const mediaSource = new MediaSource();
- videoElement.src = URL.createObjectURL(mediaSource);
- await mediaSource.addSourceBuffer(videoBlob.type);
-
- mediaSource.onsourceopen = () => {
- const audioContext = new AudioContext();
- const source = audioContext.createMediaElementSource(videoElement);
-
- source.connect(audioContext.destination);
- source.onended = () => {
- // If audio plays and ends, it has audio tracks
- resolve(true);
- };
- source.onerror = () => {
- // If there's an error, it doesn't have audio tracks
- resolve(false);
- };
-
- videoElement.play();
- };
- } catch (error) {
- resolve(false); // MediaSource or AudioContext not supported
- }
- });
-
- videoElement.addEventListener("error", (error) => {
- reject(error);
- });
-
- videoElement.load();
- } catch (error) {
- reject(error);
- } finally {
- URL.revokeObjectURL(videoElement.src);
- }
- });
-};
-
-export default hasAudio;
diff --git a/src/pages/EditorFallback/utils/muteVideo.js b/src/pages/EditorFallback/utils/muteVideo.js
deleted file mode 100644
index e517770..0000000
--- a/src/pages/EditorFallback/utils/muteVideo.js
+++ /dev/null
@@ -1,38 +0,0 @@
-async function muteVideo(ffmpeg, videoBlob, start, end) {
- try {
- const videoData = new Uint8Array(await videoBlob.arrayBuffer());
-
- // Set the input video file name
- ffmpeg.FS("writeFile", "input.mp4", videoData);
-
- // Set the output video file name
- const outputFileName = "output.mp4";
-
- // Mute the audio in the specified time range
- await ffmpeg.run(
- "-i",
- "input.mp4",
- "-af",
- `volume='if(between(t,${start},${end}),0,1)':eval=frame`,
- "-c:v",
- "copy",
- "-c:a",
- "aac",
- outputFileName
- );
-
- // Get the edited video data
- const data = ffmpeg.FS("readFile", outputFileName);
-
- // Create a Blob from the edited video data
- const editedVideoBlob = new Blob([data.buffer], { type: "video/mp4" });
-
- // Return the edited video Blob
- return editedVideoBlob;
- } catch (error) {
- console.error("Error muting video:", error);
- return null;
- }
-}
-
-export default muteVideo;
diff --git a/src/pages/EditorFallback/utils/reencodeVideo.js b/src/pages/EditorFallback/utils/reencodeVideo.js
deleted file mode 100644
index 2cd5cab..0000000
--- a/src/pages/EditorFallback/utils/reencodeVideo.js
+++ /dev/null
@@ -1,26 +0,0 @@
-async function reencodeVideo(ffmpeg, blob) {
- const videoData = new Uint8Array(await blob.arrayBuffer());
- const outputFileName = "output.mp4";
- ffmpeg.FS("writeFile", "input.mp4", videoData);
- await ffmpeg.run(
- "-i",
- "input.mp4",
- "-preset",
- "superfast",
- "-threads",
- "0",
- "-r",
- "30",
- "-tune",
- "fastdecode",
- outputFileName
- );
-
- const data = ffmpeg.FS("readFile", outputFileName);
- const editedVideoBlob = new Blob([data.buffer], {
- type: "video/mp4",
- });
- return editedVideoBlob;
-}
-
-export default reencodeVideo;
diff --git a/src/pages/EditorFallback/utils/toGIF.js b/src/pages/EditorFallback/utils/toGIF.js
deleted file mode 100644
index 397f593..0000000
--- a/src/pages/EditorFallback/utils/toGIF.js
+++ /dev/null
@@ -1,25 +0,0 @@
-async function toGIF(ffmpeg, blob) {
- const videoData = new Uint8Array(await blob.arrayBuffer());
- const outputFileName = "output.gif";
- ffmpeg.FS("writeFile", "input.mp4", videoData);
- await ffmpeg.run(
- "-i",
- "input.mp4",
- "-preset",
- "superfast",
- "-threads",
- "0",
- "-r",
- "30",
- "-tune",
- "fastdecode",
- outputFileName
- );
- const data = ffmpeg.FS("readFile", outputFileName);
- const editedVideoBlob = new Blob([data.buffer], {
- type: "image/gif",
- });
- return editedVideoBlob;
-}
-
-export default toGIF;
diff --git a/src/pages/EditorViewer/Sandbox.jsx b/src/pages/EditorViewer/Sandbox.jsx
new file mode 100644
index 0000000..cb97e2c
--- /dev/null
+++ b/src/pages/EditorViewer/Sandbox.jsx
@@ -0,0 +1,57 @@
+import React, { useEffect, useRef } from "react";
+
+const Sandbox = () => {
+ const iframeRef = useRef(null);
+
+ const sendMessage = (message) => {
+ if (iframeRef.current?.contentWindow) {
+ iframeRef.current.contentWindow.postMessage(message, "*");
+ }
+ };
+
+ const onMessage = async (message) => {
+ if (message.type === "load-ffmpeg") {
+ sendMessage({ type: "ffmpeg-load-error", fallback: true });
+ } else if (
+ message.type === "add-audio-to-video" ||
+ message.type === "base64-to-blob" ||
+ message.type === "crop-video" ||
+ message.type === "cut-video" ||
+ message.type === "mute-video" ||
+ message.type === "reencode-video" ||
+ message.type === "to-gif"
+ ) {
+ sendMessage({
+ type: "ffmpeg-error",
+ error:
+ "Processing not available in viewer mode. Please use a modern browser (Chrome 94+) for editing features.",
+ });
+ }
+ };
+
+ useEffect(() => {
+ const handler = (event) => onMessage(event.data);
+ window.addEventListener("message", handler);
+ return () => window.removeEventListener("message", handler);
+ }, []);
+
+ return (
+ <div>
+ <iframe
+ ref={iframeRef}
+ src="sandbox.html"
+ allowFullScreen
+ style={{
+ width: "100%",
+ border: "none",
+ height: "100vh",
+ position: "absolute",
+ top: 0,
+ left: 0,
+ }}
+ />
+ </div>
+ );
+};
+
+export default Sandbox;
diff --git a/src/pages/EditorViewer/index.css b/src/pages/EditorViewer/index.css
new file mode 100644
index 0000000..5dc8ff7
--- /dev/null
+++ b/src/pages/EditorViewer/index.css
@@ -0,0 +1,20 @@
+/* EditorViewer shares styles with Editor */
+body {
+ margin: 0;
+ padding: 0;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
+ "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
+ sans-serif;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+ font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
+ monospace;
+}
+
+* {
+ box-sizing: border-box;
+}
+
diff --git a/src/pages/EditorViewer/index.html b/src/pages/EditorViewer/index.html
new file mode 100644
index 0000000..34ad3cd
--- /dev/null
+++ b/src/pages/EditorViewer/index.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <title>Screenity - Viewer</title>
+
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ </head>
+
+ <body>
+ <div id="app-container"></div>
+ </body>
+</html>
diff --git a/src/pages/EditorViewer/index.jsx b/src/pages/EditorViewer/index.jsx
new file mode 100644
index 0000000..1fbdf47
--- /dev/null
+++ b/src/pages/EditorViewer/index.jsx
@@ -0,0 +1,8 @@
+import React from "react";
+import { createRoot } from "react-dom/client";
+import Sandbox from "./Sandbox";
+import "./index.css";
+
+const container = document.querySelector("#app-container");
+const root = createRoot(container);
+root.render(<Sandbox />);
diff --git a/src/pages/EditorWebCodecs/Sandbox.jsx b/src/pages/EditorWebCodecs/Sandbox.jsx
new file mode 100644
index 0000000..83cf049
--- /dev/null
+++ b/src/pages/EditorWebCodecs/Sandbox.jsx
@@ -0,0 +1,259 @@
+import React, { useEffect, useRef } from "react";
+
+import addAudioToVideo from "./utils/addAudioToVideo";
+import convertWebmToMp4 from "./utils/convertWebmToMp4";
+import cropVideo from "./utils/cropVideo";
+import cutVideo from "./utils/cutVideo";
+import muteVideo from "./utils/muteVideo";
+import reencodeVideo from "./utils/reencodeVideo";
+import toGIF from "./utils/toGIF";
+import getFrame from "./utils/getFrame";
+import hasAudio from "./utils/hasAudio";
+import convertMp4ToWebm from "./utils/convertMp4ToWebm";
+import blobToArrayBuffer from "./utils/blobToArrayBuffer";
+
+const Sandbox = () => {
+ const iframeRef = useRef(null);
+ const triggerLoad = useRef(false);
+ const ffmpegInstance = useRef(null);
+ const mediabunnyLoaded = useRef(false);
+
+ const sendMessage = (message) => {
+ iframeRef.current?.contentWindow?.postMessage(message, "*");
+ };
+
+ const loadFfmpeg = async () => {
+ if (mediabunnyLoaded.current || !triggerLoad.current) return;
+ try {
+ mediabunnyLoaded.current = true;
+ sendMessage({ type: "ffmpeg-loaded" });
+ } catch (error) {
+ sendMessage({
+ type: "ffmpeg-load-error",
+ error: JSON.stringify(error),
+ fallback: true,
+ });
+ }
+ };
+
+ const toBase64 = (blob) =>
+ new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.readAsDataURL(blob);
+ reader.onloadend = () => resolve(reader.result);
+ reader.onerror = reject;
+ });
+
+ const base64ToWebmBlob = (base64) => {
+ const dataURLRegex = /^data:.+;base64,/;
+ if (dataURLRegex.test(base64)) base64 = base64.replace(dataURLRegex, "");
+ const binary = window.atob(base64);
+ const len = binary.length;
+ const bytes = new Uint8Array(len);
+ for (let i = 0; i < len; i++) bytes[i] = binary.charCodeAt(i);
+ return new Blob([bytes], { type: "video/webm" });
+ };
+
+ const onMessage = async (message) => {
+ try {
+ switch (message.type) {
+ case "load-ffmpeg":
+ triggerLoad.current = true;
+ await loadFfmpeg();
+ break;
+
+ case "add-audio-to-video": {
+ const blob = await addAudioToVideo(
+ ffmpegInstance.current,
+ message.blob,
+ message.audio,
+ message.duration,
+ message.volume,
+ message.replaceAudio,
+ (progress) =>
+ sendMessage({
+ type: "ffmpeg-progress",
+ progress: Math.round(progress * 100),
+ })
+ );
+ const base64 = await toBase64(blob);
+ sendMessage({
+ type: "updated-blob",
+ base64,
+ topLevel: true,
+ fromAudio: true,
+ });
+ break;
+ }
+
+ case "base64-to-blob": {
+ const webmBlob = base64ToWebmBlob(message.base64);
+ const mp4Blob = await convertWebmToMp4(webmBlob, (progress) =>
+ sendMessage({
+ type: "ffmpeg-progress",
+ progress: Math.round(progress * 100),
+ })
+ );
+ const base64 = await toBase64(mp4Blob);
+ sendMessage({ type: "updated-blob", base64, topLevel: true });
+ break;
+ }
+
+ case "blob-to-array-buffer": {
+ const arrayBuffer = await blobToArrayBuffer(
+ ffmpegInstance.current,
+ message.blob
+ );
+ sendMessage({ type: "updated-array-buffer", arrayBuffer });
+ break;
+ }
+
+ case "crop-video": {
+ const blob = await cropVideo(
+ ffmpegInstance.current,
+ message.blob,
+ {
+ x: message.x,
+ y: message.y,
+ width: message.width,
+ height: message.height,
+ },
+ (progress) => sendMessage({ type: "ffmpeg-progress", progress })
+ );
+ const base64 = await toBase64(blob);
+ sendMessage({ type: "updated-blob", base64, topLevel: true });
+ break;
+ }
+
+ case "cut-video": {
+ const blob = await cutVideo(
+ ffmpegInstance.current,
+ message.blob,
+ message.startTime,
+ message.endTime,
+ message.cut,
+ message.duration,
+ message.encode,
+ (progress) => sendMessage({ type: "ffmpeg-progress", progress })
+ );
+ const base64 = await toBase64(blob);
+ sendMessage({
+ type: "updated-blob",
+ base64,
+ addToHistory: true,
+ topLevel: true,
+ });
+ break;
+ }
+
+ case "get-frame": {
+ const blob = await getFrame(
+ ffmpegInstance.current,
+ message.blob,
+ message.time
+ );
+ sendMessage({ type: "new-frame", frame: blob });
+ break;
+ }
+
+ case "has-audio": {
+ const audio = await hasAudio(ffmpegInstance.current, message.video);
+ sendMessage({ type: "updated-has-audio", hasAudio: audio });
+ break;
+ }
+
+ case "mute-video": {
+ const blob = await muteVideo(
+ ffmpegInstance.current,
+ message.blob,
+ message.startTime,
+ message.endTime,
+ message.duration,
+ (progress) => sendMessage({ type: "ffmpeg-progress", progress })
+ );
+ const base64 = await toBase64(blob);
+ sendMessage({
+ type: "updated-blob",
+ base64,
+ addToHistory: true,
+ topLevel: true,
+ });
+ break;
+ }
+
+ case "reencode-video": {
+ const blob = await reencodeVideo(
+ ffmpegInstance.current,
+ message.blob,
+ message.duration,
+ (progress) =>
+ sendMessage({
+ type: "ffmpeg-progress",
+ progress: Math.round(progress * 100),
+ })
+ );
+ const base64 = await toBase64(blob);
+ sendMessage({ type: "updated-blob", base64, topLevel: true });
+ break;
+ }
+
+ case "to-gif": {
+ const blob = await toGIF(ffmpegInstance.current, message.blob);
+ const base64 = await toBase64(blob);
+ sendMessage({ type: "download-gif", base64 });
+ break;
+ }
+
+ case "to-webm": {
+ if (message.blob?.type === "video/webm") {
+ const base64 = await toBase64(message.blob);
+ sendMessage({ type: "download-webm", base64 });
+ return;
+ }
+
+ const result = await convertMp4ToWebm(message.blob, (progress) =>
+ sendMessage({
+ type: "ffmpeg-progress",
+ progress: Math.round(progress * 100),
+ })
+ );
+
+ const base64 = await toBase64(result);
+ sendMessage({ type: "download-webm", base64 });
+ break;
+ }
+
+ default:
+ break;
+ }
+ } catch (error) {
+ sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });
+ }
+ };
+
+ useEffect(() => {
+ const handler = (event) => onMessage(event.data);
+ window.addEventListener("message", handler);
+ return () => window.removeEventListener("message", handler);
+ }, []);
+
+ return (
+ <div>
+ <iframe
+ ref={iframeRef}
+ src="sandbox.html"
+ allowFullScreen
+ style={{
+ width: "100%",
+ border: "none",
+ height: "100vh",
+ position: "absolute",
+ top: 0,
+ left: 0,
+ }}
+ />
+ </div>
+ );
+};
+
+export default Sandbox;
diff --git a/src/pages/EditorFallback/index.html b/src/pages/EditorWebCodecs/index.html
similarity index 100%
rename from src/pages/EditorFallback/index.html
rename to src/pages/EditorWebCodecs/index.html
diff --git a/src/pages/EditorFallback/index.jsx b/src/pages/EditorWebCodecs/index.jsx
similarity index 100%
rename from src/pages/EditorFallback/index.jsx
rename to src/pages/EditorWebCodecs/index.jsx
diff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoAudioMixer.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoAudioMixer.ts
new file mode 100644
index 0000000..ac59d10
--- /dev/null
+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoAudioMixer.ts
@@ -0,0 +1,139 @@
+// @ts-nocheck
+import {
+ Input,
+ BlobSource,
+ Output,
+ BufferTarget,
+ Mp4OutputFormat,
+ VideoSampleSource,
+ AudioSampleSource,
+ VideoSampleSink,
+ AudioSample,
+ ALL_FORMATS,
+ QUALITY_HIGH,
+} from "mediabunny";
+
+export class VideoAudioMixer {
+ async addAudio(
+ videoBlob,
+ audioBlob,
+ {
+ mode = "mix",
+ videoVolume = 0.7,
+ audioVolume = 0.3,
+ loop = false,
+ verbose = false,
+ onProgress,
+ } = {}
+ ) {
+ const input = new Input({
+ source: new BlobSource(videoBlob),
+ formats: ALL_FORMATS,
+ });
+
+ const outputTarget = new BufferTarget();
+ const output = new Output({
+ format: new Mp4OutputFormat({ fastStart: "in-memory" }),
+ target: outputTarget,
+ });
+
+ const videoTrack = await input.getPrimaryVideoTrack();
+ const videoSink = new VideoSampleSink(videoTrack);
+ const videoSource = new VideoSampleSource({
+ codec: "avc",
+ bitrate: QUALITY_HIGH,
+ });
+ output.addVideoTrack(videoSource);
+
+ const videoDuration = await this._getDuration(videoBlob);
+
+ const hasVideoAudio = await input
+ .getPrimaryAudioTrack()
+ .then((t) => !!t)
+ .catch(() => false);
+
+ const audioSource = new AudioSampleSource({
+ codec: "aac",
+ bitrate: 128000,
+ });
+ output.addAudioTrack(audioSource);
+
+ const bgArrayBuffer = await audioBlob.arrayBuffer();
+ const audioCtx = new AudioContext();
+ const decodedAudio = await audioCtx.decodeAudioData(bgArrayBuffer);
+ const sr = decodedAudio.sampleRate;
+ const audioDur = decodedAudio.duration;
+
+ await output.start();
+
+ for await (const frame of videoSink.samples(0, videoDuration)) {
+ await videoSource.add(frame);
+ frame.close();
+ if (onProgress && videoDuration > 0)
+ onProgress(frame.timestamp / videoDuration);
+ }
+
+ const mixBuffer = new Float32Array(Math.ceil(sr * videoDuration));
+ const writeMix = (data, offset, vol) => {
+ for (let i = 0; i < data.length && offset + i < mixBuffer.length; i++) {
+ mixBuffer[offset + i] += data[i] * vol;
+ }
+ };
+
+ if (hasVideoAudio && mode === "mix") {
+ try {
+ const videoArrayBuffer = await videoBlob.arrayBuffer();
+ const videoAudioCtx = new AudioContext();
+ const decodedVideoAudio = await videoAudioCtx.decodeAudioData(
+ videoArrayBuffer
+ );
+ const videoSamples = decodedVideoAudio.getChannelData(0);
+ writeMix(videoSamples, 0, videoVolume);
+ } catch {}
+ }
+
+ const loopCount = loop
+ ? Math.ceil(videoDuration / audioDur)
+ : Math.min(1, Math.ceil(videoDuration / audioDur));
+
+ for (let i = 0; i < loopCount; i++) {
+ const offset = Math.floor(i * audioDur * sr);
+ writeMix(decodedAudio.getChannelData(0), offset, audioVolume);
+ }
+
+ const totalSamples = Math.floor(videoDuration * sr);
+ const chunkSize = sr * 2;
+ let written = 0;
+
+ while (written < totalSamples) {
+ const slice = mixBuffer.slice(written, written + chunkSize);
+ const dur = slice.length / sr;
+ const sample = new AudioSample({
+ data: slice,
+ format: "f32-planar",
+ numberOfChannels: 1,
+ sampleRate: sr,
+ timestamp: written / sr,
+ duration: dur,
+ });
+ await audioSource.add(sample);
+ sample.close();
+ written += chunkSize;
+ }
+
+ await output.finalize();
+ return new Blob([outputTarget.buffer], { type: "video/mp4" });
+ }
+
+ async _getDuration(blob) {
+ return new Promise((resolve, reject) => {
+ const v = document.createElement("video");
+ v.src = URL.createObjectURL(blob);
+ v.onloadedmetadata = () => {
+ resolve(v.duration);
+ URL.revokeObjectURL(v.src);
+ };
+ v.onerror = reject;
+ });
+ }
+}
\ No newline at end of file
diff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoConverter.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoConverter.ts
new file mode 100644
index 0000000..31fcb72
--- /dev/null
+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoConverter.ts
@@ -0,0 +1,182 @@
+// @ts-nocheck
+import {
+ Input,
+ Output,
+ BlobSource,
+ BufferTarget,
+ Mp4OutputFormat,
+ WebMOutputFormat,
+ ALL_FORMATS,
+ Conversion,
+ type VideoCodec,
+ type AudioCodec,
+} from "mediabunny";
+
+export type SupportedFormat = "mp4" | "webm";
+
+export interface ConversionOptions {
+ videoBitrate?: number;
+ audioBitrate?: number;
+ preferredVideoCodec?: VideoCodec;
+ audioCodec?: AudioCodec;
+ onProgress?: (progress: number) => void;
+ verbose?: boolean;
+}
+
+export interface CodecInfo {
+ codec: VideoCodec;
+ displayName: string;
+ isPreferred: boolean;
+}
+
+const CODEC_DISPLAY_NAMES: Record<VideoCodec, string> = {
+ avc: "H.264",
+ hevc: "H.265 (HEVC)",
+ vp9: "VP9",
+ av1: "AV1",
+ vp8: "VP8",
+};
+
+export class VideoConverter {
+ private cachedMP4Codec: VideoCodec | null = null;
+ private cachedWebMCodec: VideoCodec | null = null;
+
+ async convertToMP4(sourceBlob: Blob, options: ConversionOptions = {}): Promise<Blob> {
+ return this.convert(sourceBlob, "mp4", options);
+ }
+
+ async convertToWebM(sourceBlob: Blob, options: ConversionOptions = {}): Promise<Blob> {
+ return this.convert(sourceBlob, "webm", options);
+ }
+
+ async detectBestCodec(format: SupportedFormat): Promise<CodecInfo | null> {
+ const outputFormat =
+ format === "mp4"
+ ? new Mp4OutputFormat({ fastStart: "in-memory" })
+ : new WebMOutputFormat();
+ const supportedCodecs = outputFormat.getSupportedVideoCodecs();
+
+ for (const codec of supportedCodecs) {
+ if (await this.canEncodeCodec(codec)) {
+ return {
+ codec,
+ displayName:
+ CODEC_DISPLAY_NAMES[codec as keyof typeof CODEC_DISPLAY_NAMES] ||
+ codec.toUpperCase(),
+ isPreferred: codec === "avc" || codec === "vp9",
+ };
+ }
+ }
+ return null;
+ }
+
+ async canEncodeCodec(codec: VideoCodec): Promise<boolean> {
+ if (typeof VideoEncoder === "undefined") return false;
+ try {
+ const testConfig = this.getEncoderConfig(codec);
+ const support = await VideoEncoder.isConfigSupported(testConfig);
+ return support.supported ?? false;
+ } catch {
+ return false;
+ }
+ }
+
+ clearCache(): void {
+ this.cachedMP4Codec = null;
+ this.cachedWebMCodec = null;
+ }
+
+ private async convert(
+ sourceBlob: Blob,
+ targetFormat: SupportedFormat,
+ options: ConversionOptions
+ ): Promise<Blob> {
+ const {
+ videoBitrate = 5_000_000,
+ audioBitrate = 128_000,
+ preferredVideoCodec,
+ audioCodec,
+ onProgress,
+ } = options;
+
+ const cache = targetFormat === "mp4" ? this.cachedMP4Codec : this.cachedWebMCodec;
+ let videoCodec: VideoCodec | null = cache;
+
+ if (!videoCodec) {
+ if (preferredVideoCodec && (await this.canEncodeCodec(preferredVideoCodec))) {
+ videoCodec = preferredVideoCodec;
+ } else {
+ const codecInfo = await this.detectBestCodec(targetFormat);
+ if (!codecInfo) {
+ throw new Error(
+ `Cannot convert to ${targetFormat.toUpperCase()}: no supported video codec.`
+ );
+ }
+ videoCodec = codecInfo.codec;
+ }
+ if (targetFormat === "mp4") this.cachedMP4Codec = videoCodec;
+ else this.cachedWebMCodec = videoCodec;
+ }
+
+ const finalAudioCodec = audioCodec || (targetFormat === "mp4" ? "aac" : "opus");
+
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(sourceBlob),
+ });
+
+ const outputFormat =
+ targetFormat === "mp4"
+ ? new Mp4OutputFormat({ fastStart: "in-memory" })
+ : new WebMOutputFormat();
+
+ const target = new BufferTarget();
+ const output = new Output({ format: outputFormat, target });
+
+ const conversion = await Conversion.init({
+ input,
+ output,
+ video: { codec: videoCodec, bitrate: videoBitrate },
+ audio: { codec: finalAudioCodec, bitrate: audioBitrate },
+ });
+
+ if (!conversion.isValid) {
+ const reasons = conversion.discardedTracks
+ .map((t) => `${t.track.type}: ${t.reason}`)
+ .join(", ");
+ throw new Error(`Conversion failed - ${reasons}`);
+ }
+
+ if (onProgress) conversion.onProgress = onProgress;
+
+ await conversion.execute();
+
+ if (!target.buffer) throw new Error("Conversion failed - no output buffer");
+
+ return new Blob([target.buffer], {
+ type: targetFormat === "mp4" ? "video/mp4" : "video/webm",
+ });
+ }
+
+ private getEncoderConfig(codec: VideoCodec): VideoEncoderConfig {
+ const baseConfig = { width: 1920, height: 1080, bitrate: 5_000_000 };
+ switch (codec) {
+ case "avc":
+ return { ...baseConfig, codec: "avc1.42E01E" };
+ case "hevc":
+ return { ...baseConfig, codec: "hev1.1.6.L93.B0" };
+ default:
+ return { ...baseConfig, codec };
+ }
+ }
+}
+
+export const videoConverter = new VideoConverter();
+
+export async function convertToMP4(blob: Blob, options?: ConversionOptions): Promise<Blob> {
+ return videoConverter.convertToMP4(blob, options);
+}
+
+export async function convertToWebM(blob: Blob, options?: ConversionOptions): Promise<Blob> {
+ return videoConverter.convertToWebM(blob, options);
+}
\ No newline at end of file
diff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoCropper.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoCropper.ts
new file mode 100644
index 0000000..0984cb0
--- /dev/null
+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoCropper.ts
@@ -0,0 +1,153 @@
+// @ts-nocheck
+import {
+ Input,
+ Output,
+ BlobSource,
+ BufferTarget,
+ Mp4OutputFormat,
+ WebMOutputFormat,
+ ALL_FORMATS,
+ Conversion,
+ type OutputFormat,
+} from "mediabunny";
+
+export interface CropOptions {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ outputFormat?: "mp4" | "webm";
+ videoBitrate?: number;
+ audioBitrate?: number;
+ onProgress?: (progress: number) => void;
+ verbose?: boolean;
+}
+
+export interface CropInfo {
+ originalWidth: number;
+ originalHeight: number;
+ croppedWidth: number;
+ croppedHeight: number;
+ cropRegion: {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ };
+}
+
+export class VideoCropper {
+ async crop(sourceBlob: Blob, options: CropOptions): Promise<Blob> {
+ const {
+ left,
+ top,
+ width,
+ height,
+ outputFormat,
+ videoBitrate,
+ audioBitrate,
+ onProgress,
+ } = options;
+
+ if (left < 0 || top < 0) throw new Error("Crop position cannot be negative");
+ if (width <= 0 || height <= 0) throw new Error("Crop dimensions must be positive");
+
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(sourceBlob),
+ });
+
+ const inputFormat = await input.getFormat();
+ const tracks = await input.getTracks();
+ const videoTrack = tracks.find((t) => t.type === "video");
+
+ if (!videoTrack || !videoTrack.isVideoTrack()) throw new Error("No video track found in input");
+
+ const originalWidth = videoTrack.displayWidth;
+ const originalHeight = videoTrack.displayHeight;
+
+ if (left + width > originalWidth || top + height > originalHeight) {
+ const clampedWidth = Math.min(width, originalWidth - left);
+ const clampedHeight = Math.min(height, originalHeight - top);
+ options.width = clampedWidth;
+ options.height = clampedHeight;
+ }
+
+ let format: OutputFormat;
+ const targetFormat =
+ outputFormat ||
+ (inputFormat.name.toLowerCase().includes("mp4") ? "mp4" : "webm");
+
+ format =
+ targetFormat === "mp4"
+ ? new Mp4OutputFormat({ fastStart: "in-memory" })
+ : new WebMOutputFormat();
+
+ const target = new BufferTarget();
+ const output = new Output({ format, target });
+
+ const conversion = await Conversion.init({
+ input,
+ output,
+ video: {
+ crop: { left, top, width, height },
+ ...(videoBitrate && { bitrate: videoBitrate }),
+ },
+ ...(audioBitrate && { audio: { bitrate: audioBitrate } }),
+ });
+
+ if (!conversion.isValid) {
+ const reasons = conversion.discardedTracks
+ .map((t) => `${t.track.type}: ${t.reason}`)
+ .join(", ");
+ throw new Error(`Cropping failed - ${reasons}`);
+ }
+
+ if (onProgress) conversion.onProgress = onProgress;
+
+ await conversion.execute();
+
+ if (!target.buffer) throw new Error("Cropping failed - no output buffer");
+
+ return new Blob([target.buffer], {
+ type: targetFormat === "mp4" ? "video/mp4" : "video/webm",
+ });
+ }
+
+ async getDimensions(blob: Blob): Promise<{
+ width: number;
+ height: number;
+ codedWidth: number;
+ codedHeight: number;
+ }> {
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(blob),
+ });
+
+ const tracks = await input.getTracks();
+ const videoTrack = tracks.find((t) => t.type === "video");
+
+ if (!videoTrack || !videoTrack.isVideoTrack()) throw new Error("No video track found");
+
+ return {
+ width: videoTrack.displayWidth,
+ height: videoTrack.displayHeight,
+ codedWidth: videoTrack.codedWidth,
+ codedHeight: videoTrack.codedHeight,
+ };
+ }
+}
+
+export const videoCropper = new VideoCropper();
+
+export async function cropVideo(
+ blob: Blob,
+ left: number,
+ top: number,
+ width: number,
+ height: number,
+ options?: Omit<CropOptions, "left" | "top" | "width" | "height">
+): Promise<Blob> {
+ return videoCropper.crop(blob, { left, top, width, height, ...options });
+}
\ No newline at end of file
diff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoCutter.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoCutter.ts
new file mode 100644
index 0000000..1d0b6c1
--- /dev/null
+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoCutter.ts
@@ -0,0 +1,111 @@
+// @ts-nocheck
+import {
+ Input,
+ BlobSource,
+ ALL_FORMATS,
+ Output,
+ BufferTarget,
+ Mp4OutputFormat,
+ QUALITY_HIGH,
+ VideoSampleSource,
+ AudioSampleSource,
+ VideoSampleSink,
+ AudioSampleSink,
+} from "mediabunny";
+
+export class VideoCutter {
+ async cut(sourceBlob, { cutStart, cutEnd, onProgress }) {
+ const total = await this.getDuration(sourceBlob);
+
+ const input = new Input({
+ source: new BlobSource(sourceBlob),
+ formats: ALL_FORMATS,
+ });
+
+ const outputTarget = new BufferTarget();
+ const output = new Output({
+ format: new Mp4OutputFormat({ fastStart: "in-memory" }),
+ target: outputTarget,
+ });
+
+ const videoTrack = await input.getPrimaryVideoTrack();
+ const audioTrack = await input.getPrimaryAudioTrack().catch(() => null);
+
+ const videoSource = new VideoSampleSource({
+ codec: "avc",
+ bitrate: QUALITY_HIGH,
+ sizeChangeBehavior: "passThrough",
+ });
+ output.addVideoTrack(videoSource);
+
+ let audioSource = null;
+ if (audioTrack) {
+ audioSource = new AudioSampleSource({
+ codec: "aac",
+ bitrate: QUALITY_HIGH,
+ });
+ output.addAudioTrack(audioSource);
+ }
+
+ await output.start();
+
+ let outPts = 0;
+ const totalSegments = [
+ [0, cutStart],
+ [cutEnd, total],
+ ];
+ let processedTime = 0;
+
+ const addSegment = async (start, end) => {
+ const segDur = end - start;
+ const baseTimestamp = outPts / 1_000_000;
+
+ const videoSink = new VideoSampleSink(videoTrack);
+ for await (const sample of videoSink.samples(start, end)) {
+ const adjusted = Math.max(0, baseTimestamp + (sample.timestamp - start));
+ sample.setTimestamp(adjusted);
+ await videoSource.add(sample);
+ sample.close();
+ processedTime += sample.duration ?? 1 / 30;
+ if (onProgress) onProgress(processedTime / total);
+ }
+
+ if (audioTrack && audioSource) {
+ const audioSink = new AudioSampleSink(audioTrack);
+ for await (const sample of audioSink.samples(start, end)) {
+ const adjusted = Math.max(0, baseTimestamp + (sample.timestamp - start));
+ sample.setTimestamp(adjusted);
+ await audioSource.add(sample);
+ sample.close();
+ processedTime += sample.duration ?? 0;
+ if (onProgress) onProgress(processedTime / total);
+ }
+ }
+
+ outPts += segDur * 1_000_000;
+ };
+
+ for (let i = 0; i < totalSegments.length; i++) {
+ const [start, end] = totalSegments[i];
+ await addSegment(start, end);
+ }
+
+ await output.finalize();
+
+ const blob = new Blob([outputTarget.buffer], { type: "video/mp4" });
+ if (onProgress) onProgress(1);
+ return blob;
+ }
+
+ getDuration(blob) {
+ return new Promise((res, rej) => {
+ const v = document.createElement("video");
+ v.src = URL.createObjectURL(blob);
+ v.onloadedmetadata = () => {
+ URL.revokeObjectURL(v.src);
+ res(v.duration);
+ };
+ v.onerror = () => rej(new Error("Failed to load video"));
+ });
+ }
+}
\ No newline at end of file
diff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoMuter.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoMuter.ts
new file mode 100644
index 0000000..cbc102f
--- /dev/null
+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoMuter.ts
@@ -0,0 +1,120 @@
+// @ts-nocheck
+import {
+ Input,
+ BlobSource,
+ Output,
+ BufferTarget,
+ Mp4OutputFormat,
+ VideoSampleSource,
+ VideoSampleSink,
+ AudioSampleSource,
+ AudioSample,
+ ALL_FORMATS,
+ QUALITY_HIGH,
+} from "mediabunny";
+
+export class VideoMuter {
+ async mute(
+ videoBlob,
+ {
+ muteStart = 0,
+ muteEnd = 0,
+ videoVolume = 1.0,
+ outputFormat = "mp4",
+ onProgress,
+ } = {}
+ ) {
+ const videoDuration = await this._getDuration(videoBlob);
+ const input = new Input({
+ source: new BlobSource(videoBlob),
+ formats: ALL_FORMATS,
+ });
+
+ const outputTarget = new BufferTarget();
+ const output = new Output({
+ format: new Mp4OutputFormat({ fastStart: "in-memory" }),
+ target: outputTarget,
+ });
+
+ const videoTrack = await input.getPrimaryVideoTrack();
+ const videoSink = new VideoSampleSink(videoTrack);
+ const videoSource = new VideoSampleSource({
+ codec: "avc",
+ bitrate: QUALITY_HIGH,
+ });
+ output.addVideoTrack(videoSource);
+
+ let decodedAudio = null;
+ try {
+ const buf = await videoBlob.arrayBuffer();
+ const ctx = new AudioContext();
+ decodedAudio = await ctx.decodeAudioData(buf);
+ } catch {}
+
+ const sr = decodedAudio?.sampleRate || 48000;
+ const mixBuffer = new Float32Array(Math.ceil(sr * videoDuration));
+
+ if (decodedAudio) {
+ const channelData = decodedAudio.getChannelData(0);
+ const muteStartSample = Math.floor(muteStart * sr);
+ const muteEndSample = Math.floor(muteEnd * sr);
+
+ for (let i = 0; i < channelData.length; i++) {
+ mixBuffer[i] =
+ i >= muteStartSample && i < muteEndSample ? 0 : channelData[i] * videoVolume;
+ }
+ } else {
+ return videoBlob;
+ }
+
+ const audioSource = new AudioSampleSource({
+ codec: "aac",
+ bitrate: 128000,
+ });
+ output.addAudioTrack(audioSource);
+
+ await output.start();
+ for await (const frame of videoSink.samples(0, videoDuration)) {
+ await videoSource.add(frame);
+ frame.close();
+ if (onProgress) onProgress(frame.timestamp / videoDuration);
+ }
+
+ const totalSamples = Math.floor(videoDuration * sr);
+ const chunkSize = sr * 2;
+ let written = 0;
+
+ while (written < totalSamples) {
+ const slice = mixBuffer.slice(written, written + chunkSize);
+ const dur = slice.length / sr;
+ const sample = new AudioSample({
+ data: slice,
+ format: "f32-planar",
+ numberOfChannels: 1,
+ sampleRate: sr,
+ timestamp: written / sr,
+ duration: dur,
+ });
+ await audioSource.add(sample);
+ sample.close();
+ written += chunkSize;
+ }
+
+ await output.finalize();
+ return new Blob([outputTarget.buffer], {
+ type: outputFormat === "webm" ? "video/webm" : "video/mp4",
+ });
+ }
+
+ async _getDuration(blob) {
+ return new Promise((resolve, reject) => {
+ const v = document.createElement("video");
+ v.src = URL.createObjectURL(blob);
+ v.onloadedmetadata = () => {
+ resolve(v.duration);
+ URL.revokeObjectURL(v.src);
+ };
+ v.onerror = reject;
+ });
+ }
+}
\ No newline at end of file
diff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoTrimmer.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoTrimmer.ts
new file mode 100644
index 0000000..8e0aecf
--- /dev/null
+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoTrimmer.ts
@@ -0,0 +1,124 @@
+// @ts-nocheck
+import {
+ Input,
+ Output,
+ BlobSource,
+ BufferTarget,
+ Mp4OutputFormat,
+ WebMOutputFormat,
+ ALL_FORMATS,
+ Conversion,
+ type OutputFormat,
+} from "mediabunny";
+
+export interface TrimOptions {
+ startTime: number;
+ endTime: number;
+ outputFormat?: "mp4" | "webm";
+ videoBitrate?: number;
+ audioBitrate?: number;
+ onProgress?: (progress: number) => void;
+}
+
+export interface TrimInfo {
+ originalDuration: number;
+ trimmedDuration: number;
+ startTime: number;
+ endTime: number;
+ format: string;
+}
+
+export class VideoTrimmer {
+ async trim(sourceBlob: Blob, options: TrimOptions): Promise<Blob> {
+ const { startTime, endTime, outputFormat, videoBitrate, audioBitrate, onProgress } = options;
+
+ if (startTime < 0) throw new Error("Start time cannot be negative");
+ if (endTime <= startTime) throw new Error("End time must be greater than start time");
+
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(sourceBlob),
+ });
+
+ const inputFormat = await input.getFormat();
+ const targetFormat =
+ outputFormat ||
+ (inputFormat.name.toLowerCase().includes("mp4") ? "mp4" : "webm");
+
+ const format: OutputFormat =
+ targetFormat === "mp4"
+ ? new Mp4OutputFormat({ fastStart: "in-memory" })
+ : new WebMOutputFormat();
+
+ const target = new BufferTarget();
+ const output = new Output({ format, target });
+
+ const conversion = await Conversion.init({
+ input,
+ output,
+ trim: { start: startTime, end: endTime },
+ ...(videoBitrate && { video: { bitrate: videoBitrate } }),
+ ...(audioBitrate && { audio: { bitrate: audioBitrate } }),
+ });
+
+ if (!conversion.isValid) {
+ const reasons = conversion.discardedTracks
+ .map((t) => `${t.track.type}: ${t.reason}`)
+ .join(", ");
+ throw new Error(`Trimming failed - ${reasons}`);
+ }
+
+ if (onProgress) conversion.onProgress = onProgress;
+
+ await conversion.execute();
+
+ if (!target.buffer) throw new Error("Trimming failed - no output buffer");
+
+ return new Blob([target.buffer], {
+ type: targetFormat === "mp4" ? "video/mp4" : "video/webm",
+ });
+ }
+
+ async getInfo(blob: Blob): Promise<{
+ format: string;
+ hasVideo: boolean;
+ hasAudio: boolean;
+ videoCodec?: string | null;
+ audioCodec?: string | null;
+ codedWidth?: number;
+ codedHeight?: number;
+ }> {
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(blob),
+ });
+
+ const format = await input.getFormat();
+ const tracks = await input.getTracks();
+ const videoTrack = tracks.find((t) => t.type === "video");
+ const audioTrack = tracks.find((t) => t.type === "audio");
+
+ return {
+ format: format.name,
+ hasVideo: !!videoTrack,
+ hasAudio: !!audioTrack,
+ videoCodec: videoTrack?.codec || null,
+ audioCodec: audioTrack?.codec || null,
+ ...(videoTrack?.isVideoTrack() && {
+ codedWidth: videoTrack.codedWidth,
+ codedHeight: videoTrack.codedHeight,
+ }),
+ };
+ }
+}
+
+export const videoTrimmer = new VideoTrimmer();
+
+export async function trimVideo(
+ blob: Blob,
+ startTime: number,
+ endTime: number,
+ options?: Omit<TrimOptions, "startTime" | "endTime">
+): Promise<Blob> {
+ return videoTrimmer.trim(blob, { startTime, endTime, ...options });
+}
\ No newline at end of file
diff --git a/src/pages/EditorWebCodecs/utils/addAudioToVideo.js b/src/pages/EditorWebCodecs/utils/addAudioToVideo.js
new file mode 100644
index 0000000..f4df020
--- /dev/null
+++ b/src/pages/EditorWebCodecs/utils/addAudioToVideo.js
@@ -0,0 +1,54 @@
+import { VideoAudioMixer } from "../mediabunny/lib/videoAudioMixer.ts";
+
+async function ensureBlob(input, mimeType = "video/webm") {
+ if (input instanceof Blob) return input;
+
+ if (input && typeof input === "object" && typeof input.size === "number") {
+ if (typeof input.arrayBuffer === "function") {
+ try {
+ const buffer = await input.arrayBuffer();
+ return new Blob([buffer], { type: input.type || mimeType });
+ } catch {}
+ }
+
+ if (typeof input.slice === "function") {
+ try {
+ const sliced = input.slice(0, input.size, input.type || mimeType);
+ if (sliced instanceof Blob) return sliced;
+ } catch {}
+ }
+ }
+
+ throw new Error(
+ `Cannot convert to Blob: ${typeof input}, constructor: ${
+ input?.constructor?.name
+ }`
+ );
+}
+
+async function addAudioToVideo(
+ ffmpeg,
+ videoBlob,
+ audioBlob,
+ videoDuration,
+ audioVolume = 1.0,
+ replaceAudio = false,
+ onProgress
+) {
+ const video = await ensureBlob(videoBlob, "video/webm");
+ const audio = await ensureBlob(audioBlob, "audio/webm");
+
+ const mixer = new VideoAudioMixer();
+ return mixer.addAudio(video, audio, {
+ mode: replaceAudio ? "replace" : "mix",
+ videoVolume: replaceAudio ? 0 : 0.7,
+ audioVolume,
+ loop: false,
+ outputFormat: "webm",
+ videoBitrate: 5_000_000,
+ audioBitrate: 128_000,
+ onProgress,
+ });
+}
+
+export default addAudioToVideo;
diff --git a/src/pages/EditorFallback/utils/blobToArrayBuffer.js b/src/pages/EditorWebCodecs/utils/blobToArrayBuffer.js
similarity index 100%
rename from src/pages/EditorFallback/utils/blobToArrayBuffer.js
rename to src/pages/EditorWebCodecs/utils/blobToArrayBuffer.js
diff --git a/src/pages/EditorWebCodecs/utils/convertMp4ToWebm.js b/src/pages/EditorWebCodecs/utils/convertMp4ToWebm.js
new file mode 100644
index 0000000..6c2959e
--- /dev/null
+++ b/src/pages/EditorWebCodecs/utils/convertMp4ToWebm.js
@@ -0,0 +1,13 @@
+import { VideoConverter } from "../mediabunny/lib/videoConverter.ts";
+
+async function convertMp4ToWebm(mp4Blob, onProgress = () => {}) {
+ const converter = new VideoConverter();
+
+ return converter.convertToWebM(mp4Blob, {
+ videoBitrate: 5_000_000,
+ audioBitrate: 128_000,
+ onProgress,
+ });
+}
+
+export default convertMp4ToWebm;
diff --git a/src/pages/EditorWebCodecs/utils/convertWebmToMp4.js b/src/pages/EditorWebCodecs/utils/convertWebmToMp4.js
new file mode 100644
index 0000000..76fc542
--- /dev/null
+++ b/src/pages/EditorWebCodecs/utils/convertWebmToMp4.js
@@ -0,0 +1,13 @@
+import { VideoConverter } from "../mediabunny/lib/videoConverter.ts";
+
+async function convertWebmToMp4(webmBlob, onProgress = () => {}) {
+ const converter = new VideoConverter();
+
+ return converter.convertToMP4(webmBlob, {
+ videoBitrate: 5_000_000,
+ audioBitrate: 128_000,
+ onProgress,
+ });
+}
+
+export default convertWebmToMp4;
diff --git a/src/pages/EditorWebCodecs/utils/cropVideo.js b/src/pages/EditorWebCodecs/utils/cropVideo.js
new file mode 100644
index 0000000..c6f135e
--- /dev/null
+++ b/src/pages/EditorWebCodecs/utils/cropVideo.js
@@ -0,0 +1,23 @@
+import { VideoCropper } from "../mediabunny/lib/videoCropper.ts";
+
+async function cropVideo(
+ ffmpeg,
+ videoBlob,
+ cropOptions,
+ onProgress = () => {}
+) {
+ const cropper = new VideoCropper();
+
+ return cropper.crop(videoBlob, {
+ left: cropOptions.x,
+ top: cropOptions.y,
+ width: cropOptions.width,
+ height: cropOptions.height,
+ outputFormat: "webm",
+ videoBitrate: 5_000_000,
+ audioBitrate: 128_000,
+ onProgress,
+ });
+}
+
+export default cropVideo;
diff --git a/src/pages/EditorWebCodecs/utils/cutVideo.js b/src/pages/EditorWebCodecs/utils/cutVideo.js
new file mode 100644
index 0000000..08f6a7e
--- /dev/null
+++ b/src/pages/EditorWebCodecs/utils/cutVideo.js
@@ -0,0 +1,39 @@
+import { VideoTrimmer } from "../mediabunny/lib/videoTrimmer.ts";
+import { VideoCutter } from "../mediabunny/lib/videoCutter.ts";
+
+export default async function cutVideo(
+ ffmpeg,
+ videoBlob,
+ startTime,
+ endTime,
+ cut,
+ duration,
+ encode,
+ onProgress = () => {}
+) {
+ let result;
+
+ if (cut) {
+ const cutter = new VideoCutter();
+ result = await cutter.cut(videoBlob, {
+ cutStart: startTime,
+ cutEnd: endTime,
+ outputFormat: "mp4",
+ videoBitrate: 5_000_000,
+ audioBitrate: 128_000,
+ onProgress,
+ });
+ } else {
+ const trimmer = new VideoTrimmer();
+ result = await trimmer.trim(videoBlob, {
+ startTime,
+ endTime,
+ outputFormat: "mp4",
+ videoBitrate: 5_000_000,
+ audioBitrate: 128_000,
+ onProgress,
+ });
+ }
+
+ return result;
+}
diff --git a/src/pages/EditorWebCodecs/utils/getFrame.js b/src/pages/EditorWebCodecs/utils/getFrame.js
new file mode 100644
index 0000000..f93241b
--- /dev/null
+++ b/src/pages/EditorWebCodecs/utils/getFrame.js
@@ -0,0 +1,36 @@
+async function getFrame(ffmpeg, videoBlob, time) {
+ return new Promise((resolve, reject) => {
+ const video = document.createElement("video");
+ const canvas = document.createElement("canvas");
+ const ctx = canvas.getContext("2d");
+
+ video.addEventListener("loadedmetadata", () => {
+ canvas.width = video.videoWidth;
+ canvas.height = video.videoHeight;
+ video.currentTime = time;
+ });
+
+ video.addEventListener("seeked", () => {
+ try {
+ ctx.drawImage(video, 0, 0);
+ canvas.toBlob((blob) => {
+ URL.revokeObjectURL(video.src);
+ if (blob) resolve(blob);
+ else reject(new Error("Failed to create blob from canvas"));
+ }, "image/png");
+ } catch (error) {
+ URL.revokeObjectURL(video.src);
+ reject(error);
+ }
+ });
+
+ video.addEventListener("error", (e) => {
+ URL.revokeObjectURL(video.src);
+ reject(new Error(`Video error: ${e.message || "Unknown error"}`));
+ });
+
+ video.src = URL.createObjectURL(videoBlob);
+ });
+}
+
+export default getFrame;
diff --git a/src/pages/EditorWebCodecs/utils/hasAudio.js b/src/pages/EditorWebCodecs/utils/hasAudio.js
new file mode 100644
index 0000000..e90da9f
--- /dev/null
+++ b/src/pages/EditorWebCodecs/utils/hasAudio.js
@@ -0,0 +1,59 @@
+async function hasAudio(ffmpeg, videoBlob) {
+ return new Promise((resolve, reject) => {
+ const video = document.createElement("video");
+ video.muted = true;
+
+ video.addEventListener("loadedmetadata", () => {
+ if (typeof video.mozHasAudio !== "undefined") {
+ const result = video.mozHasAudio;
+ URL.revokeObjectURL(video.src);
+ resolve(result);
+ return;
+ }
+
+ if (typeof video.webkitAudioDecodedByteCount !== "undefined") {
+ const result = video.webkitAudioDecodedByteCount > 0;
+ URL.revokeObjectURL(video.src);
+ resolve(result);
+ return;
+ }
+
+ const audioContext = new (window.AudioContext ||
+ window.webkitAudioContext)();
+
+ video
+ .play()
+ .then(() => {
+ const source = audioContext.createMediaElementSource(video);
+ const analyser = audioContext.createAnalyser();
+ source.connect(analyser);
+
+ const dataArray = new Uint8Array(analyser.frequencyBinCount);
+ analyser.getByteFrequencyData(dataArray);
+
+ const hasAudioData = dataArray.some((v) => v > 0);
+
+ video.pause();
+ URL.revokeObjectURL(video.src);
+ audioContext.close();
+
+ resolve(hasAudioData);
+ })
+ .catch(() => {
+ URL.revokeObjectURL(video.src);
+ audioContext.close();
+ resolve(true);
+ });
+ });
+
+ video.addEventListener("error", (e) => {
+ URL.revokeObjectURL(video.src);
+ reject(new Error(`Video error: ${e.message || "Unknown error"}`));
+ });
+
+ video.src = URL.createObjectURL(videoBlob);
+ video.load();
+ });
+}
+
+export default hasAudio;
diff --git a/src/pages/EditorWebCodecs/utils/muteVideo.js b/src/pages/EditorWebCodecs/utils/muteVideo.js
new file mode 100644
index 0000000..0fe0fc2
--- /dev/null
+++ b/src/pages/EditorWebCodecs/utils/muteVideo.js
@@ -0,0 +1,23 @@
+import { VideoMuter } from "../mediabunny/lib/videoMuter.ts";
+
+async function muteVideo(
+ ffmpeg,
+ videoBlob,
+ startTime,
+ endTime,
+ duration,
+ onProgress = () => {}
+) {
+ const muter = new VideoMuter();
+
+ return muter.mute(videoBlob, {
+ muteStart: startTime,
+ muteEnd: endTime,
+ outputFormat: "webm",
+ videoBitrate: 5_000_000,
+ audioBitrate: 128_000,
+ onProgress,
+ });
+}
+
+export default muteVideo;
diff --git a/src/pages/EditorWebCodecs/utils/reencodeVideo.js b/src/pages/EditorWebCodecs/utils/reencodeVideo.js
new file mode 100644
index 0000000..7b7bbde
--- /dev/null
+++ b/src/pages/EditorWebCodecs/utils/reencodeVideo.js
@@ -0,0 +1,18 @@
+import { VideoConverter } from "../mediabunny/lib/videoConverter.ts";
+
+async function reencodeVideo(
+ ffmpeg,
+ videoBlob,
+ duration,
+ onProgress = () => {}
+) {
+ const converter = new VideoConverter();
+
+ return converter.convertToMP4(videoBlob, {
+ videoBitrate: 5_000_000,
+ audioBitrate: 128_000,
+ onProgress,
+ });
+}
+
+export default reencodeVideo;
diff --git a/src/pages/EditorWebCodecs/utils/toGIF.js b/src/pages/EditorWebCodecs/utils/toGIF.js
new file mode 100644
index 0000000..28abb35
--- /dev/null
+++ b/src/pages/EditorWebCodecs/utils/toGIF.js
@@ -0,0 +1,83 @@
+import GIF from "gif.js";
+
+async function toGIF(ffmpeg, videoBlob, onProgress = () => {}) {
+ return new Promise((resolve, reject) => {
+ const video = document.createElement("video");
+ const canvas = document.createElement("canvas");
+ const ctx = canvas.getContext("2d");
+
+ video.addEventListener("loadedmetadata", async () => {
+ try {
+ const duration = video.duration;
+ const width = 540;
+ const height = Math.round(
+ (video.videoHeight / video.videoWidth) * width
+ );
+ const fps = 12;
+ const quality = 5;
+
+ canvas.width = width;
+ canvas.height = height;
+
+ const gif = new GIF({
+ workers: 2,
+ quality,
+ width,
+ height,
+ workerScript: "/assets/vendor/gif.js/gif.worker.js",
+ });
+
+ const frameInterval = 1 / fps;
+ const totalFrames = Math.floor(duration * fps);
+ let frameCount = 0;
+
+ const captureFrame = (time) =>
+ new Promise((resolveFrame) => {
+ const seekHandler = () => {
+ video.removeEventListener("seeked", seekHandler);
+ ctx.drawImage(video, 0, 0, width, height);
+ gif.addFrame(canvas, {
+ copy: true,
+ delay: Math.round(1000 / fps),
+ });
+ frameCount++;
+ onProgress(frameCount / totalFrames);
+ resolveFrame();
+ };
+ video.addEventListener("seeked", seekHandler);
+ video.currentTime = time;
+ });
+
+ for (let i = 0; i < totalFrames; i++) {
+ const time = Math.min(i * frameInterval, duration - 0.001);
+ await captureFrame(time);
+ }
+
+ gif.on("finished", (blob) => {
+ URL.revokeObjectURL(video.src);
+ video.remove();
+ onProgress(1);
+ resolve(blob);
+ });
+
+ gif.on("progress", (progress) => onProgress(progress));
+
+ gif.render();
+ } catch (error) {
+ URL.revokeObjectURL(video.src);
+ video.remove();
+ reject(error);
+ }
+ });
+
+ video.addEventListener("error", (e) => {
+ URL.revokeObjectURL(video.src);
+ reject(new Error(`Video error: ${e.message || "Unknown error"}`));
+ });
+
+ video.src = URL.createObjectURL(videoBlob);
+ video.load();
+ });
+}
+
+export default toGIF;
diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsx
index e18a83c..ef68eb4 100644
--- a/src/pages/Recorder/Recorder.jsx
+++ b/src/pages/Recorder/Recorder.jsx
@@ -81,13 +81,14 @@ const Recorder = () => {
async function saveChunk(e, i) {
const ts = e.timecode ?? 0;
- if (
- savedCount.current > 0 &&
- ts === lastTimecode.current &&
- e.data.size === lastSize.current
- ) {
- return false;
- }
+ // FLAG: disabled duplicate chunk check due to issues with some devices
+ // if (
+ // savedCount.current > 0 &&
+ // ts === lastTimecode.current &&
+ // e.data.size === lastSize.current
+ // ) {
+ // return false;
+ // }
if (!(await canFitChunk(e.data.size))) {
lowStorageAbort.current = true;
@@ -194,7 +195,7 @@ const Recorder = () => {
return;
}
- chunksStore.clear();
+ await chunksStore.clear();
lastTimecode.current = 0;
lastSize.current = 0;
@@ -244,6 +245,9 @@ const Recorder = () => {
};
recorder.current.onstop = async () => {
+ try {
+ recorder.current?.requestData();
+ } catch {}
if (isRestarting.current) return;
await waitForDrain();
if (!sentLast.current) {
@@ -253,6 +257,16 @@ const Recorder = () => {
}
};
+ if (helperAudioStream.current) {
+ const track = helperAudioStream.current.getAudioTracks()[0];
+ if (track) {
+ track.onended = () => {
+ chrome.storage.local.set({ recording: false });
+ sendStopRecording();
+ };
+ }
+ }
+
const checkMaxMemory = () => {
try {
navigator.storage.estimate().then(({ usage = 0, quota = 0 }) => {
@@ -275,7 +289,7 @@ const Recorder = () => {
}
};
- recorder.current.ondataavailable = (e) => {
+ recorder.current.ondataavailable = async (e) => {
if (!e || !e.data || !e.data.size) {
if (recorder.current && recorder.current.state === "inactive") {
chrome.storage.local.set({
@@ -288,9 +302,7 @@ const Recorder = () => {
return;
}
- if (lowStorageAbort.current) {
- return;
- }
+ if (lowStorageAbort.current) return;
if (!hasChunks.current) {
hasChunks.current = true;
@@ -298,7 +310,25 @@ const Recorder = () => {
lastSize.current = e.data.size;
}
+ // push chunk
pending.current.push(e);
+ pendingBytes.current += e.data.size;
+
+ if (pendingBytes.current > MAX_PENDING_BYTES) {
+ try {
+ if (recorder.current.state !== "paused") {
+ recorder.current.pause();
+ }
+ await drainQueue();
+ if (recorder.current.state === "paused") {
+ recorder.current.resume();
+ }
+ } catch {
+ // fallback: force drain without pausing
+ await drainQueue();
+ }
+ }
+
void drainQueue();
};
@@ -332,14 +362,19 @@ const Recorder = () => {
async function stopRecording() {
isFinishing.current = true;
- if (recorder.current) {
- try {
- recorder.current.requestData();
- } catch {}
- recorder.current.stop();
- await waitForDrain();
- recorder.current = null;
- }
+
+ try {
+ recorder.current?.requestData();
+ } catch {}
+
+ try {
+ if (recorder.current && recorder.current.state !== "inactive") {
+ recorder.current.stop();
+ }
+ } catch {}
+
+ await waitForDrain();
+ recorder.current = null;
if (liveStream.current) {
liveStream.current.getTracks().forEach((t) => t.stop());
@@ -646,6 +681,23 @@ const Recorder = () => {
tabID.current = streamId;
};
+ // FLAG: add protection on page close
+ useEffect(() => {
+ const handleClose = () => {
+ try {
+ stopRecording();
+ } catch {}
+ };
+
+ window.addEventListener("pagehide", handleClose);
+ window.addEventListener("beforeunload", handleClose);
+
+ return () => {
+ window.removeEventListener("pagehide", handleClose);
+ window.removeEventListener("beforeunload", handleClose);
+ };
+ }, []);
+
const onMessage = useCallback(
(request, sender, sendResponse) => {
if (request.type === "loaded") {
diff --git a/src/pages/RecorderOffscreen/RecorderOffscreen.jsx b/src/pages/RecorderOffscreen/RecorderOffscreen.jsx
index 61aee7f..b1d3731 100644
--- a/src/pages/RecorderOffscreen/RecorderOffscreen.jsx
+++ b/src/pages/RecorderOffscreen/RecorderOffscreen.jsx
@@ -46,7 +46,6 @@ const RecorderOffscreen = () => {
const fps = useRef(30);
const backupRef = useRef(false);
- // FLAG: New stuff
const pending = useRef([]);
const draining = useRef(false);
const lowStorageAbort = useRef(false);
diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsx
index fff7100..69691ea 100644
--- a/src/pages/Region/Recorder.jsx
+++ b/src/pages/Region/Recorder.jsx
@@ -85,13 +85,14 @@ const Recorder = () => {
async function saveChunk(e, i) {
const ts = e.timecode ?? 0;
- if (
- savedCount.current > 0 &&
- ts === lastTimecode.current &&
- e.data.size === lastSize.current
- ) {
- return false;
- }
+ // FLAG: disabled duplicate chunk check due to issues with some devices
+ // if (
+ // savedCount.current > 0 &&
+ // ts === lastTimecode.current &&
+ // e.data.size === lastSize.current
+ // ) {
+ // return false;
+ // }
if (!(await canFitChunk(e.data.size))) {
lowStorageAbort.current = true;
@@ -251,7 +252,7 @@ const Recorder = () => {
return;
}
- chunksStore.clear();
+ await chunksStore.clear();
try {
const { qualityValue } = await chrome.storage.local.get(["qualityValue"]);
@@ -360,21 +361,23 @@ const Recorder = () => {
};
recorder.current.onstop = async () => {
+ try {
+ recorder.current.requestData();
+ } catch {}
+
regionRef.current = false;
recordingRef.current = false;
+
if (isRestarting.current) return;
+
await waitForDrain();
- if (!isDismissing.current) {
- if (!sentLast.current) {
- sentLast.current = true;
- isFinished.current = true;
- chrome.runtime.sendMessage({ type: "video-ready" });
- isFinishing.current = false;
- // Reload this iframe
- window.location.reload();
- }
- } else {
- isDismissing.current = false;
+
+ if (!sentLast.current) {
+ sentLast.current = true;
+ isFinished.current = true;
+ chrome.runtime.sendMessage({ type: "video-ready" });
+ isFinishing.current = false;
+ window.location.reload();
}
};
@@ -408,7 +411,7 @@ const Recorder = () => {
}
};
- recorder.current.ondataavailable = (e) => {
+ recorder.current.ondataavailable = async (e) => {
if (!e || !e.data || !e.data.size) {
if (recorder.current && recorder.current.state === "inactive") {
chrome.storage.local.set({
@@ -433,6 +436,15 @@ const Recorder = () => {
pending.current.push(e);
pendingBytes.current += e.data.size;
+
+ if (pendingBytes.current > MAX_PENDING_BYTES) {
+ try {
+ recorder.current.pause();
+ await drainQueue();
+ recorder.current.resume();
+ } catch {}
+ }
+
void drainQueue();
};
@@ -455,6 +467,20 @@ const Recorder = () => {
chrome.runtime.sendMessage({ type: "stop-recording-tab" });
};
+ const vTrack = liveStream.current.getVideoTracks()[0];
+ if (vTrack) {
+ vTrack.oninactive = () => {
+ chrome.runtime.sendMessage({ type: "stop-recording-tab" });
+ };
+ }
+
+ const aTrack = helperAudioStream.current?.getAudioTracks()[0];
+ if (aTrack) {
+ aTrack.oninactive = () => {
+ chrome.runtime.sendMessage({ type: "stop-recording-tab" });
+ };
+ }
+
helperVideoStream.current.getVideoTracks()[0].onended = () => {
regionRef.current = false;
chrome.storage.local.set({
@@ -474,7 +500,13 @@ const Recorder = () => {
try {
recorder.current.requestData();
} catch {}
- recorder.current.stop();
+
+ try {
+ if (recorder.current.state !== "inactive") {
+ recorder.current.stop();
+ }
+ } catch {}
+
await waitForDrain();
recorder.current = null;
}
diff --git a/src/pages/Sandbox/Sandbox.jsx b/src/pages/Sandbox/Sandbox.jsx
index a45e3c9..42cc895 100644
--- a/src/pages/Sandbox/Sandbox.jsx
+++ b/src/pages/Sandbox/Sandbox.jsx
@@ -41,6 +41,7 @@ const Sandbox = () => {
useEffect(() => {
if (!contentState.blob || !contentState.ffmpeg) return;
if (contentState.frame) return;
+ // Frame extraction now works in fallback mode using Canvas API
contentState.getFrame();
}, [contentState.blob, contentState.ffmpeg]);
@@ -109,6 +110,21 @@ const Sandbox = () => {
});
}, []);
+ // Regenerate frame when entering crop mode to reflect current blob
+ useEffect(() => {
+ if (
+ contentState.mode === "crop" &&
+ contentState.getFrame &&
+ contentState.blob &&
+ contentState.ffmpeg
+ ) {
+ // Small delay to ensure state updates have propagated
+ setTimeout(() => {
+ contentState.getFrame();
+ }, 50);
+ }
+ }, [contentState.mode]);
+
return (
<div ref={parentRef}>
<Modal />
diff --git a/src/pages/Sandbox/components/editor/CropperWrap.jsx b/src/pages/Sandbox/components/editor/CropperWrap.jsx
index fb098ce..e930253 100644
--- a/src/pages/Sandbox/components/editor/CropperWrap.jsx
+++ b/src/pages/Sandbox/components/editor/CropperWrap.jsx
@@ -80,8 +80,8 @@ const CropperWrap = () => {
grid: true,
}}
defaultSize={{
- width: contentState.width,
- height: contentState.height,
+ width: contentState.width || undefined,
+ height: contentState.height || undefined,
}}
backgroundWrapperClassName="CropperBackgroundWrapper"
width={contentState.width}
diff --git a/src/pages/Sandbox/context/ContentState.jsx b/src/pages/Sandbox/context/ContentState.jsx
index 7c1ca37..073f57d 100644
--- a/src/pages/Sandbox/context/ContentState.jsx
+++ b/src/pages/Sandbox/context/ContentState.jsx
@@ -79,6 +79,7 @@ const ContentState = (props) => {
hasBeenEdited: false,
dragInteracted: false,
noffmpeg: false,
+ processingProgress: 0, // Progress percentage (0-100) for current operation
openModal: null,
rawBlob: null,
override: false,
@@ -86,6 +87,7 @@ const ContentState = (props) => {
chunkCount: 0,
chunkIndex: 0,
bannerSupport: false,
+ backupBlob: null,
};
const [contentState, setContentState] = useState(defaultState);
@@ -150,6 +152,31 @@ const ContentState = (props) => {
}
}, [contentState.saved]);
+ const createBackup = () => {
+ setContentState((prev) => ({
+ ...prev,
+ backupBlob: prev.blob,
+ }));
+ };
+
+ const restoreBackup = () => {
+ setContentState((prev) => ({
+ ...prev,
+ blob: prev.backupBlob || prev.blob,
+ mode: "player",
+ start: 0,
+ end: 1,
+ backupBlob: null,
+ }));
+ };
+
+ const clearBackup = () => {
+ setContentState((prev) => ({
+ ...prev,
+ backupBlob: null,
+ }));
+ };
+
const addToHistory = useCallback(() => {
setContentState((prevState) => ({
...prevState,
@@ -266,8 +293,8 @@ const ContentState = (props) => {
blob,
recordingDuration,
async (fixedWebm) => {
+ // Skip conversion only if Chrome is outdated or recording exceeds edit limit
if (
- contentStateRef.current.fallback ||
contentStateRef.current.updateChrome ||
contentStateRef.current.noffmpeg ||
(contentStateRef.current.duration >
@@ -301,8 +328,8 @@ const ContentState = (props) => {
type: "video/webm; codecs=vp8, opus",
});
+ // Skip conversion only if Chrome is outdated or recording exceeds edit limit
if (
- contentStateRef.current.fallback ||
contentStateRef.current.updateChrome ||
contentStateRef.current.noffmpeg ||
(contentStateRef.current.duration >
@@ -331,8 +358,8 @@ const ContentState = (props) => {
}
} else {
/// Skip fixing duration
+ // Skip conversion only if Chrome is outdated or recording exceeds edit limit
if (
- contentStateRef.current.fallback ||
contentStateRef.current.updateChrome ||
contentStateRef.current.noffmpeg ||
(contentStateRef.current.duration >
@@ -403,7 +430,6 @@ const ContentState = (props) => {
await Promise.all(
chunks.map(async (chunk) => {
if (contentStateRef.current.chunkIndex >= chunkCount.current) {
- console.warn("Too many chunks received");
return; // Skip processing
}
@@ -496,32 +522,73 @@ const ContentState = (props) => {
setContentState((prevContentState) => ({
...prevContentState,
fallback: true,
+ noffmpeg: false, // Pretending FFmpeg is loaded (using Mediabunny)
isFfmpegRunning: false,
- noffmpeg: true,
- ffmpegLoaded: true,
- ffmpeg: true,
+ editLimit: 3600, // Set high edit limit (1 hour) for recovery mode
}));
- buildBlobFromChunks();
+ buildBlobFromChunks()
+ .then(() => {
+ sendResponse({ status: "ok" });
+ })
+ .catch((error) => {
+ sendResponse({ status: "error", error: error.message });
+ });
+
+ return true; // Keep message port open for async response
} else if (message.type === "large-recording") {
setContentState((prevContentState) => ({
...prevContentState,
+ noffmpeg: false,
isFfmpegRunning: false,
- noffmpeg: true,
- ffmpegLoaded: true,
- ffmpeg: true,
+ editLimit: 0,
}));
- buildBlobFromChunks();
+ buildBlobFromChunks()
+ .then(() => {
+ sendResponse({ status: "ok" });
+ })
+ .catch((error) => {
+ sendResponse({ status: "error", error: error.message });
+ });
+
+ return true; // Keep message port open for async response
} else if (message.type === "fallback-recording") {
setContentState((prevContentState) => ({
...prevContentState,
fallback: true,
+ noffmpeg: false,
isFfmpegRunning: false,
- noffmpeg: true,
- ffmpegLoaded: true,
- ffmpeg: true,
+ editLimit: 3600,
}));
+
+ buildBlobFromChunks()
+ .then(() => {
+ sendResponse({ status: "ok" });
+ })
+ .catch((error) => {
+ sendResponse({ status: "error", error: error.message });
+ });
+
+ return true;
+ } else if (message.type === "viewer-recording") {
+ setContentState((prevContentState) => ({
+ ...prevContentState,
+ fallback: true,
+ noffmpeg: true, // No FFmpeg
+ isFfmpegRunning: false,
+ editLimit: 0, // No editing allowed
+ }));
+
+ buildBlobFromChunks()
+ .then(() => {
+ sendResponse({ status: "ok" });
+ })
+ .catch((error) => {
+ sendResponse({ status: "error", error: error.message });
+ });
+
+ return true;
} else if (message.type === "banner-support") {
setContentState((prevContentState) => ({
...prevContentState,
@@ -553,12 +620,27 @@ const ContentState = (props) => {
const onMessage = async (event) => {
if (event.data.type === "updated-blob") {
const base64 = event.data.base64;
- const blob = new Blob([base64ToUint8Array(base64)], {
- type: "video/mp4",
- });
+ // const blob = new Blob([base64ToUint8Array(base64)], {
+ // type: "video/mp4",
+ // });
+ const blob = base64ToUint8Array(base64);
+
+ const wasCropping = contentState.cropping;
+ const isTopLevel = event.data.topLevel === true;
+ const isFromAudio = event.data.fromAudio === true;
+
+ if (isFromAudio) {
+ sendMessage({
+ type: "reencode-video",
+ blob,
+ duration: contentState.duration,
+ topLevel: isTopLevel,
+ });
+ return;
+ }
- setContentState((prevContentState) => ({
- ...prevContentState,
+ setContentState((prev) => ({
+ ...prev,
blob: blob,
mp4ready: true,
hasBeenEdited: true,
@@ -568,19 +650,24 @@ const ContentState = (props) => {
cutting: false,
muting: false,
cropping: false,
+ processingProgress: 0,
+ hasTempChanges: !isTopLevel,
+
+ ...(prev.fromCropper && { mode: "player", fromCropper: false }),
+ ...(prev.fromAudio && { mode: "player", fromAudio: false }),
}));
- // Get duration of video blob
const video = document.createElement("video");
video.preload = "metadata";
video.onloadedmetadata = async () => {
- setContentState((prevState) => ({
- ...prevState,
+ setContentState((prev) => ({
+ ...prev,
duration: video.duration,
width: video.videoWidth,
height: video.videoHeight,
start: 0,
end: 1,
+ ...(wasCropping && { top: 0, left: 0 }),
}));
if (event.data.addToHistory) {
@@ -590,20 +677,21 @@ const ContentState = (props) => {
URL.revokeObjectURL(video.src);
video.remove();
};
+
video.src = URL.createObjectURL(blob);
- // Check if originalBlob is null, if so, set it to the blob
- if (!contentState.originalBlob) {
- setContentState((prevContentState) => ({
- ...prevContentState,
+ if (!contentState.originalBlob && isTopLevel) {
+ setContentState((prev) => ({
+ ...prev,
originalBlob: blob,
}));
}
} else if (event.data.type === "download-mp4") {
const base64 = event.data.base64;
- const blob = new Blob([base64ToUint8Array(base64)], {
- type: "video/mp4",
- });
+ // const blob = new Blob([base64ToUint8Array(base64)], {
+ // type: "video/mp4",
+ // });
+ const blob = base64ToUint8Array(base64);
// Download the blob
const url = URL.createObjectURL(blob);
requestDownload(url, ".mp4");
@@ -615,9 +703,10 @@ const ContentState = (props) => {
}));
} else if (event.data.type === "download-gif") {
const base64 = event.data.base64;
- const blob = new Blob([base64ToUint8Array(base64)], {
- type: "image/gif",
- });
+ // const blob = new Blob([base64ToUint8Array(base64)], {
+ // type: "image/gif",
+ // });
+ const blob = base64ToUint8Array(base64);
// Download the blob
const url = URL.createObjectURL(blob);
requestDownload(url, ".gif");
@@ -668,9 +757,42 @@ const ContentState = (props) => {
} else if (event.data.type === "crop-update") {
setContentState((prevContentState) => ({
...prevContentState,
- mode: "player",
+ mode: "crop",
+ cropping: false,
+ isFfmpegRunning: false,
+ processingProgress: 0,
start: 0,
end: 1,
+ fromCropper: false,
+ }));
+
+ setTimeout(() => {
+ if (contentState.getFrame) {
+ contentState.getFrame();
+ }
+ }, 100);
+ } else if (event.data.type === "ffmpeg-progress") {
+ const pct = Math.min(100, Math.max(0, Math.round(event.data.progress)));
+
+ setContentState((prevContentState) => ({
+ ...prevContentState,
+ processingProgress: pct,
+ }));
+ } else if (event.data.type === "download-webm") {
+ const base64 = event.data.base64;
+ // const blob = new Blob([base64ToUint8Array(base64)], {
+ // type: "video/webm",
+ // });
+ const blob = base64ToUint8Array(base64);
+
+ const url = URL.createObjectURL(blob);
+ await requestDownload(url, ".webm");
+
+ setContentState((prevState) => ({
+ ...prevState,
+ saved: true,
+ isFfmpegRunning: false,
+ downloadingWEBM: false,
}));
}
};
@@ -686,15 +808,19 @@ const ContentState = (props) => {
};
const getBlob = async () => {
+ // Skip conversion only if Chrome is outdated or recording exceeds edit limit
if (
- contentState.fallback ||
contentState.noffmpeg ||
(contentState.duration > contentState.editLimit && !contentState.override)
- )
+ ) {
return;
- const webmVideo = new Blob([base64ToUint8Array(contentState.base64)], {
- type: "video/webm",
- });
+ }
+
+ // const webmVideo = new Blob([base64ToUint8Array(contentState.base64)], {
+ // type: "video/webm",
+ // });
+
+ const webmVideo = base64ToUint8Array(contentState.base64);
setContentState((prevState) => ({
...prevState,
@@ -708,7 +834,16 @@ const ContentState = (props) => {
!contentState.updateChrome &&
(contentState.duration <= contentState.editLimit || contentState.override)
) {
- sendMessage({ type: "base64-to-blob", base64: contentState.base64 });
+ // Set isFfmpegRunning to true when starting conversion
+ setContentState((prevState) => ({
+ ...prevState,
+ isFfmpegRunning: true,
+ }));
+ sendMessage({
+ type: "base64-to-blob",
+ base64: contentState.base64,
+ topLevel: true,
+ });
}
chrome.runtime.sendMessage({ type: "recording-complete" });
@@ -743,18 +878,22 @@ const ContentState = (props) => {
)
return;
- setContentState((prevState) => ({
- ...prevState,
+ const sourceBlob = videoBlob || contentState.blob || contentState.webm;
+
+ setContentState((prev) => ({
+ ...prev,
isFfmpegRunning: true,
+ processingProgress: 0,
}));
sendMessage({
type: "add-audio-to-video",
- blob: videoBlob,
+ blob: sourceBlob,
audio: audioBlob,
duration: contentState.duration,
volume: volume,
replaceAudio: contentState.replaceAudio,
+ topLevel: false,
});
};
@@ -766,63 +905,56 @@ const ContentState = (props) => {
)
return;
- if (cut) {
- setContentState((prevState) => ({
- ...prevState,
- cutting: true,
- }));
- } else {
- setContentState((prevState) => ({
- ...prevState,
- trimming: true,
- }));
- }
+ const sourceBlob = contentState.blob;
- setContentState((prevState) => ({
- ...prevState,
+ setContentState((prev) => ({
+ ...prev,
isFfmpegRunning: true,
+ processingProgress: 0,
+ [cut ? "cutting" : "trimming"]: true,
}));
sendMessage({
type: "cut-video",
- blob: contentState.blob,
+ blob: sourceBlob,
startTime: contentState.start * contentState.duration,
endTime: contentState.end * contentState.duration,
- cut: cut,
+ cut,
duration: contentState.duration,
encode: false,
+ topLevel: false,
});
};
const handleMute = async () => {
- if (contentState.isFfmpegRunning || contentState.muting) {
- return;
- }
+ if (contentState.isFfmpegRunning) return;
if (
contentState.duration > contentState.editLimit &&
!contentState.override
)
return;
- setContentState((prevState) => ({
- ...prevState,
+ const sourceBlob = contentState.blob;
+
+ setContentState((prev) => ({
+ ...prev,
muting: true,
isFfmpegRunning: true,
+ processingProgress: 0,
}));
sendMessage({
type: "mute-video",
- blob: contentState.blob,
+ blob: sourceBlob,
startTime: contentState.start * contentState.duration,
endTime: contentState.end * contentState.duration,
duration: contentState.duration,
+ topLevel: false,
});
};
const handleCrop = async (x, y, width, height) => {
- if (contentState.isFfmpegRunning || contentState.cropping) {
- return;
- }
+ if (contentState.isFfmpegRunning || contentState.cropping) return;
if (
contentState.duration > contentState.editLimit &&
!contentState.override
@@ -833,33 +965,41 @@ const ContentState = (props) => {
...prevState,
cropping: true,
isFfmpegRunning: true,
+ processingProgress: 0,
}));
+ const sourceBlob = contentState.blob;
+
sendMessage({
type: "crop-video",
- blob: contentState.blob,
- x: x,
- y: y,
- width: width,
- height: height,
+ blob: sourceBlob,
+ x,
+ y,
+ width,
+ height,
+ topLevel: false,
});
return true;
};
- const handleReencode = async () => {
+ const handleReencode = async (topLevel = false) => {
if (contentState.isFfmpegRunning) return;
+ const sourceBlob = contentState.blob;
+
setContentState((prevState) => ({
...prevState,
isFfmpegRunning: true,
reencoding: true,
+ processingProgress: 0, // Reset progress
}));
sendMessage({
type: "reencode-video",
- blob: contentState.blob,
+ blob: sourceBlob,
duration: contentState.duration,
+ topLevel,
});
return true;
@@ -909,7 +1049,6 @@ const ContentState = (props) => {
);
});
- // One-shot listener
await new Promise((resolve) => {
const handler = async (delta) => {
if (delta.id !== downloadId || !delta.state) return;
@@ -979,7 +1118,27 @@ const ContentState = (props) => {
};
const downloadWEBM = async () => {
- if (contentState.isFfmpegRunning || contentState.downloadingWEBM) {
+ if (contentState.isFfmpegRunning || contentState.downloadingWEBM) return;
+
+ const sourceBlob = contentState.blob || contentState.webm;
+
+ if (!sourceBlob) {
+ return;
+ }
+
+ const hasFFmpeg = contentState.ffmpegLoaded && !contentState.noffmpeg;
+ const isAlreadyWebm = sourceBlob.type === "video/webm";
+
+ if (!hasFFmpeg || isAlreadyWebm) {
+ const url = URL.createObjectURL(sourceBlob);
+ await requestDownload(url, ".webm");
+
+ setContentState((prevState) => ({
+ ...prevState,
+ downloadingWEBM: false,
+ isFfmpegRunning: false,
+ saved: true,
+ }));
return;
}
@@ -987,10 +1146,16 @@ const ContentState = (props) => {
...prevState,
downloadingWEBM: true,
isFfmpegRunning: true,
+ processingProgress: 0,
}));
- const url = URL.createObjectURL(contentState.webm);
- requestDownload(url, ".webm");
+ sendMessage({
+ type: "to-webm",
+ blob: sourceBlob,
+ duration: contentState.duration,
+ });
+
+ await waitForUpdatedBlob();
setContentState((prevState) => ({
...prevState,
@@ -1022,7 +1187,18 @@ const ContentState = (props) => {
sendMessage({ type: "load-ffmpeg" });
};
- // Include all functions in the context
+ const waitForUpdatedBlob = () => {
+ return new Promise((resolve) => {
+ const handler = (event) => {
+ if (event.data?.type === "updated-blob") {
+ window.removeEventListener("message", handler);
+ resolve();
+ }
+ };
+ window.addEventListener("message", handler);
+ });
+ };
+
contentState.undo = undo;
contentState.redo = redo;
contentState.addToHistory = addToHistory;
@@ -1036,6 +1212,10 @@ const ContentState = (props) => {
contentState.downloadWEBM = downloadWEBM;
contentState.addAudio = addAudio;
contentState.loadFFmpeg = loadFFmpeg;
+ contentState.waitForUpdatedBlob = waitForUpdatedBlob;
+ contentState.createBackup = createBackup;
+ contentState.restoreBackup = restoreBackup;
+ contentState.clearBackup = clearBackup;
return (
<ContentStateContext.Provider value={[contentState, setContentState]}>
diff --git a/src/pages/Sandbox/layout/editor/AudioNav.js b/src/pages/Sandbox/layout/editor/AudioNav.js
index f4703ee..1dbd114 100644
--- a/src/pages/Sandbox/layout/editor/AudioNav.js
+++ b/src/pages/Sandbox/layout/editor/AudioNav.js
@@ -1,43 +1,53 @@
import React, { useContext } from "react";
import styles from "../../styles/edit/_EditorNav.module.scss";
-import { ContentStateContext } from "../../context/ContentState"; // Import the ContentState context
+import { ContentStateContext } from "../../context/ContentState";
const URL = "/assets/";
const AudioNav = () => {
- const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState context
+ const [contentState, setContentState] = useContext(ContentStateContext);
const handleCancel = () => {
- setContentState((prevContentState) => ({
- ...prevContentState,
+ setContentState((prev) => ({
+ ...prev,
mode: "player",
- blob: contentState.originalBlob,
start: 0,
end: 1,
- width: contentState.prevWidth,
- height: contentState.prevHeight,
- left: 0,
- top: 0,
- fromCropper: false,
+ pendingAudio: null,
}));
+ contentState.restoreBackup();
};
const handleRevert = () => {
- setContentState((prevContentState) => ({
- ...prevContentState,
+ setContentState((prev) => ({
+ ...prev,
blob: contentState.originalBlob,
start: 0,
end: 1,
+ pendingAudio: null,
}));
};
const saveChanges = async () => {
- setContentState((prevContentState) => ({
- ...prevContentState,
- mode: "player",
- start: 0,
- end: 1,
+ const { pendingAudio, volume } = contentState;
+ const source = contentState.blob;
+
+ setContentState((prev) => ({
+ ...prev,
+ isFfmpegRunning: true,
+ processingProgress: 0,
+ fromAudio: true,
}));
+
+ if (pendingAudio) {
+ contentState.addAudio(source, pendingAudio, volume);
+ } else {
+ contentState.handleReencode(true);
+ }
+
+ await contentState.waitForUpdatedBlob?.();
+
+ contentState.clearBackup();
};
return (
@@ -45,18 +55,18 @@ const AudioNav = () => {
<div className={styles.navWrap}>
<div
className={styles.editorNavLeft}
- onClick={() => {
- chrome.runtime.sendMessage({ type: "open-home" });
- }}
+ onClick={() => chrome.runtime.sendMessage({ type: "open-home" })}
>
<img src={URL + "editor/logo.svg"} alt="Logo" />
</div>
+
<div className={styles.editorNavCenter}>
<div className={styles.editorNavTitle}>
- {chrome.i18n.getMessage("sandboxEditorMainTitle") + " "}{" "}
+ {chrome.i18n.getMessage("sandboxEditorMainTitle")}{" "}
<span className={styles.beta}>BETA</span>
</div>
</div>
+
<div className={styles.editorNavRight}>
<button
className="button simpleButton blackButton"
@@ -65,6 +75,7 @@ const AudioNav = () => {
>
{chrome.i18n.getMessage("sandboxEditorCancelButton")}
</button>
+
<button
className="button secondaryButton"
onClick={handleRevert}
@@ -72,14 +83,27 @@ const AudioNav = () => {
>
{chrome.i18n.getMessage("sandboxEditorRevertButton")}
</button>
+
<button
className="button primaryButton"
onClick={saveChanges}
disabled={contentState.isFfmpegRunning}
>
- {contentState.cropping
- ? chrome.i18n.getMessage("sandboxEditorSaveProgressButton")
- : chrome.i18n.getMessage("sandboxEditorSaveButton")}
+ {contentState.isFfmpegRunning ? (
+ contentState.processingProgress > 0 ? (
+ <>
+ {chrome.i18n.getMessage("sandboxEditorSaveProgressButton") ||
+ "Saving"}{" "}
+ {Math.round(contentState.processingProgress)}%
+ </>
+ ) : (
+ chrome.i18n.getMessage("sandboxEditorSaveProgressButton") ||
+ "Saving..."
+ )
+ ) : (
+ chrome.i18n.getMessage("sandboxEditorSaveButton") ||
+ "Save changes"
+ )}
</button>
</div>
</div>
diff --git a/src/pages/Sandbox/layout/editor/AudioUI.js b/src/pages/Sandbox/layout/editor/AudioUI.js
index 360560c..3947039 100644
--- a/src/pages/Sandbox/layout/editor/AudioUI.js
+++ b/src/pages/Sandbox/layout/editor/AudioUI.js
@@ -38,8 +38,15 @@ const AudioUI = (props) => {
return;
}
- contentState.addAudio(contentState.blob, file, contentState.volume);
+ // Use rawBlob (webm from recovery) if blob (mp4) is not available yet
+ const videoBlob =
+ contentState.blob || contentState.rawBlob || contentState.webm;
+ //contentState.addAudio(videoBlob, file, contentState.volume);
setAudio(file);
+ setContentState((prev) => ({
+ ...prev,
+ pendingAudio: file,
+ }));
};
const handleVolume = (e) => {
@@ -60,14 +67,6 @@ const AudioUI = (props) => {
}));
};
- const updateAudio = async () => {
- setContentState((prevContentState) => ({
- ...prevContentState,
- blob: prevBlob.current,
- }));
- contentState.addAudio(prevBlob.current, audio, contentState.volume);
- };
-
return (
<div>
<div className={styles.section}>
@@ -164,13 +163,13 @@ const AudioUI = (props) => {
</Slider.Root>
</div>
<Switch />
- <button
+ {/* <button
className={["button", "primaryButton", styles.updateButton].join(" ")}
onClick={updateAudio}
disabled={contentState.isFfmpegRunning || !audio}
>
{chrome.i18n.getMessage("sandboxAudioUpdateButton")}
- </button>
+ </button> */}
</div>
</div>
);
diff --git a/src/pages/Sandbox/layout/editor/CropNav.js b/src/pages/Sandbox/layout/editor/CropNav.js
index 29c8e6e..a5c6fac 100644
--- a/src/pages/Sandbox/layout/editor/CropNav.js
+++ b/src/pages/Sandbox/layout/editor/CropNav.js
@@ -11,7 +11,6 @@ const CropNav = () => {
setContentState((prevContentState) => ({
...prevContentState,
mode: "player",
- blob: contentState.originalBlob,
start: 0,
end: 1,
width: contentState.prevWidth,
@@ -20,6 +19,8 @@ const CropNav = () => {
top: 0,
fromCropper: false,
}));
+
+ contentState.clearBackup();
};
const handleRevert = () => {
@@ -37,12 +38,21 @@ const CropNav = () => {
};
const saveChanges = async () => {
- contentState.handleCrop(
+ await contentState.handleCrop(
contentState.left,
contentState.top,
contentState.width,
contentState.height
);
+
+ setContentState((prev) => ({
+ ...prev,
+ // mode: "player",
+ fromCropper: true,
+ hasTempChanges: false,
+ }));
+
+ contentState.clearBackup();
};
return (
@@ -75,16 +85,28 @@ const CropNav = () => {
onClick={handleRevert}
disabled={contentState.isFfmpegRunning}
>
- {chrome.i18n.getMessage("sandboxEditorResetButton")}
+ {chrome.i18n.getMessage("sandboxEditorRevertButton")}
</button>
<button
className="button primaryButton"
onClick={saveChanges}
disabled={contentState.isFfmpegRunning}
>
- {contentState.cropping
- ? chrome.i18n.getMessage("sandboxEditorSaveProgressButton")
- : chrome.i18n.getMessage("sandboxEditorSaveButton")}
+ {contentState.isFfmpegRunning ? (
+ contentState.processingProgress > 0 ? (
+ <>
+ {chrome.i18n.getMessage("sandboxEditorSaveProgressButton") ||
+ "Saving"}{" "}
+ {Math.round(contentState.processingProgress)}%
+ </>
+ ) : (
+ chrome.i18n.getMessage("sandboxEditorSaveProgressButton") ||
+ "Saving..."
+ )
+ ) : (
+ chrome.i18n.getMessage("sandboxEditorSaveButton") ||
+ "Save changes"
+ )}
</button>
</div>
</div>
diff --git a/src/pages/Sandbox/layout/editor/CropUI.js b/src/pages/Sandbox/layout/editor/CropUI.js
index 1598192..0a70c3c 100644
--- a/src/pages/Sandbox/layout/editor/CropUI.js
+++ b/src/pages/Sandbox/layout/editor/CropUI.js
@@ -201,6 +201,22 @@ const CropUI = (props) => {
/>
<span>px</span>
</div>
+ {/* <button
+ className={["button", "primaryButton", styles.updateButton].join(
+ " "
+ )}
+ onClick={() => {
+ contentState.handleCrop(
+ contentState.left,
+ contentState.top,
+ contentState.width,
+ contentState.height
+ );
+ }}
+ disabled={contentState.isFfmpegRunning}
+ >
+ {chrome.i18n.getMessage("sandboxCropUpdateButton") || "Update crop"}
+ </button> */}
</div>
</div>
</div>
diff --git a/src/pages/Sandbox/layout/editor/EditorNav.js b/src/pages/Sandbox/layout/editor/EditorNav.js
index c8c875b..93690a8 100644
--- a/src/pages/Sandbox/layout/editor/EditorNav.js
+++ b/src/pages/Sandbox/layout/editor/EditorNav.js
@@ -11,10 +11,11 @@ const EditorNav = () => {
setContentState((prevContentState) => ({
...prevContentState,
mode: "player",
- blob: contentState.originalBlob,
start: 0,
end: 1,
}));
+
+ contentState.restoreBackup();
};
const handleRevert = () => {
@@ -27,13 +28,17 @@ const EditorNav = () => {
};
const saveChanges = async () => {
- await contentState.handleReencode();
- setContentState((prevContentState) => ({
- ...prevContentState,
+ if (contentState.isFfmpegRunning) return;
+
+ setContentState((prev) => ({
+ ...prev,
mode: "player",
+ hasTempChanges: false,
start: 0,
end: 1,
}));
+
+ contentState.clearBackup();
};
return (
diff --git a/src/pages/Sandbox/layout/editor/TrimUI.js b/src/pages/Sandbox/layout/editor/TrimUI.js
index 2acc6da..04587b7 100644
--- a/src/pages/Sandbox/layout/editor/TrimUI.js
+++ b/src/pages/Sandbox/layout/editor/TrimUI.js
@@ -70,7 +70,10 @@ const TrimUI = (props) => {
>
<ReactSVG src={TrimIcon} />
{contentState.trimming
- ? chrome.i18n.getMessage("sandboxEditorTrimProgressButton")
+ ? chrome.i18n.getMessage("sandboxEditorTrimProgressButton") +
+ (contentState.processingProgress > 0
+ ? ` ${contentState.processingProgress}%`
+ : "")
: chrome.i18n.getMessage("sandboxEditorTrimButton")}
</button>
<button
@@ -83,7 +86,10 @@ const TrimUI = (props) => {
>
<ReactSVG src={RemoveIcon} />
{contentState.cutting
- ? chrome.i18n.getMessage("sandboxEditorCutProgressButton")
+ ? chrome.i18n.getMessage("sandboxEditorCutProgressButton") +
+ (contentState.processingProgress > 0
+ ? ` ${contentState.processingProgress}%`
+ : "")
: chrome.i18n.getMessage("sandboxEditorCutButton")}
</button>
<button
@@ -93,7 +99,10 @@ const TrimUI = (props) => {
>
<ReactSVG src={MuteIcon} />
{contentState.muting
- ? chrome.i18n.getMessage("sandboxEditorMuteProgressButton")
+ ? chrome.i18n.getMessage("sandboxEditorMuteProgressButton") +
+ (contentState.processingProgress > 0
+ ? ` ${contentState.processingProgress}%`
+ : "")
: chrome.i18n.getMessage("sandboxEditorMuteButton")}
</button>
</div>
diff --git a/src/pages/Sandbox/layout/player/RightPanel.js b/src/pages/Sandbox/layout/player/RightPanel.js
index 45bc0f9..cb34c19 100644
--- a/src/pages/Sandbox/layout/player/RightPanel.js
+++ b/src/pages/Sandbox/layout/player/RightPanel.js
@@ -20,7 +20,6 @@ const RightPanel = () => {
const contentStateRef = useRef(contentState);
const consoleErrorRef = useRef([]);
- // Override console.error to catch errors from ffmpeg.wasm
useEffect(() => {
console.error = (error) => {
consoleErrorRef.current.push(error);
@@ -103,6 +102,9 @@ const RightPanel = () => {
)
return;
if (!contentState.mp4ready) return;
+
+ contentState.createBackup();
+
setContentState((prevContentState) => ({
...prevContentState,
mode: "edit",
@@ -123,7 +125,15 @@ const RightPanel = () => {
!contentState.override
)
return;
+
if (!contentState.mp4ready) return;
+
+ contentState.createBackup();
+
+ if (!contentState.frame && !contentState.isFfmpegRunning) {
+ contentState.getFrame();
+ }
+
setContentState((prevContentState) => ({
...prevContentState,
mode: "crop",
@@ -144,6 +154,9 @@ const RightPanel = () => {
)
return;
if (!contentState.mp4ready) return;
+
+ contentState.createBackup();
+
setContentState((prevContentState) => ({
...prevContentState,
mode: "audio",
@@ -252,7 +265,7 @@ const RightPanel = () => {
</div>
</div>
)}
- {contentState.fallback && (
+ {contentState.fallback && contentState.noffmpeg && (
<div className={styles.alert}>
<div className={styles.buttonLeft}>
<ReactSVG src={URL + "editor/icons/alert.svg"} />
diff --git a/src/pages/Sandbox/styles/edit/_Switch.module.scss b/src/pages/Sandbox/styles/edit/_Switch.module.scss
index ac40c83..2af9c30 100644
--- a/src/pages/Sandbox/styles/edit/_Switch.module.scss
+++ b/src/pages/Sandbox/styles/edit/_Switch.module.scss
@@ -39,12 +39,11 @@
border-radius: 9999px;
box-shadow: 0px 1px 10px rgba(0, 0, 0, 0.1);
transition: transform 100ms;
- transform: translateX(2px);
+ transform: translateX(4px);
will-change: transform;
- margin-left: -5px;
}
.SwitchThumb[data-state="checked"] {
- transform: translateX(15px);
+ transform: translateX(16px);
}
.Label {
diff --git a/utils/build.js b/utils/build.js
index ae27b9e..56d3def 100755
--- a/utils/build.js
+++ b/utils/build.js
@@ -11,7 +11,24 @@ delete config.custom;
config.mode = "production";
-webpack(config, (err) => {
- if (err) throw err;
+webpack(config, (err, stats) => {
+ if (err) {
+ console.error("Webpack compilation error:", err);
+ throw err;
+ }
+
+ if (stats.hasErrors()) {
+ console.error("Webpack compilation failed with errors:");
+ const info = stats.toJson();
+ console.error(info.errors);
+ process.exit(1);
+ }
+
+ if (stats.hasWarnings()) {
+ console.warn("Webpack compilation had warnings:");
+ const info = stats.toJson();
+ console.warn(info.warnings);
+ }
+
console.log("Production build completed successfully!");
});
diff --git a/webpack.config.js b/webpack.config.js
index 8af7e5e..c82d58a 100755
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -39,11 +39,18 @@ const entryPoints = {
editor: path.join(__dirname, "src", "pages", "Editor", "index.jsx"),
region: path.join(__dirname, "src", "pages", "Region", "index.jsx"),
download: path.join(__dirname, "src", "pages", "Download", "index.jsx"),
- editorfallback: path.join(
+ editorwebcodecs: path.join(
__dirname,
"src",
"pages",
- "EditorFallback",
+ "EditorWebCodecs",
+ "index.jsx"
+ ),
+ editorviewer: path.join(
+ __dirname,
+ "src",
+ "pages",
+ "EditorViewer",
"index.jsx"
),
backup: path.join(__dirname, "src", "pages", "Backup", "index.jsx"),
@@ -56,11 +63,23 @@ const htmlPlugins = Object.keys(entryPoints)
return null;
}
+ // Map entry names to folder names (for multi-word entries)
+ const folderNameMap = {
+ cloudrecorder: "CloudRecorder",
+ recorderoffscreen: "RecorderOffscreen",
+ editorwebcodecs: "EditorWebCodecs",
+ editorviewer: "EditorViewer",
+ };
+
+ const folderName =
+ folderNameMap[entryName] ||
+ entryName.charAt(0).toUpperCase() + entryName.slice(1);
+
const templatePath = path.join(
__dirname,
"src",
"pages",
- entryName.charAt(0).toUpperCase() + entryName.slice(1),
+ folderName,
"index.html"
);