mirror of
https://github.com/zhw2590582/ArtPlayer.git
synced 2026-10-20 12:11:20 -08:00
Refactor code structure for improved readability and maintainability
Remove debugging border from the websr plugin's styling Enhance canvas sizing logic in artplayer-plugin-websr - Updated canvas positioning to center it within the player. - Introduced a new function to calculate canvas size based on the video aspect ratio. - Adjusted canvas dimensions during initialization and on resize events to maintain aspect ratio. - Ensured canvas styles are updated to reflect the calculated dimensions. feat: add comparison mode to artplayer-plugin-websr - Updated README.md to reflect new comparison feature and simplified content. - Modified package.json to remove unnecessary keywords. - Enhanced index.js to implement comparison functionality, allowing users to compare original and upscaled video. - Added new methods for enabling, disabling, and toggling comparison mode, as well as setting and getting the comparison position. - Updated TypeScript definitions to include new comparison options and methods.
This commit is contained in:
1 parent
07a5b0c0f0
commit
7dffd99cfd
308 files changed
+3175
-852
No files matched your search
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
.DS_Store
|
||||
.parcel-cache
|
||||
yarn.lock
|
||||
package-lock.json
|
||||
src
|
||||
@@ -0,0 +1,11 @@
|
||||
# artplayer-plugin-websr
|
||||
|
||||
websr plugin for ArtPlayer
|
||||
|
||||
## Demo
|
||||
|
||||
[https://artplayer.org](https://artplayer.org/?libs=./uncompiled/artplayer-plugin-websr/index.js&example=websr)
|
||||
|
||||
## License
|
||||
|
||||
MIT © Harvey Zack
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
/*!
|
||||
* artplayer-plugin-websr.js v1.0.0
|
||||
* Github: https://github.com/zhw2590582/ArtPlayer
|
||||
* (c) 2017-2026 Harvey Zack
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
!function(e,n,t,r,s){var i="u">typeof globalThis?globalThis:"u">typeof self?self:"u">typeof window?window:"u">typeof global?global:{},o="function"==typeof i[r]&&i[r],u=o.i||{},a=o.cache||{},c="u">typeof module&&"function"==typeof module.require&&module.require.bind(module);function l(n,t){if(!a[n]){if(!e[n]){if(s[n])return s[n];var u="function"==typeof i[r]&&i[r];if(!t&&u)return u(n,!0);if(o)return o(n,!0);if(c&&"string"==typeof n)return c(n);var f=Error("Cannot find module '"+n+"'");throw f.code="MODULE_NOT_FOUND",f}_.resolve=p,_.cache={};var d=a[n]=new l.Module(n);e[n][0].call(d.exports,_,d,d.exports,i)}return a[n].exports;function _(e){var n=_.resolve(e);if(!1===n)return{};if(Array.isArray(n)){var t={__esModule:!0};return n.forEach(function(e){var n=e[0],r=e[1],s=e[2]||e[0],i=l(r);"*"===n?Object.keys(i).forEach(function(e){"default"===e||"__esModule"===e||Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return i[e]}})}):"*"===s?Object.defineProperty(t,n,{enumerable:!0,value:i}):Object.defineProperty(t,n,{enumerable:!0,get:function(){return"default"===s?i.__esModule?i.default:i:i[s]}})}),t}return l(n)}function p(t){var r=e[n][1][t];return null!=r?r:t}}function f(e){this.id=e,this.bundle=l,this.require=c,this.exports={}}l.isParcelRequire=!0,l.Module=f,l.modules=e,l.cache=a,l.parent=o,l.distDir=void 0,l.publicUrl=void 0,l.devServer=void 0,l.i=u,l.register=function(n,t){e[n]=[function(e,n){n.exports=t},{}]},Object.defineProperty(l,"root",{get:function(){return i[r]}}),i[r]=l;for(var d=0;d<n.length;d++)l(n[d]);if(t){var _=l(t);"object"==typeof exports&&"u">typeof module?module.exports=_:"function"==typeof define&&define.amd&&define(function(){return _})}}({"80h6e":[function(e,n,t,r){var s=e("@parcel/transformer-js/src/esmodule-helpers.js");s.defineInteropFlag(t),s.export(t,"default",()=>u);var i=e("@websr/websr"),o=s.interopDefault(i);function u(e={}){return n=>{let{template:{$player:t},constructor:{validator:r,utils:{append:s,setStyles:i}}}=n;(e=r({scale:2,networkName:"",weights:null,compare:!1,...e},{scale:"number",networkName:"string",weights:"?string|object",compare:"boolean"})).networkName||console.error("WebSR: networkName is required"),e.weights||console.error("WebSR: weights is required");let u=null,a=null,c=!1,l=!0,f=null,d=.5,_=!1,p=document.createElement("canvas");p.id="artplayer-websr-canvas",i(p,{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:"block",pointerEvents:"none",zIndex:"11",imageRendering:"crisp-edges"}),s(t,p);let h=document.createElement("div");function x(n){if(i(h,{left:100*(d=Math.max(0,Math.min(1,n)))+"%"}),e.compare){let e=100*d;i(p,{clipPath:`inset(0 0 0 ${e}%)`})}}function v(){let e=n.video;if(!e)return{displayWidth:640,displayHeight:360};let r=t.offsetWidth||640,s=t.offsetHeight||360,i=(e.videoWidth||640)/(e.videoHeight||360),o=r,u=s;return r/s>i?o=s*i:u=r/i,{displayWidth:o,displayHeight:u}}async function b(){try{let t;if(c)return!0;if(!navigator.gpu)return console.warn("WebGPU is not supported"),!1;if(!(a=await o.default.initWebGPU()))return console.warn("Failed to initialize WebGPU"),!1;if("string"==typeof e.weights){let n=await fetch(e.weights);if(!n.ok)return console.warn(`Failed to load weights from ${e.weights}`),!1;t=await n.json()}else{if("object"!=typeof e.weights)return console.warn("Invalid weights format"),!1;t=e.weights}let r=n.video;if(!r)return console.warn("Video element not found"),!1;let{displayWidth:s,displayHeight:l}=v();return p.width=s*e.scale,p.height=l*e.scale,i(p,{width:s+"px",height:l+"px"}),u=new(0,o.default)({source:r,network_name:e.networkName,weights:t,gpu:a,canvas:p}),c=!0,!0}catch(e){return console.error("WebSR initialization error:",e),!1}}async function m(){if(u&&l&&n.video)try{await u.render(n.video)}catch(e){console.error("WebSR render error:",e)}}async function y(){if(!u||!l||!n.video||n.video.paused){f=null;return}try{await u.render(n.video)}catch(e){console.error("WebSR render error:",e)}l&&!n.video.paused&&(f=requestAnimationFrame(y))}async function w(){if(!l){if(!c&&!await b())return void console.error("Failed to initialize WebSR");l=!0,setStyle(p,"display","block"),n.video&&!n.video.paused&&(f=requestAnimationFrame(y)),n.emit("artplayerPluginWebsr:enable")}}function g(){l&&(l=!1,i(p,{display:"none"}),f&&(cancelAnimationFrame(f),f=null),n.emit("artplayerPluginWebsr:disable"))}async function k(){l?g():await w()}return h.id="artplayer-websr-divider",i(h,{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"2px",height:"100%",backgroundColor:"#fff",display:e.compare?"block":"none",pointerEvents:"auto",cursor:"col-resize",zIndex:"12"}),s(t,h),document.addEventListener("mousemove",e=>{if(!_)return;let n=t.getBoundingClientRect();x((e.clientX-n.left)/n.width)}),document.addEventListener("mouseup",()=>{_=!1}),h.addEventListener("mousedown",()=>{_=!0}),document.addEventListener("touchmove",e=>{if(!_)return;let n=t.getBoundingClientRLine truncated
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
/*!
|
||||
* artplayer-plugin-websr.js v1.0.0
|
||||
* Github: https://github.com/zhw2590582/ArtPlayer
|
||||
* (c) 2017-2026 Harvey Zack
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
!function(e,n,t,r,s){var i="u">typeof globalThis?globalThis:"u">typeof self?self:"u">typeof window?window:"u">typeof global?global:{},o="function"==typeof i[r]&&i[r],u=o.i||{},a=o.cache||{},c="u">typeof module&&"function"==typeof module.require&&module.require.bind(module);function l(n,t){if(!a[n]){if(!e[n]){if(s[n])return s[n];var u="function"==typeof i[r]&&i[r];if(!t&&u)return u(n,!0);if(o)return o(n,!0);if(c&&"string"==typeof n)return c(n);var f=Error("Cannot find module '"+n+"'");throw f.code="MODULE_NOT_FOUND",f}_.resolve=p,_.cache={};var d=a[n]=new l.Module(n);e[n][0].call(d.exports,_,d,d.exports,i)}return a[n].exports;function _(e){var n=_.resolve(e);if(!1===n)return{};if(Array.isArray(n)){var t={__esModule:!0};return n.forEach(function(e){var n=e[0],r=e[1],s=e[2]||e[0],i=l(r);"*"===n?Object.keys(i).forEach(function(e){"default"===e||"__esModule"===e||Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return i[e]}})}):"*"===s?Object.defineProperty(t,n,{enumerable:!0,value:i}):Object.defineProperty(t,n,{enumerable:!0,get:function(){return"default"===s?i.__esModule?i.default:i:i[s]}})}),t}return l(n)}function p(t){var r=e[n][1][t];return null!=r?r:t}}function f(e){this.id=e,this.bundle=l,this.require=c,this.exports={}}l.isParcelRequire=!0,l.Module=f,l.modules=e,l.cache=a,l.parent=o,l.distDir=void 0,l.publicUrl=void 0,l.devServer=void 0,l.i=u,l.register=function(n,t){e[n]=[function(e,n){n.exports=t},{}]},Object.defineProperty(l,"root",{get:function(){return i[r]}}),i[r]=l;for(var d=0;d<n.length;d++)l(n[d]);if(t){var _=l(t);"object"==typeof exports&&"u">typeof module?module.exports=_:"function"==typeof define&&define.amd&&define(function(){return _})}}({hrC3O:[function(e,n,t,r){var s=e("@parcel/transformer-js/src/esmodule-helpers.js");s.defineInteropFlag(t),s.export(t,"default",function(){return f});var i=e("@swc/helpers/cjs/_async_to_generator.cjs"),o=e("@swc/helpers/cjs/_object_spread.cjs"),u=e("@swc/helpers/cjs/_type_of.cjs"),a=e("@swc/helpers/cjs/_ts_generator.cjs"),c=e("@websr/websr"),l=s.interopDefault(c);function f(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(n){var t=n.template.$player,r=n.constructor,s=r.validator,c=r.utils,f=c.append,d=c.setStyles;(e=s((0,o._)({scale:2,networkName:"",weights:null,compare:!1},e),{scale:"number",networkName:"string",weights:"?string|object",compare:"boolean"})).networkName||console.error("WebSR: networkName is required"),e.weights||console.error("WebSR: weights is required");var _=null,p=null,h=!1,v=!0,x=null,b=.5,m=!1,y=document.createElement("canvas");y.id="artplayer-websr-canvas",d(y,{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:"block",pointerEvents:"none",zIndex:"11",imageRendering:"crisp-edges"}),f(t,y);var w=document.createElement("div");function g(n){if(d(w,{left:100*(b=Math.max(0,Math.min(1,n)))+"%"}),e.compare){var t=100*b;d(y,{clipPath:"inset(0 0 0 ".concat(t,"%)")})}}function k(){var e=n.video;if(!e)return{displayWidth:640,displayHeight:360};var r=t.offsetWidth||640,s=t.offsetHeight||360,i=(e.videoWidth||640)/(e.videoHeight||360),o=r,u=s;return r/s>i?o=s*i:u=r/i,{displayWidth:o,displayHeight:u}}function P(){return(0,i._)(function(){var t,r,s,i,o,c;return(0,a._)(this,function(a){switch(a.label){case 0:if(a.trys.push([0,6,,7]),h)return[2,!0];if(!navigator.gpu)return console.warn("WebGPU is not supported"),[2,!1];return[4,l.default.initWebGPU()];case 1:if(!(p=a.sent()))return console.warn("Failed to initialize WebGPU"),[2,!1];if("string"!=typeof e.weights)return[3,4];return[4,fetch(e.weights)];case 2:if(!(r=a.sent()).ok)return console.warn("Failed to load weights from ".concat(e.weights)),[2,!1];return[4,r.json()];case 3:return t=a.sent(),[3,5];case 4:if("object"!==(0,u._)(e.weights))return console.warn("Invalid weights format"),[2,!1];t=e.weights,a.label=5;case 5:if(!(s=n.video))return console.warn("Video element not found"),[2,!1];return o=(i=k()).displayWidth,c=i.displayHeight,y.width=o*e.scale,y.height=c*e.scale,d(y,{width:o+"px",height:c+"px"}),_=new(0,l.default)({source:s,network_name:e.networkName,weights:t,gpu:p,canvas:y}),h=!0,[2,!0];case 6:return console.error("WebSR initialization error:",a.sent()),[2,!1];case 7:return[2]}})})()}function S(){return(0,i._)(function(){return(0,a._)(this,function(e){switch(e.label){case 0:if(!_||!v||!n.video)return[2];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,_.render(n.video)];case 2:return e.sent(),[3,4];case 3:return console.error("WebSR render error:",e.sent()),[3,4];case 4:return[2]}})})()}function U(){return(0,i._)(function(){return(0,a._)(this,function(e){switch(e.label){case 0:if(!_||!v||!n.video||n.video.paused)return x=null,[2];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,_.render(n.video)];case 2:return e.sent(),[3,4];case 3:return console.error("WebSR render error:",e.sent()),[3,4];case 4:return v&&!n.video.paused&&(x=requestAnimationFrame(U)),[2]}})})()}function T(){rLine truncated
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
/*!
|
||||
* artplayer-plugin-websr.js v1.0.0
|
||||
* Github: https://github.com/zhw2590582/ArtPlayer
|
||||
* (c) 2017-2026 Harvey Zack
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
!function(e,n,t,r,s){var i="u">typeof globalThis?globalThis:"u">typeof self?self:"u">typeof window?window:"u">typeof global?global:{},o="function"==typeof i[r]&&i[r],u=o.i||{},a=o.cache||{},c="u">typeof module&&"function"==typeof module.require&&module.require.bind(module);function l(n,t){if(!a[n]){if(!e[n]){if(s[n])return s[n];var u="function"==typeof i[r]&&i[r];if(!t&&u)return u(n,!0);if(o)return o(n,!0);if(c&&"string"==typeof n)return c(n);var f=Error("Cannot find module '"+n+"'");throw f.code="MODULE_NOT_FOUND",f}_.resolve=p,_.cache={};var d=a[n]=new l.Module(n);e[n][0].call(d.exports,_,d,d.exports,i)}return a[n].exports;function _(e){var n=_.resolve(e);if(!1===n)return{};if(Array.isArray(n)){var t={__esModule:!0};return n.forEach(function(e){var n=e[0],r=e[1],s=e[2]||e[0],i=l(r);"*"===n?Object.keys(i).forEach(function(e){"default"===e||"__esModule"===e||Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return i[e]}})}):"*"===s?Object.defineProperty(t,n,{enumerable:!0,value:i}):Object.defineProperty(t,n,{enumerable:!0,get:function(){return"default"===s?i.__esModule?i.default:i:i[s]}})}),t}return l(n)}function p(t){var r=e[n][1][t];return null!=r?r:t}}function f(e){this.id=e,this.bundle=l,this.require=c,this.exports={}}l.isParcelRequire=!0,l.Module=f,l.modules=e,l.cache=a,l.parent=o,l.distDir=void 0,l.publicUrl=void 0,l.devServer=void 0,l.i=u,l.register=function(n,t){e[n]=[function(e,n){n.exports=t},{}]},Object.defineProperty(l,"root",{get:function(){return i[r]}}),i[r]=l;for(var d=0;d<n.length;d++)l(n[d]);if(t){var _=l(t);"object"==typeof exports&&"u">typeof module?module.exports=_:"function"==typeof define&&define.amd&&define(function(){return _})}}({hOg5u:[function(e,n,t,r){var s=e("@parcel/transformer-js/src/esmodule-helpers.js");s.defineInteropFlag(t),s.export(t,"default",()=>u);var i=e("@websr/websr"),o=s.interopDefault(i);function u(e={}){return n=>{let{template:{$player:t},constructor:{validator:r,utils:{append:s,setStyles:i}}}=n;(e=r({scale:2,networkName:"",weights:null,compare:!1,...e},{scale:"number",networkName:"string",weights:"?string|object",compare:"boolean"})).networkName||console.error("WebSR: networkName is required"),e.weights||console.error("WebSR: weights is required");let u=null,a=null,c=!1,l=!0,f=null,d=.5,_=!1,p=document.createElement("canvas");p.id="artplayer-websr-canvas",i(p,{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:"block",pointerEvents:"none",zIndex:"11",imageRendering:"crisp-edges"}),s(t,p);let h=document.createElement("div");function x(n){if(i(h,{left:100*(d=Math.max(0,Math.min(1,n)))+"%"}),e.compare){let e=100*d;i(p,{clipPath:`inset(0 0 0 ${e}%)`})}}function v(){let e=n.video;if(!e)return{displayWidth:640,displayHeight:360};let r=t.offsetWidth||640,s=t.offsetHeight||360,i=(e.videoWidth||640)/(e.videoHeight||360),o=r,u=s;return r/s>i?o=s*i:u=r/i,{displayWidth:o,displayHeight:u}}async function b(){try{let t;if(c)return!0;if(!navigator.gpu)return console.warn("WebGPU is not supported"),!1;if(!(a=await o.default.initWebGPU()))return console.warn("Failed to initialize WebGPU"),!1;if("string"==typeof e.weights){let n=await fetch(e.weights);if(!n.ok)return console.warn(`Failed to load weights from ${e.weights}`),!1;t=await n.json()}else{if("object"!=typeof e.weights)return console.warn("Invalid weights format"),!1;t=e.weights}let r=n.video;if(!r)return console.warn("Video element not found"),!1;let{displayWidth:s,displayHeight:l}=v();return p.width=s*e.scale,p.height=l*e.scale,i(p,{width:s+"px",height:l+"px"}),u=new(0,o.default)({source:r,network_name:e.networkName,weights:t,gpu:a,canvas:p}),c=!0,!0}catch(e){return console.error("WebSR initialization error:",e),!1}}async function m(){if(u&&l&&n.video)try{await u.render(n.video)}catch(e){console.error("WebSR render error:",e)}}async function y(){if(!u||!l||!n.video||n.video.paused){f=null;return}try{await u.render(n.video)}catch(e){console.error("WebSR render error:",e)}l&&!n.video.paused&&(f=requestAnimationFrame(y))}async function w(){if(!l){if(!c&&!await b())return void console.error("Failed to initialize WebSR");l=!0,setStyle(p,"display","block"),n.video&&!n.video.paused&&(f=requestAnimationFrame(y)),n.emit("artplayerPluginWebsr:enable")}}function g(){l&&(l=!1,i(p,{display:"none"}),f&&(cancelAnimationFrame(f),f=null),n.emit("artplayerPluginWebsr:disable"))}async function k(){l?g():await w()}return h.id="artplayer-websr-divider",i(h,{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"2px",height:"100%",backgroundColor:"#fff",display:e.compare?"block":"none",pointerEvents:"auto",cursor:"col-resize",zIndex:"12"}),s(t,h),document.addEventListener("mousemove",e=>{if(!_)return;let n=t.getBoundingClientRect();x((e.clientX-n.left)/n.width)}),document.addEventListener("mouseup",()=>{_=!1}),h.addEventListener("mousedown",()=>{_=!0}),document.addEventListener("touchmove",e=>{if(!_)return;let n=t.getBoundingClientRecLine truncated
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "artplayer-plugin-websr",
|
||||
"version": "1.0.0",
|
||||
"description": "AI upscaling plugin for ArtPlayer using WebSR - real-time video super-resolution with WebGPU",
|
||||
"author": "Harvey Zack <laozhaochaguan@gmail.com>",
|
||||
"license": "MIT",
|
||||
"homepage": "https://artplayer.org",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/zhw2590582/ArtPlayer.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/zhw2590582/ArtPlayer/issues"
|
||||
},
|
||||
"keywords": [
|
||||
"html5",
|
||||
"video",
|
||||
"player"
|
||||
],
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./types/artplayer-plugin-websr.d.ts",
|
||||
"import": "./dist/artplayer-plugin-websr.mjs",
|
||||
"require": "./dist/artplayer-plugin-websr.js"
|
||||
},
|
||||
"./legacy": {
|
||||
"types": "./types/artplayer-plugin-websr.d.ts",
|
||||
"import": "./dist/artplayer-plugin-websr.legacy.js",
|
||||
"require": "./dist/artplayer-plugin-websr.legacy.js"
|
||||
}
|
||||
},
|
||||
"main": "dist/artplayer-plugin-websr.js",
|
||||
"module": "./dist/artplayer-plugin-websr.mjs",
|
||||
"types": "types/artplayer-plugin-websr.d.ts",
|
||||
"legacy": "dist/artplayer-plugin-websr.legacy.js",
|
||||
"browserslist": "last 1 Chrome version",
|
||||
"dependencies": {
|
||||
"@websr/websr": "^0.0.14"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
import WebSR from '@websr/websr';
|
||||
|
||||
export default function artplayerPluginWebsr(option = {}) {
|
||||
return (art) => {
|
||||
const {
|
||||
template: { $player },
|
||||
constructor: {
|
||||
validator,
|
||||
utils: { append, setStyles },
|
||||
},
|
||||
} = art;
|
||||
|
||||
// Default options
|
||||
option = validator(
|
||||
{
|
||||
scale: 2,
|
||||
networkName: '',
|
||||
weights: null,
|
||||
compare: false,
|
||||
...option,
|
||||
},
|
||||
{
|
||||
scale: 'number',
|
||||
networkName: 'string',
|
||||
weights: '?string|object',
|
||||
compare: 'boolean',
|
||||
}
|
||||
);
|
||||
|
||||
// Validate required parameters
|
||||
if (!option.networkName) {
|
||||
console.error('WebSR: networkName is required');
|
||||
}
|
||||
if (!option.weights) {
|
||||
console.error('WebSR: weights is required');
|
||||
}
|
||||
|
||||
let websr = null;
|
||||
let gpu = null;
|
||||
let isInitialized = false;
|
||||
let isEnabled = true; // Always enabled
|
||||
let renderFrameId = null;
|
||||
let comparePosition = 0.5; // Comparison split position (0-1)
|
||||
let isCompareDragging = false;
|
||||
|
||||
// Create canvas for upscaled output
|
||||
const $canvas = document.createElement('canvas');
|
||||
$canvas.id = 'artplayer-websr-canvas';
|
||||
setStyles($canvas, {
|
||||
position: 'absolute',
|
||||
top: '50%',
|
||||
left: '50%',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
display: 'block',
|
||||
pointerEvents: 'none',
|
||||
zIndex: '11',
|
||||
imageRendering: 'crisp-edges',
|
||||
});
|
||||
append($player, $canvas);
|
||||
|
||||
// Create comparison divider
|
||||
const $compareDivider = document.createElement('div');
|
||||
$compareDivider.id = 'artplayer-websr-divider';
|
||||
setStyles($compareDivider, {
|
||||
position: 'absolute',
|
||||
top: '50%',
|
||||
left: '50%',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
width: '2px',
|
||||
height: '100%',
|
||||
backgroundColor: '#fff',
|
||||
display: option.compare ? 'block' : 'none',
|
||||
pointerEvents: 'auto',
|
||||
cursor: 'col-resize',
|
||||
zIndex: '12',
|
||||
});
|
||||
append($player, $compareDivider);
|
||||
|
||||
// Function to update divider position and canvas clip-path
|
||||
function updateDividerPosition(pos) {
|
||||
comparePosition = Math.max(0, Math.min(1, pos));
|
||||
const offsetX = comparePosition * 100;
|
||||
setStyles($compareDivider, {
|
||||
left: offsetX + '%',
|
||||
});
|
||||
|
||||
// Update canvas clip-path to show only right side (upscaled)
|
||||
if (option.compare) {
|
||||
const clipPercent = comparePosition * 100;
|
||||
setStyles($canvas, {
|
||||
clipPath: `inset(0 0 0 ${clipPercent}%)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Mouse events for comparison dragging
|
||||
document.addEventListener('mousemove', (e) => {
|
||||
if (!isCompareDragging) return;
|
||||
const rect = $player.getBoundingClientRect();
|
||||
const pos = (e.clientX - rect.left) / rect.width;
|
||||
updateDividerPosition(pos);
|
||||
});
|
||||
|
||||
document.addEventListener('mouseup', () => {
|
||||
isCompareDragging = false;
|
||||
});
|
||||
|
||||
$compareDivider.addEventListener('mousedown', () => {
|
||||
isCompareDragging = true;
|
||||
});
|
||||
|
||||
// Touch events for mobile
|
||||
document.addEventListener('touchmove', (e) => {
|
||||
if (!isCompareDragging) return;
|
||||
const rect = $player.getBoundingClientRect();
|
||||
const pos = (e.touches[0].clientX - rect.left) / rect.width;
|
||||
updateDividerPosition(pos);
|
||||
}, { passive: true });
|
||||
|
||||
document.addEventListener('touchend', () => {
|
||||
isCompareDragging = false;
|
||||
});
|
||||
|
||||
$compareDivider.addEventListener('touchstart', () => {
|
||||
isCompareDragging = true;
|
||||
});
|
||||
|
||||
// Function to calculate canvas size based on video aspect ratio
|
||||
function calcCanvasSize() {
|
||||
const videoElement = art.video;
|
||||
if (!videoElement) {
|
||||
return { displayWidth: 640, displayHeight: 360 };
|
||||
}
|
||||
|
||||
const containerWidth = $player.offsetWidth || 640;
|
||||
const containerHeight = $player.offsetHeight || 360;
|
||||
const videoWidth = videoElement.videoWidth || 640;
|
||||
const videoHeight = videoElement.videoHeight || 360;
|
||||
const aspectRatio = videoWidth / videoHeight;
|
||||
|
||||
let displayWidth = containerWidth;
|
||||
let displayHeight = containerHeight;
|
||||
|
||||
if (containerWidth / containerHeight > aspectRatio) {
|
||||
// Container is wider than video
|
||||
displayWidth = containerHeight * aspectRatio;
|
||||
} else {
|
||||
// Container is taller than video
|
||||
displayHeight = containerWidth / aspectRatio;
|
||||
}
|
||||
|
||||
return { displayWidth, displayHeight };
|
||||
}
|
||||
|
||||
// Initialize WebGPU and WebSR
|
||||
async function initWebSR() {
|
||||
try {
|
||||
if (isInitialized) return true;
|
||||
|
||||
// Check WebGPU support
|
||||
if (!navigator.gpu) {
|
||||
console.warn('WebGPU is not supported');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Initialize WebGPU
|
||||
gpu = await WebSR.initWebGPU();
|
||||
if (!gpu) {
|
||||
console.warn('Failed to initialize WebGPU');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Load weights
|
||||
let weights;
|
||||
if (typeof option.weights === 'string') {
|
||||
// If weights is a URL, fetch it
|
||||
const weightResponse = await fetch(option.weights);
|
||||
if (!weightResponse.ok) {
|
||||
console.warn(`Failed to load weights from ${option.weights}`);
|
||||
return false;
|
||||
}
|
||||
weights = await weightResponse.json();
|
||||
} else if (typeof option.weights === 'object') {
|
||||
// If weights is an object, use it directly
|
||||
weights = option.weights;
|
||||
} else {
|
||||
console.warn('Invalid weights format');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create WebSR instance
|
||||
const videoElement = art.video;
|
||||
if (!videoElement) {
|
||||
console.warn('Video element not found');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Set canvas dimensions based on video aspect ratio
|
||||
const { displayWidth, displayHeight } = calcCanvasSize();
|
||||
$canvas.width = displayWidth * option.scale;
|
||||
$canvas.height = displayHeight * option.scale;
|
||||
setStyles($canvas, {
|
||||
width: displayWidth + 'px',
|
||||
height: displayHeight + 'px',
|
||||
});
|
||||
|
||||
websr = new WebSR({
|
||||
source: videoElement,
|
||||
network_name: option.networkName,
|
||||
weights: weights,
|
||||
gpu: gpu,
|
||||
canvas: $canvas,
|
||||
});
|
||||
|
||||
isInitialized = true;
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('WebSR initialization error:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Render single frame
|
||||
async function renderSingleFrame() {
|
||||
if (!websr || !isEnabled || !art.video) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await websr.render(art.video);
|
||||
} catch (error) {
|
||||
console.error('WebSR render error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Render frame function
|
||||
async function renderFrame() {
|
||||
if (!websr || !isEnabled || !art.video || art.video.paused) {
|
||||
renderFrameId = null;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await websr.render(art.video);
|
||||
} catch (error) {
|
||||
console.error('WebSR render error:', error);
|
||||
}
|
||||
|
||||
// Continue rendering
|
||||
if (isEnabled && !art.video.paused) {
|
||||
renderFrameId = requestAnimationFrame(renderFrame);
|
||||
}
|
||||
}
|
||||
|
||||
// Enable WebSR
|
||||
async function enable() {
|
||||
if (isEnabled) return;
|
||||
|
||||
if (!isInitialized) {
|
||||
const initialized = await initWebSR();
|
||||
if (!initialized) {
|
||||
console.error('Failed to initialize WebSR');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
isEnabled = true;
|
||||
setStyle($canvas, 'display', 'block');
|
||||
|
||||
// Start rendering if video is playing
|
||||
if (art.video && !art.video.paused) {
|
||||
renderFrameId = requestAnimationFrame(renderFrame);
|
||||
}
|
||||
|
||||
art.emit('artplayerPluginWebsr:enable');
|
||||
}
|
||||
|
||||
// Disable WebSR
|
||||
function disable() {
|
||||
if (!isEnabled) return;
|
||||
|
||||
isEnabled = false;
|
||||
setStyles($canvas, {
|
||||
display: 'none',
|
||||
});
|
||||
|
||||
// Cancel ongoing render
|
||||
if (renderFrameId) {
|
||||
cancelAnimationFrame(renderFrameId);
|
||||
renderFrameId = null;
|
||||
}
|
||||
|
||||
art.emit('artplayerPluginWebsr:disable');
|
||||
}
|
||||
|
||||
// Toggle WebSR
|
||||
async function toggle() {
|
||||
if (isEnabled) {
|
||||
disable();
|
||||
} else {
|
||||
await enable();
|
||||
}
|
||||
}
|
||||
|
||||
// Listen to video events
|
||||
art.on('play', () => {
|
||||
renderSingleFrame(); // Render current frame immediately
|
||||
if (isEnabled && isInitialized && !renderFrameId) {
|
||||
renderFrameId = requestAnimationFrame(renderFrame);
|
||||
}
|
||||
});
|
||||
|
||||
art.on('pause', () => {
|
||||
if (renderFrameId) {
|
||||
cancelAnimationFrame(renderFrameId);
|
||||
renderFrameId = null;
|
||||
}
|
||||
});
|
||||
|
||||
art.on('seek', () => {
|
||||
if (isEnabled && isInitialized && !art.video.paused && !renderFrameId) {
|
||||
renderFrameId = requestAnimationFrame(renderFrame);
|
||||
}
|
||||
});
|
||||
|
||||
art.on('resize', () => {
|
||||
if (websr && $canvas.offsetParent) {
|
||||
const { displayWidth, displayHeight } = calcCanvasSize();
|
||||
$canvas.width = displayWidth * option.scale;
|
||||
$canvas.height = displayHeight * option.scale;
|
||||
setStyles($canvas, {
|
||||
width: displayWidth + 'px',
|
||||
height: displayHeight + 'px',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
art.on('destroy', () => {
|
||||
disable();
|
||||
if (renderFrameId) {
|
||||
cancelAnimationFrame(renderFrameId);
|
||||
renderFrameId = null;
|
||||
}
|
||||
if ($canvas.parentNode) {
|
||||
$canvas.parentNode.removeChild($canvas);
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize if enabled by default
|
||||
initWebSR().then(() => {
|
||||
// Render first frame after initialization
|
||||
if (isEnabled && isInitialized && art.video) {
|
||||
renderSingleFrame();
|
||||
}
|
||||
}).catch(err => console.error('Failed to init WebSR:', err));
|
||||
|
||||
// Return plugin API
|
||||
return {
|
||||
name: 'artplayerPluginWebsr',
|
||||
websr: () => websr,
|
||||
gpu: () => gpu,
|
||||
canvas: () => $canvas,
|
||||
enable,
|
||||
disable,
|
||||
toggle,
|
||||
isEnabled: () => isEnabled,
|
||||
isInitialized: () => isInitialized,
|
||||
// Comparison mode methods
|
||||
enableCompare: () => {
|
||||
option.compare = true;
|
||||
setStyles($compareDivider, { display: 'block' });
|
||||
updateDividerPosition(comparePosition);
|
||||
},
|
||||
disableCompare: () => {
|
||||
option.compare = false;
|
||||
setStyles($compareDivider, { display: 'none' });
|
||||
setStyles($canvas, { clipPath: 'none' });
|
||||
},
|
||||
toggleCompare: () => {
|
||||
if (option.compare) {
|
||||
setStyles($compareDivider, { display: 'none' });
|
||||
setStyles($canvas, { clipPath: 'none' });
|
||||
option.compare = false;
|
||||
} else {
|
||||
option.compare = true;
|
||||
setStyles($compareDivider, { display: 'block' });
|
||||
updateDividerPosition(comparePosition);
|
||||
}
|
||||
},
|
||||
setComparePosition: (pos) => {
|
||||
updateDividerPosition(pos);
|
||||
},
|
||||
getComparePosition: () => comparePosition,
|
||||
isComparing: () => option.compare,
|
||||
update: async (newOption) => {
|
||||
// Update weights and networkName (requires re-initialization)
|
||||
if ((newOption.weights !== undefined && newOption.weights !== option.weights) ||
|
||||
(newOption.networkName !== undefined && newOption.networkName !== option.networkName)) {
|
||||
// Update option values
|
||||
if (newOption.weights !== undefined) {
|
||||
option.weights = newOption.weights;
|
||||
}
|
||||
if (newOption.networkName !== undefined) {
|
||||
option.networkName = newOption.networkName;
|
||||
}
|
||||
// Mark as uninitialized to reload with new config
|
||||
isInitialized = false;
|
||||
// Reinitialize if enabled
|
||||
if (isEnabled) {
|
||||
await initWebSR();
|
||||
}
|
||||
}
|
||||
|
||||
// Update scale factor
|
||||
if (newOption.scale !== undefined && newOption.scale !== option.scale) {
|
||||
option.scale = newOption.scale;
|
||||
if ($canvas) {
|
||||
const { displayWidth, displayHeight } = calcCanvasSize();
|
||||
$canvas.width = displayWidth * option.scale;
|
||||
$canvas.height = displayHeight * option.scale;
|
||||
setStyles($canvas, {
|
||||
width: displayWidth + 'px',
|
||||
height: displayHeight + 'px',
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.artplayerPluginWebsr = artplayerPluginWebsr;
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import type Artplayer from 'artplayer';
|
||||
|
||||
interface Option {
|
||||
/**
|
||||
* Upscale factor
|
||||
* @default 2
|
||||
*/
|
||||
scale?: number;
|
||||
/**
|
||||
* Network name for upscaling (required)
|
||||
* e.g., 'anime4k/cnn-2x-m-an'
|
||||
*/
|
||||
networkName: string;
|
||||
/**
|
||||
* Weights for the neural network (required)
|
||||
* Can be a URL string or a pre-loaded weights object
|
||||
* e.g., '/path/to/weights.json' or { layers: [...] }
|
||||
*/
|
||||
weights: string | object;
|
||||
/**
|
||||
* Enable comparison mode
|
||||
* @default false
|
||||
*/
|
||||
compare?: boolean;
|
||||
}
|
||||
|
||||
interface Result {
|
||||
name: 'artplayerPluginWebsr';
|
||||
/**
|
||||
* Get WebSR instance
|
||||
*/
|
||||
websr: () => any;
|
||||
/**
|
||||
* Get GPU context
|
||||
*/
|
||||
gpu: () => any;
|
||||
/**
|
||||
* Get canvas element
|
||||
*/
|
||||
canvas: () => HTMLCanvasElement;
|
||||
/**
|
||||
* Enable WebSR upscaling
|
||||
*/
|
||||
enable: () => Promise<void>;
|
||||
/**
|
||||
* Disable WebSR upscaling
|
||||
*/
|
||||
disable: () => void;
|
||||
/**
|
||||
* Toggle WebSR upscaling
|
||||
*/
|
||||
toggle: () => Promise<void>;
|
||||
/**
|
||||
* Check if WebSR is enabled
|
||||
*/
|
||||
isEnabled: () => boolean;
|
||||
/**
|
||||
* Check if WebSR is initialized
|
||||
*/
|
||||
isInitialized: () => boolean;
|
||||
/**
|
||||
* Update options at runtime
|
||||
* Supported options: enabled, weights, networkName, scale
|
||||
*/
|
||||
update: (option: Partial<Option>) => Promise<void>;
|
||||
/**
|
||||
* Enable comparison mode
|
||||
*/
|
||||
enableCompare: () => void;
|
||||
/**
|
||||
* Disable comparison mode
|
||||
*/
|
||||
disableCompare: () => void;
|
||||
/**
|
||||
* Toggle comparison mode
|
||||
*/
|
||||
toggleCompare: () => void;
|
||||
/**
|
||||
* Set comparison split position (0-1)
|
||||
*/
|
||||
setComparePosition: (pos: number) => void;
|
||||
/**
|
||||
* Get current comparison split position (0-1)
|
||||
*/
|
||||
getComparePosition: () => number;
|
||||
/**
|
||||
* Check if comparison mode is enabled
|
||||
*/
|
||||
isComparing: () => boolean;
|
||||
}
|
||||
|
||||
declare const artplayerPluginWebsr: (option?: Option) => (art: Artplayer) => Result;
|
||||
|
||||
export default artplayerPluginWebsr
|
||||
Reference in new issue
Block a user