diff --git a/.gitattributes b/.gitattributes index dd32d6cac..5b90c6890 100644 --- a/.gitattributes +++ b/.gitattributes @@ -9,3 +9,5 @@ test/browser/media/dash/*.m4s binary test/browser/media/*.m4a binary refactor/baselines/core-vendor/*.txt text eol=lf refactor/baselines/thumbnail-vendor/* text eol=lf whitespace=-blank-at-eof +# Preserve the exact upstream WebVTT reference bytes, including license trailing lines. +refactor/baselines/multiple-subtitles-vendor/* text eol=lf whitespace=-blank-at-eof diff --git a/docs/compiled/artplayer-plugin-multiple-subtitles.js b/docs/compiled/artplayer-plugin-multiple-subtitles.js index 749450150..5c7e6eafb 100644 --- a/docs/compiled/artplayer-plugin-multiple-subtitles.js +++ b/docs/compiled/artplayer-plugin-multiple-subtitles.js @@ -3,5 +3,56 @@ * Github: https://github.com/zhw2590582/ArtPlayer * (c) 2017-2026 Harvey Zhao * Released under the MIT License. + * + * This package includes WebVTT parser and serializer code from w3c/webvtt.js. + * Reference revision: 380cfcce34ba8b472d3a31474874eb72a0e5f460 + * https://github.com/w3c/webvtt.js/tree/380cfcce34ba8b472d3a31474874eb72a0e5f460 + * The parser has a CC0 public-domain dedication. Local adaptations replace + * the IIFE/global exports with named ESM exports and format the code. + * The ArtPlayer plugin wrapper remains MIT licensed. + * + * ## creative commons + * + * # CC0 1.0 Universal + * + * CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + * + * ### Statement of Purpose + * + * The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + * + * Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + * + * For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + * + * 1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + * + * i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; + * + * ii. moral rights retained by the original author(s) and/or performer(s); + * + * iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; + * + * iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; + * + * v. rights protecting the extraction, dissemination, use and reuse of data in a Work; + * + * vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and + * + * vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + * + * 2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + * + * 3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + * + * 4. __Limitations and Disclaimers.__ + * + * a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. + * + * b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. + * + * c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. + * + * d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. */ -!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(t.artplayerPluginMultipleSubtitles=t(),define(function(){return t.artplayerPluginMultipleSubtitles})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerPluginMultipleSubtitles=t()}(this,function(){"use strict";var e={direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center"},t=function(t){t||(t={"&":"&","<":"<",">":">","&lrm":"\u200e","&rlm":"\u200f"," ":"\xa0"}),this.entities=t,this.parse=function(a,s){a=a.replace(/\0/g,"\ufffd");var r=Date.now(),o=0,l=a.split(/\r\n|\r|\n/),f=!1,c=[],u=[],d=[];function p(e,t){d.push({message:e,line:o+1,col:t})}var m=l[o],g=m.length,h="WEBVTT",v=0,b=6;for("\ufeff"===m[0]&&(v=1,b+=1),(gb&&" "!==m[b]&&"\t"!==m[b])&&p('No valid signature. (File needs to start with "WEBVTT".)'),o++;""!=l[o]&&void 0!=l[o];){if(p("No blank line after the signature."),-1!=l[o].indexOf("--\x3e")){f=!0;break}o++}for(;void 0!=l[o];){for(var x;!f&&""==l[o];)o++;if(!f&&void 0==l[o])break;x=Object.assign({},e,{id:"",startTime:0,endTime:0,pauseOnExit:!1,direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center",text:"",tree:null});var T=!0;if(-1==l[o].indexOf("--\x3e")){if(x.id=l[o],/^NOTE($|[ \t])/.test(x.id)){for(o++;""!=l[o]&&void 0!=l[o];)-1!=l[o].indexOf("--\x3e")&&p("Cannot have timestamp in a comment."),o++;continue}if(/^STYLE($|[ \t])/.test(x.id)){var y=[],w=!1;for(o++;""!=l[o]&&void 0!=l[o];)-1!=l[o].indexOf("--\x3e")&&(p("Cannot have timestamp in a style block."),w=!0),y.push(l[o]),o++;if(u.length){p("Style blocks cannot appear after the first cue.");continue}w||c.push(y.join("\n"));continue}if(""==l[++o]||void 0==l[o]){p("Cue identifier cannot be standalone.");continue}if(-1==l[o].indexOf("--\x3e")){T=!1,p("Cue identifier needs to be followed by timestamp.");continue}}f=!1;var O=new n(l[o],p),L=0;if(u.length>0&&(L=u[u.length-1].startTime),!T||O.parse(x,L)){for(o++;""!=l[o]&&void 0!=l[o];){if(-1!=l[o].indexOf("--\x3e")){p("Blank line missing before cue."),f=!0;break}""!=x.text&&(x.text+="\n"),x.text+=l[o],o++}var I=new i(x.text,p,s,t);x.tree=I.parse(x.startTime,x.endTime),u.push(x)}else for(x=null,o++;""!=l[o]&&void 0!=l[o];){if(-1!=l[o].indexOf("--\x3e")){f=!0;break}o++}}return u.sort(function(e,t){return e.startTimet.startTime?1:e.endTime>t.endTime?-1:e.endTime2||parseInt(t,10)>59)&&(l="hours"),":"==e[a])if(a++,2==(n=o(/\d/)).length){if("hours"==l||":"==e[a]){if(":"!=e[a])return void s("No seconds found or minutes is greater than 59.");if(a++,2!=(i=o(/\d/)).length)return void s("Must be exactly two digits.")}else{if(2!=t.length)return void s("Must be exactly two digits.");i=n,n=t,t="0"}if("."==e[a])if(a++,3==(r=o(/\d/)).length)if(parseInt(n,10)>59)s("You cannot have more than 59 minutes.");else{if(!(parseInt(i,10)>59))return 60*parseInt(t,10)*60+60*parseInt(n,10)+parseInt(i,10)+parseInt(r,10)/1e3;s("You cannot have more than 59 seconds.")}else s("Milliseconds must be given in three digits.");else s('No decimal separator (".") found.')}else s("Must be exactly two digits.");else s("No time unit separator found.");else s("Timestamp must start with a character in the range 0-9.");else s("No timestamp found.")}this.parse=function(t,o){if(r(n),t.startTime=l(),void 0!=t.startTime)if(t.startTime"==e[a]){if(a++,i.test(e[a])&&s("'--\x3e' not separated from timestamp by whitespace."),r(n),t.endTime=l(),void 0!=t.endTime)return t.endTime<=t.startTime&&s("End timestamp is not greater than start timestamp."),i.test(e[a]),r(n),function(e,t){for(var i=e.split(n),a=[],r=0;r100)){s("Line position cannot be >100%.");continue}if(""===d||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==u){if(!["start","center","end"].includes(u)){s("Line alignment needs to be one of start, center or end");continue}t.lineAlign=u}t.snapToLines=!p,t.linePosition=parseFloat(d),parseFloat(d).toString()!==d&&(t.nonSerializable=!0)}else if("position"==l){if(/,/.test(f)){c=f.split(","),f=c[0];var m=c[1]}if("%"!=f[f.length-1]){s("Text position must be a percentage.");continue}if(parseInt(f,10)>100||parseInt(f,10)<0){s("Text position needs to be between 0 and 100%.");continue}if(""===(d=f.slice(0,f.length-1))||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==m){if(!["line-left","center","line-right"].includes(m)){s("Position alignment needs to be one of line-left, center or line-right");continue}t.positionAlign=m}t.textPosition=parseFloat(d)}else if("size"==l){if("%"!=f[f.length-1]){s("Size must be a percentage.");continue}if(parseInt(f,10)>100){s("Size cannot be >100%.");continue}var g=f.slice(0,f.length-1);if(void 0===g||""===g||isNaN(g)){s("Size needs to be a number"),g=100;continue}if((g=parseFloat(g))<0||g>100){s("Size needs to be between 0 and 100%.");continue}t.size=g}else if("align"==l){var h=["start","center","end","left","right"];if(-1==h.indexOf(f)){s("Alignment can only be set to one of "+h.join(", ")+".");continue}t.alignment=f}else s("Invalid setting.")}}(e.substring(a),t),!0}else s("No valid timestamp separator found.");else s("No valid timestamp separator found.");else s("No valid timestamp separator found.")},this.parseTimestamp=function(){var t=l();if(void 0==e[a])return t;s("Timestamp must not have trailing characters.")}},i=function(e,t,i,a){this.entities=a;var s=this,r=(e=e,0),o=function(e){"metadata"!=i&&t(e,r+1)};function l(){for(var t="data",n="",i="",l=[];void 0!=e[r-1]||0==r;){var f=e[r];if("data"==t)if("&"==f)i=f,t="escape";else if("<"==f&&""==n)t="tag";else{if("<"==f||void 0==f)return["text",n];n+=f}else if("escape"==t){if("<"==f||void 0==f){let e;return o("Incorrect escape."),(e=i.match(/^&#([0-9]+)$/))?n+=String.fromCharCode(e[1]):s.entities[i]?n+=s.entities[i]:n+=i,["text",n]}if("&"==f)o("Incorrect escape."),n+=i,i=f;else if(/[a-z#0-9]/i.test(f))i+=f;else if(";"==f){let e;(e=i.match(/^&#(x?[0-9]+)$/))?n+=String.fromCharCode("0"+e[1]):s.entities[i+f]?n+=s.entities[i+f]:(e=Object.keys(a).find(e=>i.startsWith(e)))?n+=s.entities[e]+i.slice(e.length)+f:(o("Incorrect escape."),n+=i+";"),t="data"}else o("Incorrect escape."),n+=i+f,t="data"}else if("tag"==t)if("\t"==f||"\n"==f||"\f"==f||" "==f)t="start tag annotation";else if("."==f)t="start tag class";else if("/"==f)t="end tag";else if(/\d/.test(f))n=f,t="timestamp tag";else{if(">"==f||void 0==f)return">"==f&&r++,["start tag","",[],""];n=f,t="start tag"}else if("start tag"==t)if("\t"==f||"\f"==f||" "==f)t="start tag annotation";else if("\n"==f)i=f,t="start tag annotation";else if("."==f)t="start tag class";else{if(">"==f||void 0==f)return">"==f&&r++,["start tag",n,[],""];n+=f}else if("start tag class"==t)if("\t"==f||"\f"==f||" "==f)i&&l.push(i),i="",t="start tag annotation";else if("\n"==f)i&&l.push(i),i=f,t="start tag annotation";else if("."==f)i&&l.push(i),i="";else{if(">"==f||void 0==f)return">"==f&&r++,i&&l.push(i),["start tag",n,l,""];i+=f}else if("start tag annotation"==t){if(">"==f||void 0==f)return">"==f&&r++,["start tag",n,l,i=i.split(/[\u0020\t\f\r\n]+/).filter(function(e){if(e)return!0}).join(" ")];i+=f}else if("end tag"==t){if(">"==f||void 0==f)return">"==f&&r++,["end tag",n];n+=f}else if("timestamp tag"==t){if(">"==f||void 0==f)return">"==f&&r++,["timestamp",n];n+=f}else o("Never happens.");r++}}this.parse=function(t,a){var s={children:[]},f=s,c=[];function u(e){f.children.push({type:"object",name:e[1],classes:e[2],children:[],parent:f}),f=f.children[f.children.length-1]}function d(e){for(var t=f;t;){if(t.name==e)return!0;t=t.parent}}for(;void 0!=e[r];){var p=l();if("text"==p[0])f.children.push({type:"text",value:p[1],parent:f});else if("start tag"==p[0]){"chapters"==i&&o("Start tags not allowed in chapter title text.");var m=p[1];"v"!=m&&"lang"!=m&&""!=p[3]&&o("Only and can have an annotation."),"c"==m||"i"==m||"b"==m||"u"==m||"ruby"==m||"rt"==m&&"ruby"==f.name?u(p):"v"==m?(d("v")&&o(" cannot be nested inside itself."),u(p),f.value=p[3],p[3]||o(" requires an annotation.")):"lang"==m?(u(p),f.value=p[3]):o("Incorrect start tag.")}else if("end tag"==p[0])"chapters"==i&&o("End tags not allowed in chapter title text."),p[1]==f.name?f=f.parent:"ruby"==p[1]&&"rt"==f.name?f=f.parent.parent:o("Incorrect end tag.");else if("timestamp"==p[0]){"chapters"==i&&o("Timestamp not allowed in chapter title text.");var g=new n(p[1],o).parseTimestamp();void 0!=g&&((g<=t||g>=a)&&o("Timestamp must be between start timestamp and end timestamp."),c.length>0&&c[c.length-1]>=g&&o("Timestamp must be greater than any previous timestamp."),f.children.push({type:"timestamp",value:g,parent:f}),c.push(g))}}for(;f.parent;)"v"!=f.name&&o("Required end tag missing."),f=f.parent;return function e(t){const n={...t};return t.children&&(n.children=t.children.map(e)),n.parent&&delete n.parent,n}(s)}},a=function(){function t(e){const t=("00"+1e3*(e-Math.floor(e)).toFixed(3)).slice(-3);let n=0,i=0,a=0;return e>=3600&&(n=Math.floor(e/3600)),i=Math.floor((e-3600*n)/60),a=Math.floor(e-3600*n-60*i),(n?n+":":"")+(""+i).padStart(2,"0")+":"+(""+a).padStart(2,"0")+"."+t}function n(e){for(var i="",a=0;a/g,">");else if("object"==s.type){if(i+="<"+s.name,s.classes)for(var r=0;r"}else"timestamp"==s.type?i+="<"+t(s.value)+">":i+="<"+s.value+">"}return i}function i(i){return(void 0!==i.id?i.id+"\n":"")+t(i.startTime)+" --\x3e "+t(i.endTime)+function(t){var n="";const i=Object.keys(e).filter(n=>t[n]!==e[n]);return i.includes("direction")&&(n+=" vertical:"+t.direction),i.includes("alignment")&&(n+=" align:"+t.alignment),i.includes("size")&&(n+=" size:"+t.size+"%"),(i.includes("lineAlign")||i.includes("linePosition"))&&(n+=" line:"+t.linePosition+(t.snapToLines?"":"%")+(t.lineAlign&&t.lineAlign!=e.lineAlign?","+t.lineAlign:"")),(i.includes("textPosition")||i.includes("positionAlign"))&&(n+=" position:"+t.textPosition+"%"+(t.positionAlign&&t.positionAlign!==e.positionAlign?","+t.positionAlign:"")),n}(i)+"\n"+n(i.tree.children)+"\n\n"}function a(e){return"STYLE\n"+e+"\n\n"}this.serialize=function(e,t){var n="WEBVTT\n\n";if(t)for(var s=0;s{const{unescape:i,getExt:s,srtToVtt:r,assToVtt:o}=n.constructor.utils,l=new t,f=new a,c=await Promise.all(e.map(e=>async function(e,{getExt:t,srtToVtt:n,assToVtt:i}){const a=await fetch(e.url),s=await a.arrayBuffer(),r=new TextDecoder(e.encoding||"utf-8").decode(s);switch(e.type||t(e.url)){case"srt":return n(r);case"ass":return i(r);case"vtt":return r;default:return""}}(e,{getExt:s,srtToVtt:r,assToVtt:o}))),u=c.map((t,n)=>{const i=l.parse(t,"metadata");return i.url=e[n].url,i.name=e[n].name,i});let d="";function p(e=[]){const a=function(e){const n=(new t).parse("","metadata");for(let t=0;t${n.value}`}}}n.cues.push(...i.cues)}return n}(e),s=f.serialize(a.cues);URL.revokeObjectURL(d);const r=URL.createObjectURL(new Blob([s],{type:"text/vtt"}));d=r,n.option.subtitle.escape=!1,n.subtitle.init({...n.option.subtitle,url:r,type:"vtt",onVttLoad:i})}return p(u),{name:"multipleSubtitles",tracks:(e=[])=>p(e.map(e=>u.find(t=>t.name===e))),reset:()=>p(u)}}}}); +!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerPluginMultipleSubtitles=t(),define(function(){return e.artplayerPluginMultipleSubtitles})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerPluginMultipleSubtitles=t()}(this,function(){"use strict";var e={direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center"},t=function(t){t||(t={"&":"&","<":"<",">":">","&lrm":"\u200e","&rlm":"\u200f"," ":"\xa0"}),this.entities=t,this.parse=function(a,s){a=a.replace(/\0/g,"\ufffd");var r=Date.now(),o=0,l=a.split(/\r\n|\r|\n/),f=!1,c=[],u=[],d=[];function p(e,t){d.push({message:e,line:o+1,col:t})}var m=l[o],g=m.length,h="WEBVTT",v=0,b=6;for("\ufeff"===m[0]&&(v=1,b+=1),(gb&&" "!==m[b]&&"\t"!==m[b])&&p('No valid signature. (File needs to start with "WEBVTT".)'),o++;""!=l[o]&&void 0!=l[o];){if(p("No blank line after the signature."),-1!=l[o].indexOf("--\x3e")){f=!0;break}o++}for(;void 0!=l[o];){for(var x;!f&&""==l[o];)o++;if(!f&&void 0==l[o])break;x=Object.assign({},e,{id:"",startTime:0,endTime:0,pauseOnExit:!1,direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center",text:"",tree:null});var T=!0;if(-1==l[o].indexOf("--\x3e")){if(x.id=l[o],/^NOTE($|[ \t])/.test(x.id)){for(o++;""!=l[o]&&void 0!=l[o];)-1!=l[o].indexOf("--\x3e")&&p("Cannot have timestamp in a comment."),o++;continue}if(/^STYLE($|[ \t])/.test(x.id)){var y=[],w=!1;for(o++;""!=l[o]&&void 0!=l[o];)-1!=l[o].indexOf("--\x3e")&&(p("Cannot have timestamp in a style block."),w=!0),y.push(l[o]),o++;if(u.length){p("Style blocks cannot appear after the first cue.");continue}w||c.push(y.join("\n"));continue}if(""==l[++o]||void 0==l[o]){p("Cue identifier cannot be standalone.");continue}if(-1==l[o].indexOf("--\x3e")){T=!1,p("Cue identifier needs to be followed by timestamp.");continue}}f=!1;var O=new n(l[o],p),L=0;if(u.length>0&&(L=u[u.length-1].startTime),!T||O.parse(x,L)){for(o++;""!=l[o]&&void 0!=l[o];){if(-1!=l[o].indexOf("--\x3e")){p("Blank line missing before cue."),f=!0;break}""!=x.text&&(x.text+="\n"),x.text+=l[o],o++}var I=new i(x.text,p,s,t);x.tree=I.parse(x.startTime,x.endTime),u.push(x)}else for(x=null,o++;""!=l[o]&&void 0!=l[o];){if(-1!=l[o].indexOf("--\x3e")){f=!0;break}o++}}return u.sort(function(e,t){return e.startTimet.startTime?1:e.endTime>t.endTime?-1:e.endTime2||parseInt(t,10)>59)&&(l="hours"),":"==e[a])if(a++,2==(n=o(/\d/)).length){if("hours"==l||":"==e[a]){if(":"!=e[a])return void s("No seconds found or minutes is greater than 59.");if(a++,2!=(i=o(/\d/)).length)return void s("Must be exactly two digits.")}else{if(2!=t.length)return void s("Must be exactly two digits.");i=n,n=t,t="0"}if("."==e[a])if(a++,3==(r=o(/\d/)).length)if(parseInt(n,10)>59)s("You cannot have more than 59 minutes.");else{if(!(parseInt(i,10)>59))return 60*parseInt(t,10)*60+60*parseInt(n,10)+parseInt(i,10)+parseInt(r,10)/1e3;s("You cannot have more than 59 seconds.")}else s("Milliseconds must be given in three digits.");else s('No decimal separator (".") found.')}else s("Must be exactly two digits.");else s("No time unit separator found.");else s("Timestamp must start with a character in the range 0-9.");else s("No timestamp found.")}this.parse=function(t,o){if(r(n),t.startTime=l(),void 0!=t.startTime)if(t.startTime"==e[a]){if(a++,i.test(e[a])&&s("'--\x3e' not separated from timestamp by whitespace."),r(n),t.endTime=l(),void 0!=t.endTime)return t.endTime<=t.startTime&&s("End timestamp is not greater than start timestamp."),i.test(e[a]),r(n),function(e,t){for(var i=e.split(n),a=[],r=0;r100)){s("Line position cannot be >100%.");continue}if(""===d||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==u){if(!["start","center","end"].includes(u)){s("Line alignment needs to be one of start, center or end");continue}t.lineAlign=u}t.snapToLines=!p,t.linePosition=parseFloat(d),parseFloat(d).toString()!==d&&(t.nonSerializable=!0)}else if("position"==l){if(/,/.test(f)){c=f.split(","),f=c[0];var m=c[1]}if("%"!=f[f.length-1]){s("Text position must be a percentage.");continue}if(parseInt(f,10)>100||parseInt(f,10)<0){s("Text position needs to be between 0 and 100%.");continue}if(""===(d=f.slice(0,f.length-1))||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==m){if(!["line-left","center","line-right"].includes(m)){s("Position alignment needs to be one of line-left, center or line-right");continue}t.positionAlign=m}t.textPosition=parseFloat(d)}else if("size"==l){if("%"!=f[f.length-1]){s("Size must be a percentage.");continue}if(parseInt(f,10)>100){s("Size cannot be >100%.");continue}var g=f.slice(0,f.length-1);if(void 0===g||""===g||isNaN(g)){s("Size needs to be a number"),g=100;continue}if((g=parseFloat(g))<0||g>100){s("Size needs to be between 0 and 100%.");continue}t.size=g}else if("align"==l){var h=["start","center","end","left","right"];if(-1==h.indexOf(f)){s("Alignment can only be set to one of "+h.join(", ")+".");continue}t.alignment=f}else s("Invalid setting.")}}(e.substring(a),t),!0}else s("No valid timestamp separator found.");else s("No valid timestamp separator found.");else s("No valid timestamp separator found.")},this.parseTimestamp=function(){var t=l();if(void 0==e[a])return t;s("Timestamp must not have trailing characters.")}},i=function(e,t,i,a){this.entities=a;var s=this,r=(e=e,0),o=function(e){"metadata"!=i&&t(e,r+1)};function l(){for(var t="data",n="",i="",l=[];void 0!=e[r-1]||0==r;){var f=e[r];if("data"==t)if("&"==f)i=f,t="escape";else if("<"==f&&""==n)t="tag";else{if("<"==f||void 0==f)return["text",n];n+=f}else if("escape"==t){if("<"==f||void 0==f){let e;return o("Incorrect escape."),(e=i.match(/^&#([0-9]+)$/))?n+=String.fromCharCode(e[1]):s.entities[i]?n+=s.entities[i]:n+=i,["text",n]}if("&"==f)o("Incorrect escape."),n+=i,i=f;else if(/[a-z#0-9]/i.test(f))i+=f;else if(";"==f){let e;(e=i.match(/^&#(x?[0-9]+)$/))?n+=String.fromCharCode("0"+e[1]):s.entities[i+f]?n+=s.entities[i+f]:(e=Object.keys(a).find(e=>i.startsWith(e)))?n+=s.entities[e]+i.slice(e.length)+f:(o("Incorrect escape."),n+=i+";"),t="data"}else o("Incorrect escape."),n+=i+f,t="data"}else if("tag"==t)if("\t"==f||"\n"==f||"\f"==f||" "==f)t="start tag annotation";else if("."==f)t="start tag class";else if("/"==f)t="end tag";else if(/\d/.test(f))n=f,t="timestamp tag";else{if(">"==f||void 0==f)return">"==f&&r++,["start tag","",[],""];n=f,t="start tag"}else if("start tag"==t)if("\t"==f||"\f"==f||" "==f)t="start tag annotation";else if("\n"==f)i=f,t="start tag annotation";else if("."==f)t="start tag class";else{if(">"==f||void 0==f)return">"==f&&r++,["start tag",n,[],""];n+=f}else if("start tag class"==t)if("\t"==f||"\f"==f||" "==f)i&&l.push(i),i="",t="start tag annotation";else if("\n"==f)i&&l.push(i),i=f,t="start tag annotation";else if("."==f)i&&l.push(i),i="";else{if(">"==f||void 0==f)return">"==f&&r++,i&&l.push(i),["start tag",n,l,""];i+=f}else if("start tag annotation"==t){if(">"==f||void 0==f)return">"==f&&r++,["start tag",n,l,i=i.split(/[\u0020\t\f\r\n]+/).filter(function(e){if(e)return!0}).join(" ")];i+=f}else if("end tag"==t){if(">"==f||void 0==f)return">"==f&&r++,["end tag",n];n+=f}else if("timestamp tag"==t){if(">"==f||void 0==f)return">"==f&&r++,["timestamp",n];n+=f}else o("Never happens.");r++}}this.parse=function(t,a){var s={children:[]},f=s,c=[];function u(e){f.children.push({type:"object",name:e[1],classes:e[2],children:[],parent:f}),f=f.children[f.children.length-1]}function d(e){for(var t=f;t;){if(t.name==e)return!0;t=t.parent}}for(;void 0!=e[r];){var p=l();if("text"==p[0])f.children.push({type:"text",value:p[1],parent:f});else if("start tag"==p[0]){"chapters"==i&&o("Start tags not allowed in chapter title text.");var m=p[1];"v"!=m&&"lang"!=m&&""!=p[3]&&o("Only and can have an annotation."),"c"==m||"i"==m||"b"==m||"u"==m||"ruby"==m||"rt"==m&&"ruby"==f.name?u(p):"v"==m?(d("v")&&o(" cannot be nested inside itself."),u(p),f.value=p[3],p[3]||o(" requires an annotation.")):"lang"==m?(u(p),f.value=p[3]):o("Incorrect start tag.")}else if("end tag"==p[0])"chapters"==i&&o("End tags not allowed in chapter title text."),p[1]==f.name?f=f.parent:"ruby"==p[1]&&"rt"==f.name?f=f.parent.parent:o("Incorrect end tag.");else if("timestamp"==p[0]){"chapters"==i&&o("Timestamp not allowed in chapter title text.");var g=new n(p[1],o).parseTimestamp();void 0!=g&&((g<=t||g>=a)&&o("Timestamp must be between start timestamp and end timestamp."),c.length>0&&c[c.length-1]>=g&&o("Timestamp must be greater than any previous timestamp."),f.children.push({type:"timestamp",value:g,parent:f}),c.push(g))}}for(;f.parent;)"v"!=f.name&&o("Required end tag missing."),f=f.parent;return function e(t){const n={...t};return t.children&&(n.children=t.children.map(e)),n.parent&&delete n.parent,n}(s)}},a=function(){function t(e){const t=("00"+1e3*(e-Math.floor(e)).toFixed(3)).slice(-3);let n=0,i=0,a=0;return e>=3600&&(n=Math.floor(e/3600)),i=Math.floor((e-3600*n)/60),a=Math.floor(e-3600*n-60*i),(n?n+":":"")+(""+i).padStart(2,"0")+":"+(""+a).padStart(2,"0")+"."+t}function n(e){for(var i="",a=0;a/g,">");else if("object"==s.type){if(i+="<"+s.name,s.classes)for(var r=0;r"}else"timestamp"==s.type?i+="<"+t(s.value)+">":i+="<"+s.value+">"}return i}function i(i){return(void 0!==i.id?i.id+"\n":"")+t(i.startTime)+" --\x3e "+t(i.endTime)+function(t){var n="";const i=Object.keys(e).filter(n=>t[n]!==e[n]);return i.includes("direction")&&(n+=" vertical:"+t.direction),i.includes("alignment")&&(n+=" align:"+t.alignment),i.includes("size")&&(n+=" size:"+t.size+"%"),(i.includes("lineAlign")||i.includes("linePosition"))&&(n+=" line:"+t.linePosition+(t.snapToLines?"":"%")+(t.lineAlign&&t.lineAlign!=e.lineAlign?","+t.lineAlign:"")),(i.includes("textPosition")||i.includes("positionAlign"))&&(n+=" position:"+t.textPosition+"%"+(t.positionAlign&&t.positionAlign!==e.positionAlign?","+t.positionAlign:"")),n}(i)+"\n"+n(i.tree.children)+"\n\n"}function a(e){return"STYLE\n"+e+"\n\n"}this.serialize=function(e,t){var n="WEBVTT\n\n";if(t)for(var s=0;s{const{unescape:i,getExt:s,srtToVtt:r,assToVtt:o}=n.constructor.utils,l=new t,f=new a,c=await Promise.all(e.map(e=>async function(e,{getExt:t,srtToVtt:n,assToVtt:i}){const a=await fetch(e.url),s=await a.arrayBuffer(),r=new TextDecoder(e.encoding||"utf-8").decode(s);switch(e.type||t(e.url)){case"srt":return n(r);case"ass":return i(r);case"vtt":return r;default:return""}}(e,{getExt:s,srtToVtt:r,assToVtt:o}))),u=c.map((t,n)=>{const i=l.parse(t,"metadata");return i.url=e[n].url,i.name=e[n].name,i});let d="";function p(e=[]){const a=function(e){const n=(new t).parse("","metadata");for(let t=0;t${n.value}`}}}n.cues.push(...i.cues)}return n}(e),s=f.serialize(a.cues);URL.revokeObjectURL(d);const r=URL.createObjectURL(new Blob([s],{type:"text/vtt"}));d=r,n.option.subtitle.escape=!1,n.subtitle.init({...n.option.subtitle,url:r,type:"vtt",onVttLoad:i})}return p(u),{name:"multipleSubtitles",tracks:(e=[])=>p(e.map(e=>u.find(t=>t.name===e))),reset:()=>p(u)}}}}); diff --git a/docs/compiled/artplayer-plugin-multiple-subtitles.legacy.js b/docs/compiled/artplayer-plugin-multiple-subtitles.legacy.js index f6b175bd8..14454c165 100644 --- a/docs/compiled/artplayer-plugin-multiple-subtitles.legacy.js +++ b/docs/compiled/artplayer-plugin-multiple-subtitles.legacy.js @@ -3,5 +3,56 @@ * Github: https://github.com/zhw2590582/ArtPlayer * (c) 2017-2026 Harvey Zhao * Released under the MIT License. + * + * This package includes WebVTT parser and serializer code from w3c/webvtt.js. + * Reference revision: 380cfcce34ba8b472d3a31474874eb72a0e5f460 + * https://github.com/w3c/webvtt.js/tree/380cfcce34ba8b472d3a31474874eb72a0e5f460 + * The parser has a CC0 public-domain dedication. Local adaptations replace + * the IIFE/global exports with named ESM exports and format the code. + * The ArtPlayer plugin wrapper remains MIT licensed. + * + * ## creative commons + * + * # CC0 1.0 Universal + * + * CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + * + * ### Statement of Purpose + * + * The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + * + * Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + * + * For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + * + * 1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + * + * i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; + * + * ii. moral rights retained by the original author(s) and/or performer(s); + * + * iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; + * + * iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; + * + * v. rights protecting the extraction, dissemination, use and reuse of data in a Work; + * + * vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and + * + * vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + * + * 2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + * + * 3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + * + * 4. __Limitations and Disclaimers.__ + * + * a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. + * + * b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. + * + * c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. + * + * d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. */ -!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(t.artplayerPluginMultipleSubtitles=t(),define(function(){return t.artplayerPluginMultipleSubtitles})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerPluginMultipleSubtitles=t()}(this,function(){"use strict";var e=Object.defineProperty,t=Object.defineProperties,n=Object.getOwnPropertyDescriptors,i=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,r=(t,n,i)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[n]=i,o=(e,t)=>{for(var n in t||(t={}))a.call(t,n)&&r(e,n,t[n]);if(i)for(var n of i(t))s.call(t,n)&&r(e,n,t[n]);return e},l=(e,t,n)=>new Promise((i,a)=>{var s=e=>{try{o(n.next(e))}catch(t){a(t)}},r=e=>{try{o(n.throw(e))}catch(t){a(t)}},o=e=>e.done?i(e.value):Promise.resolve(e.value).then(s,r);o((n=n.apply(e,t)).next())}),f={direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center"},c=function(e){e||(e={"&":"&","<":"<",">":">","&lrm":"\u200e","&rlm":"\u200f"," ":"\xa0"}),this.entities=e,this.parse=function(t,n){t=t.replace(/\0/g,"\ufffd");var i=Date.now(),a=0,s=t.split(/\r\n|\r|\n/),r=!1,o=[],l=[],c=[];function p(e,t){c.push({message:e,line:a+1,col:t})}var m=s[a],g=m.length,h="WEBVTT",v=0,b=6;for("\ufeff"===m[0]&&(v=1,b+=1),(gb&&" "!==m[b]&&"\t"!==m[b])&&p('No valid signature. (File needs to start with "WEBVTT".)'),a++;""!=s[a]&&void 0!=s[a];){if(p("No blank line after the signature."),-1!=s[a].indexOf("--\x3e")){r=!0;break}a++}for(;void 0!=s[a];){for(var x;!r&&""==s[a];)a++;if(!r&&void 0==s[a])break;x=Object.assign({},f,{id:"",startTime:0,endTime:0,pauseOnExit:!1,direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center",text:"",tree:null});var T=!0;if(-1==s[a].indexOf("--\x3e")){if(x.id=s[a],/^NOTE($|[ \t])/.test(x.id)){for(a++;""!=s[a]&&void 0!=s[a];)-1!=s[a].indexOf("--\x3e")&&p("Cannot have timestamp in a comment."),a++;continue}if(/^STYLE($|[ \t])/.test(x.id)){var y=[],w=!1;for(a++;""!=s[a]&&void 0!=s[a];)-1!=s[a].indexOf("--\x3e")&&(p("Cannot have timestamp in a style block."),w=!0),y.push(s[a]),a++;if(l.length){p("Style blocks cannot appear after the first cue.");continue}w||o.push(y.join("\n"));continue}if(""==s[++a]||void 0==s[a]){p("Cue identifier cannot be standalone.");continue}if(-1==s[a].indexOf("--\x3e")){T=!1,p("Cue identifier needs to be followed by timestamp.");continue}}r=!1;var O=new u(s[a],p),P=0;if(l.length>0&&(P=l[l.length-1].startTime),!T||O.parse(x,P)){for(a++;""!=s[a]&&void 0!=s[a];){if(-1!=s[a].indexOf("--\x3e")){p("Blank line missing before cue."),r=!0;break}""!=x.text&&(x.text+="\n"),x.text+=s[a],a++}var I=new d(x.text,p,n,e);x.tree=I.parse(x.startTime,x.endTime),l.push(x)}else for(x=null,a++;""!=s[a]&&void 0!=s[a];){if(-1!=s[a].indexOf("--\x3e")){r=!0;break}a++}}return l.sort(function(e,t){return e.startTimet.startTime?1:e.endTime>t.endTime?-1:e.endTime2||parseInt(t,10)>59)&&(l="hours"),":"==e[a])if(a++,2==(n=o(/\d/)).length){if("hours"==l||":"==e[a]){if(":"!=e[a])return void s("No seconds found or minutes is greater than 59.");if(a++,2!=(i=o(/\d/)).length)return void s("Must be exactly two digits.")}else{if(2!=t.length)return void s("Must be exactly two digits.");i=n,n=t,t="0"}if("."==e[a])if(a++,3==(r=o(/\d/)).length)if(parseInt(n,10)>59)s("You cannot have more than 59 minutes.");else{if(!(parseInt(i,10)>59))return 60*parseInt(t,10)*60+60*parseInt(n,10)+parseInt(i,10)+parseInt(r,10)/1e3;s("You cannot have more than 59 seconds.")}else s("Milliseconds must be given in three digits.");else s('No decimal separator (".") found.')}else s("Must be exactly two digits.");else s("No time unit separator found.");else s("Timestamp must start with a character in the range 0-9.");else s("No timestamp found.")}this.parse=function(t,o){if(r(n),t.startTime=l(),void 0!=t.startTime)if(t.startTime"==e[a]){if(a++,i.test(e[a])&&s("'--\x3e' not separated from timestamp by whitespace."),r(n),t.endTime=l(),void 0!=t.endTime)return t.endTime<=t.startTime&&s("End timestamp is not greater than start timestamp."),i.test(e[a]),r(n),function(e,t){for(var i=e.split(n),a=[],r=0;r100)){s("Line position cannot be >100%.");continue}if(""===d||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==u){if(!["start","center","end"].includes(u)){s("Line alignment needs to be one of start, center or end");continue}t.lineAlign=u}t.snapToLines=!p,t.linePosition=parseFloat(d),parseFloat(d).toString()!==d&&(t.nonSerializable=!0)}else if("position"==l){if(/,/.test(f)){c=f.split(","),f=c[0];var m=c[1]}if("%"!=f[f.length-1]){s("Text position must be a percentage.");continue}if(parseInt(f,10)>100||parseInt(f,10)<0){s("Text position needs to be between 0 and 100%.");continue}if(""===(d=f.slice(0,f.length-1))||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==m){if(!["line-left","center","line-right"].includes(m)){s("Position alignment needs to be one of line-left, center or line-right");continue}t.positionAlign=m}t.textPosition=parseFloat(d)}else if("size"==l){if("%"!=f[f.length-1]){s("Size must be a percentage.");continue}if(parseInt(f,10)>100){s("Size cannot be >100%.");continue}var g=f.slice(0,f.length-1);if(void 0===g||""===g||isNaN(g)){s("Size needs to be a number"),g=100;continue}if((g=parseFloat(g))<0||g>100){s("Size needs to be between 0 and 100%.");continue}t.size=g}else if("align"==l){var h=["start","center","end","left","right"];if(-1==h.indexOf(f)){s("Alignment can only be set to one of "+h.join(", ")+".");continue}t.alignment=f}else s("Invalid setting.")}}(e.substring(a),t),!0}else s("No valid timestamp separator found.");else s("No valid timestamp separator found.");else s("No valid timestamp separator found.")},this.parseTimestamp=function(){var t=l();if(void 0==e[a])return t;s("Timestamp must not have trailing characters.")}},d=function(e,t,n,i){this.entities=i;var a=this,s=(e=e,0),r=function(e){"metadata"!=n&&t(e,s+1)};function l(){for(var t="data",n="",o="",l=[];void 0!=e[s-1]||0==s;){var f=e[s];if("data"==t)if("&"==f)o=f,t="escape";else if("<"==f&&""==n)t="tag";else{if("<"==f||void 0==f)return["text",n];n+=f}else if("escape"==t){if("<"==f||void 0==f){let e;return r("Incorrect escape."),(e=o.match(/^&#([0-9]+)$/))?n+=String.fromCharCode(e[1]):a.entities[o]?n+=a.entities[o]:n+=o,["text",n]}if("&"==f)r("Incorrect escape."),n+=o,o=f;else if(/[a-z#0-9]/i.test(f))o+=f;else if(";"==f){let e;(e=o.match(/^&#(x?[0-9]+)$/))?n+=String.fromCharCode("0"+e[1]):a.entities[o+f]?n+=a.entities[o+f]:(e=Object.keys(i).find(e=>o.startsWith(e)))?n+=a.entities[e]+o.slice(e.length)+f:(r("Incorrect escape."),n+=o+";"),t="data"}else r("Incorrect escape."),n+=o+f,t="data"}else if("tag"==t)if("\t"==f||"\n"==f||"\f"==f||" "==f)t="start tag annotation";else if("."==f)t="start tag class";else if("/"==f)t="end tag";else if(/\d/.test(f))n=f,t="timestamp tag";else{if(">"==f||void 0==f)return">"==f&&s++,["start tag","",[],""];n=f,t="start tag"}else if("start tag"==t)if("\t"==f||"\f"==f||" "==f)t="start tag annotation";else if("\n"==f)o=f,t="start tag annotation";else if("."==f)t="start tag class";else{if(">"==f||void 0==f)return">"==f&&s++,["start tag",n,[],""];n+=f}else if("start tag class"==t)if("\t"==f||"\f"==f||" "==f)o&&l.push(o),o="",t="start tag annotation";else if("\n"==f)o&&l.push(o),o=f,t="start tag annotation";else if("."==f)o&&l.push(o),o="";else{if(">"==f||void 0==f)return">"==f&&s++,o&&l.push(o),["start tag",n,l,""];o+=f}else if("start tag annotation"==t){if(">"==f||void 0==f)return">"==f&&s++,["start tag",n,l,o=o.split(/[\u0020\t\f\r\n]+/).filter(function(e){if(e)return!0}).join(" ")];o+=f}else if("end tag"==t){if(">"==f||void 0==f)return">"==f&&s++,["end tag",n];n+=f}else if("timestamp tag"==t){if(">"==f||void 0==f)return">"==f&&s++,["timestamp",n];n+=f}else r("Never happens.");s++}}this.parse=function(t,i){var a={children:[]},f=a,c=[];function d(e){f.children.push({type:"object",name:e[1],classes:e[2],children:[],parent:f}),f=f.children[f.children.length-1]}function p(e){for(var t=f;t;){if(t.name==e)return!0;t=t.parent}}for(;void 0!=e[s];){var m=l();if("text"==m[0])f.children.push({type:"text",value:m[1],parent:f});else if("start tag"==m[0]){"chapters"==n&&r("Start tags not allowed in chapter title text.");var g=m[1];"v"!=g&&"lang"!=g&&""!=m[3]&&r("Only and can have an annotation."),"c"==g||"i"==g||"b"==g||"u"==g||"ruby"==g||"rt"==g&&"ruby"==f.name?d(m):"v"==g?(p("v")&&r(" cannot be nested inside itself."),d(m),f.value=m[3],m[3]||r(" requires an annotation.")):"lang"==g?(d(m),f.value=m[3]):r("Incorrect start tag.")}else if("end tag"==m[0])"chapters"==n&&r("End tags not allowed in chapter title text."),m[1]==f.name?f=f.parent:"ruby"==m[1]&&"rt"==f.name?f=f.parent.parent:r("Incorrect end tag.");else if("timestamp"==m[0]){"chapters"==n&&r("Timestamp not allowed in chapter title text.");var h=new u(m[1],r).parseTimestamp();void 0!=h&&((h<=t||h>=i)&&r("Timestamp must be between start timestamp and end timestamp."),c.length>0&&c[c.length-1]>=h&&r("Timestamp must be greater than any previous timestamp."),f.children.push({type:"timestamp",value:h,parent:f}),c.push(h))}}for(;f.parent;)"v"!=f.name&&r("Required end tag missing."),f=f.parent;return function e(t){const n=o({},t);return t.children&&(n.children=t.children.map(e)),n.parent&&delete n.parent,n}(a)}},p=function(){function e(e){const t=("00"+1e3*(e-Math.floor(e)).toFixed(3)).slice(-3);let n=0,i=0,a=0;return e>=3600&&(n=Math.floor(e/3600)),i=Math.floor((e-3600*n)/60),a=Math.floor(e-3600*n-60*i),(n?n+":":"")+(""+i).padStart(2,"0")+":"+(""+a).padStart(2,"0")+"."+t}function t(n){for(var i="",a=0;a/g,">");else if("object"==s.type){if(i+="<"+s.name,s.classes)for(var r=0;r"}else"timestamp"==s.type?i+="<"+e(s.value)+">":i+="<"+s.value+">"}return i}function n(n){return(void 0!==n.id?n.id+"\n":"")+e(n.startTime)+" --\x3e "+e(n.endTime)+function(e){var t="";const n=Object.keys(f).filter(t=>e[t]!==f[t]);return n.includes("direction")&&(t+=" vertical:"+e.direction),n.includes("alignment")&&(t+=" align:"+e.alignment),n.includes("size")&&(t+=" size:"+e.size+"%"),(n.includes("lineAlign")||n.includes("linePosition"))&&(t+=" line:"+e.linePosition+(e.snapToLines?"":"%")+(e.lineAlign&&e.lineAlign!=f.lineAlign?","+e.lineAlign:"")),(n.includes("textPosition")||n.includes("positionAlign"))&&(t+=" position:"+e.textPosition+"%"+(e.positionAlign&&e.positionAlign!==f.positionAlign?","+e.positionAlign:"")),t}(n)+"\n"+t(n.tree.children)+"\n\n"}function i(e){return"STYLE\n"+e+"\n\n"}this.serialize=function(e,t){var a="WEBVTT\n\n";if(t)for(var s=0;sl(null,null,function*(){const{unescape:a,getExt:s,srtToVtt:r,assToVtt:f}=i.constructor.utils,u=new c,d=new p,m=yield Promise.all(e.map(e=>function(e,t){return l(this,arguments,function*(e,{getExt:t,srtToVtt:n,assToVtt:i}){const a=yield fetch(e.url),s=yield a.arrayBuffer(),r=new TextDecoder(e.encoding||"utf-8").decode(s);switch(e.type||t(e.url)){case"srt":return n(r);case"ass":return i(r);case"vtt":return r;default:return""}})}(e,{getExt:s,srtToVtt:r,assToVtt:f}))),g=m.map((t,n)=>{const i=u.parse(t,"metadata");return i.url=e[n].url,i.name=e[n].name,i});let h="";function v(e=[]){const s=function(e){const t=(new c).parse("","metadata");for(let n=0;n${n.value}`}}}t.cues.push(...i.cues)}return t}(e),r=d.serialize(s.cues);URL.revokeObjectURL(h);const l=URL.createObjectURL(new Blob([r],{type:"text/vtt"}));var f;h=l,i.option.subtitle.escape=!1,i.subtitle.init((f=o({},i.option.subtitle),t(f,n({url:l,type:"vtt",onVttLoad:a}))))}return v(g),{name:"multipleSubtitles",tracks:(e=[])=>v(e.map(e=>g.find(t=>t.name===e))),reset:()=>v(g)}})}}); +!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerPluginMultipleSubtitles=t(),define(function(){return e.artplayerPluginMultipleSubtitles})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerPluginMultipleSubtitles=t()}(this,function(){"use strict";var e=Object.defineProperty,t=Object.defineProperties,n=Object.getOwnPropertyDescriptors,i=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,r=(t,n,i)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[n]=i,o=(e,t)=>{for(var n in t||(t={}))a.call(t,n)&&r(e,n,t[n]);if(i)for(var n of i(t))s.call(t,n)&&r(e,n,t[n]);return e},l=(e,t,n)=>new Promise((i,a)=>{var s=e=>{try{o(n.next(e))}catch(t){a(t)}},r=e=>{try{o(n.throw(e))}catch(t){a(t)}},o=e=>e.done?i(e.value):Promise.resolve(e.value).then(s,r);o((n=n.apply(e,t)).next())}),f={direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center"},c=function(e){e||(e={"&":"&","<":"<",">":">","&lrm":"\u200e","&rlm":"\u200f"," ":"\xa0"}),this.entities=e,this.parse=function(t,n){t=t.replace(/\0/g,"\ufffd");var i=Date.now(),a=0,s=t.split(/\r\n|\r|\n/),r=!1,o=[],l=[],c=[];function p(e,t){c.push({message:e,line:a+1,col:t})}var m=s[a],g=m.length,h="WEBVTT",v=0,b=6;for("\ufeff"===m[0]&&(v=1,b+=1),(gb&&" "!==m[b]&&"\t"!==m[b])&&p('No valid signature. (File needs to start with "WEBVTT".)'),a++;""!=s[a]&&void 0!=s[a];){if(p("No blank line after the signature."),-1!=s[a].indexOf("--\x3e")){r=!0;break}a++}for(;void 0!=s[a];){for(var x;!r&&""==s[a];)a++;if(!r&&void 0==s[a])break;x=Object.assign({},f,{id:"",startTime:0,endTime:0,pauseOnExit:!1,direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center",text:"",tree:null});var T=!0;if(-1==s[a].indexOf("--\x3e")){if(x.id=s[a],/^NOTE($|[ \t])/.test(x.id)){for(a++;""!=s[a]&&void 0!=s[a];)-1!=s[a].indexOf("--\x3e")&&p("Cannot have timestamp in a comment."),a++;continue}if(/^STYLE($|[ \t])/.test(x.id)){var y=[],w=!1;for(a++;""!=s[a]&&void 0!=s[a];)-1!=s[a].indexOf("--\x3e")&&(p("Cannot have timestamp in a style block."),w=!0),y.push(s[a]),a++;if(l.length){p("Style blocks cannot appear after the first cue.");continue}w||o.push(y.join("\n"));continue}if(""==s[++a]||void 0==s[a]){p("Cue identifier cannot be standalone.");continue}if(-1==s[a].indexOf("--\x3e")){T=!1,p("Cue identifier needs to be followed by timestamp.");continue}}r=!1;var O=new u(s[a],p),P=0;if(l.length>0&&(P=l[l.length-1].startTime),!T||O.parse(x,P)){for(a++;""!=s[a]&&void 0!=s[a];){if(-1!=s[a].indexOf("--\x3e")){p("Blank line missing before cue."),r=!0;break}""!=x.text&&(x.text+="\n"),x.text+=s[a],a++}var I=new d(x.text,p,n,e);x.tree=I.parse(x.startTime,x.endTime),l.push(x)}else for(x=null,a++;""!=s[a]&&void 0!=s[a];){if(-1!=s[a].indexOf("--\x3e")){r=!0;break}a++}}return l.sort(function(e,t){return e.startTimet.startTime?1:e.endTime>t.endTime?-1:e.endTime2||parseInt(t,10)>59)&&(l="hours"),":"==e[a])if(a++,2==(n=o(/\d/)).length){if("hours"==l||":"==e[a]){if(":"!=e[a])return void s("No seconds found or minutes is greater than 59.");if(a++,2!=(i=o(/\d/)).length)return void s("Must be exactly two digits.")}else{if(2!=t.length)return void s("Must be exactly two digits.");i=n,n=t,t="0"}if("."==e[a])if(a++,3==(r=o(/\d/)).length)if(parseInt(n,10)>59)s("You cannot have more than 59 minutes.");else{if(!(parseInt(i,10)>59))return 60*parseInt(t,10)*60+60*parseInt(n,10)+parseInt(i,10)+parseInt(r,10)/1e3;s("You cannot have more than 59 seconds.")}else s("Milliseconds must be given in three digits.");else s('No decimal separator (".") found.')}else s("Must be exactly two digits.");else s("No time unit separator found.");else s("Timestamp must start with a character in the range 0-9.");else s("No timestamp found.")}this.parse=function(t,o){if(r(n),t.startTime=l(),void 0!=t.startTime)if(t.startTime"==e[a]){if(a++,i.test(e[a])&&s("'--\x3e' not separated from timestamp by whitespace."),r(n),t.endTime=l(),void 0!=t.endTime)return t.endTime<=t.startTime&&s("End timestamp is not greater than start timestamp."),i.test(e[a]),r(n),function(e,t){for(var i=e.split(n),a=[],r=0;r100)){s("Line position cannot be >100%.");continue}if(""===d||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==u){if(!["start","center","end"].includes(u)){s("Line alignment needs to be one of start, center or end");continue}t.lineAlign=u}t.snapToLines=!p,t.linePosition=parseFloat(d),parseFloat(d).toString()!==d&&(t.nonSerializable=!0)}else if("position"==l){if(/,/.test(f)){c=f.split(","),f=c[0];var m=c[1]}if("%"!=f[f.length-1]){s("Text position must be a percentage.");continue}if(parseInt(f,10)>100||parseInt(f,10)<0){s("Text position needs to be between 0 and 100%.");continue}if(""===(d=f.slice(0,f.length-1))||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==m){if(!["line-left","center","line-right"].includes(m)){s("Position alignment needs to be one of line-left, center or line-right");continue}t.positionAlign=m}t.textPosition=parseFloat(d)}else if("size"==l){if("%"!=f[f.length-1]){s("Size must be a percentage.");continue}if(parseInt(f,10)>100){s("Size cannot be >100%.");continue}var g=f.slice(0,f.length-1);if(void 0===g||""===g||isNaN(g)){s("Size needs to be a number"),g=100;continue}if((g=parseFloat(g))<0||g>100){s("Size needs to be between 0 and 100%.");continue}t.size=g}else if("align"==l){var h=["start","center","end","left","right"];if(-1==h.indexOf(f)){s("Alignment can only be set to one of "+h.join(", ")+".");continue}t.alignment=f}else s("Invalid setting.")}}(e.substring(a),t),!0}else s("No valid timestamp separator found.");else s("No valid timestamp separator found.");else s("No valid timestamp separator found.")},this.parseTimestamp=function(){var t=l();if(void 0==e[a])return t;s("Timestamp must not have trailing characters.")}},d=function(e,t,n,i){this.entities=i;var a=this,s=(e=e,0),r=function(e){"metadata"!=n&&t(e,s+1)};function l(){for(var t="data",n="",o="",l=[];void 0!=e[s-1]||0==s;){var f=e[s];if("data"==t)if("&"==f)o=f,t="escape";else if("<"==f&&""==n)t="tag";else{if("<"==f||void 0==f)return["text",n];n+=f}else if("escape"==t){if("<"==f||void 0==f){let e;return r("Incorrect escape."),(e=o.match(/^&#([0-9]+)$/))?n+=String.fromCharCode(e[1]):a.entities[o]?n+=a.entities[o]:n+=o,["text",n]}if("&"==f)r("Incorrect escape."),n+=o,o=f;else if(/[a-z#0-9]/i.test(f))o+=f;else if(";"==f){let e;(e=o.match(/^&#(x?[0-9]+)$/))?n+=String.fromCharCode("0"+e[1]):a.entities[o+f]?n+=a.entities[o+f]:(e=Object.keys(i).find(e=>o.startsWith(e)))?n+=a.entities[e]+o.slice(e.length)+f:(r("Incorrect escape."),n+=o+";"),t="data"}else r("Incorrect escape."),n+=o+f,t="data"}else if("tag"==t)if("\t"==f||"\n"==f||"\f"==f||" "==f)t="start tag annotation";else if("."==f)t="start tag class";else if("/"==f)t="end tag";else if(/\d/.test(f))n=f,t="timestamp tag";else{if(">"==f||void 0==f)return">"==f&&s++,["start tag","",[],""];n=f,t="start tag"}else if("start tag"==t)if("\t"==f||"\f"==f||" "==f)t="start tag annotation";else if("\n"==f)o=f,t="start tag annotation";else if("."==f)t="start tag class";else{if(">"==f||void 0==f)return">"==f&&s++,["start tag",n,[],""];n+=f}else if("start tag class"==t)if("\t"==f||"\f"==f||" "==f)o&&l.push(o),o="",t="start tag annotation";else if("\n"==f)o&&l.push(o),o=f,t="start tag annotation";else if("."==f)o&&l.push(o),o="";else{if(">"==f||void 0==f)return">"==f&&s++,o&&l.push(o),["start tag",n,l,""];o+=f}else if("start tag annotation"==t){if(">"==f||void 0==f)return">"==f&&s++,["start tag",n,l,o=o.split(/[\u0020\t\f\r\n]+/).filter(function(e){if(e)return!0}).join(" ")];o+=f}else if("end tag"==t){if(">"==f||void 0==f)return">"==f&&s++,["end tag",n];n+=f}else if("timestamp tag"==t){if(">"==f||void 0==f)return">"==f&&s++,["timestamp",n];n+=f}else r("Never happens.");s++}}this.parse=function(t,i){var a={children:[]},f=a,c=[];function d(e){f.children.push({type:"object",name:e[1],classes:e[2],children:[],parent:f}),f=f.children[f.children.length-1]}function p(e){for(var t=f;t;){if(t.name==e)return!0;t=t.parent}}for(;void 0!=e[s];){var m=l();if("text"==m[0])f.children.push({type:"text",value:m[1],parent:f});else if("start tag"==m[0]){"chapters"==n&&r("Start tags not allowed in chapter title text.");var g=m[1];"v"!=g&&"lang"!=g&&""!=m[3]&&r("Only and can have an annotation."),"c"==g||"i"==g||"b"==g||"u"==g||"ruby"==g||"rt"==g&&"ruby"==f.name?d(m):"v"==g?(p("v")&&r(" cannot be nested inside itself."),d(m),f.value=m[3],m[3]||r(" requires an annotation.")):"lang"==g?(d(m),f.value=m[3]):r("Incorrect start tag.")}else if("end tag"==m[0])"chapters"==n&&r("End tags not allowed in chapter title text."),m[1]==f.name?f=f.parent:"ruby"==m[1]&&"rt"==f.name?f=f.parent.parent:r("Incorrect end tag.");else if("timestamp"==m[0]){"chapters"==n&&r("Timestamp not allowed in chapter title text.");var h=new u(m[1],r).parseTimestamp();void 0!=h&&((h<=t||h>=i)&&r("Timestamp must be between start timestamp and end timestamp."),c.length>0&&c[c.length-1]>=h&&r("Timestamp must be greater than any previous timestamp."),f.children.push({type:"timestamp",value:h,parent:f}),c.push(h))}}for(;f.parent;)"v"!=f.name&&r("Required end tag missing."),f=f.parent;return function e(t){const n=o({},t);return t.children&&(n.children=t.children.map(e)),n.parent&&delete n.parent,n}(a)}},p=function(){function e(e){const t=("00"+1e3*(e-Math.floor(e)).toFixed(3)).slice(-3);let n=0,i=0,a=0;return e>=3600&&(n=Math.floor(e/3600)),i=Math.floor((e-3600*n)/60),a=Math.floor(e-3600*n-60*i),(n?n+":":"")+(""+i).padStart(2,"0")+":"+(""+a).padStart(2,"0")+"."+t}function t(n){for(var i="",a=0;a/g,">");else if("object"==s.type){if(i+="<"+s.name,s.classes)for(var r=0;r"}else"timestamp"==s.type?i+="<"+e(s.value)+">":i+="<"+s.value+">"}return i}function n(n){return(void 0!==n.id?n.id+"\n":"")+e(n.startTime)+" --\x3e "+e(n.endTime)+function(e){var t="";const n=Object.keys(f).filter(t=>e[t]!==f[t]);return n.includes("direction")&&(t+=" vertical:"+e.direction),n.includes("alignment")&&(t+=" align:"+e.alignment),n.includes("size")&&(t+=" size:"+e.size+"%"),(n.includes("lineAlign")||n.includes("linePosition"))&&(t+=" line:"+e.linePosition+(e.snapToLines?"":"%")+(e.lineAlign&&e.lineAlign!=f.lineAlign?","+e.lineAlign:"")),(n.includes("textPosition")||n.includes("positionAlign"))&&(t+=" position:"+e.textPosition+"%"+(e.positionAlign&&e.positionAlign!==f.positionAlign?","+e.positionAlign:"")),t}(n)+"\n"+t(n.tree.children)+"\n\n"}function i(e){return"STYLE\n"+e+"\n\n"}this.serialize=function(e,t){var a="WEBVTT\n\n";if(t)for(var s=0;sl(null,null,function*(){const{unescape:a,getExt:s,srtToVtt:r,assToVtt:f}=i.constructor.utils,u=new c,d=new p,m=yield Promise.all(e.map(e=>function(e,t){return l(this,arguments,function*(e,{getExt:t,srtToVtt:n,assToVtt:i}){const a=yield fetch(e.url),s=yield a.arrayBuffer(),r=new TextDecoder(e.encoding||"utf-8").decode(s);switch(e.type||t(e.url)){case"srt":return n(r);case"ass":return i(r);case"vtt":return r;default:return""}})}(e,{getExt:s,srtToVtt:r,assToVtt:f}))),g=m.map((t,n)=>{const i=u.parse(t,"metadata");return i.url=e[n].url,i.name=e[n].name,i});let h="";function v(e=[]){const s=function(e){const t=(new c).parse("","metadata");for(let n=0;n${n.value}`}}}t.cues.push(...i.cues)}return t}(e),r=d.serialize(s.cues);URL.revokeObjectURL(h);const l=URL.createObjectURL(new Blob([r],{type:"text/vtt"}));var f;h=l,i.option.subtitle.escape=!1,i.subtitle.init((f=o({},i.option.subtitle),t(f,n({url:l,type:"vtt",onVttLoad:a}))))}return v(g),{name:"multipleSubtitles",tracks:(e=[])=>v(e.map(e=>g.find(t=>t.name===e))),reset:()=>v(g)}})}}); diff --git a/docs/compiled/artplayer-plugin-multiple-subtitles.mjs b/docs/compiled/artplayer-plugin-multiple-subtitles.mjs index 8a9d230f3..4befa73d6 100644 --- a/docs/compiled/artplayer-plugin-multiple-subtitles.mjs +++ b/docs/compiled/artplayer-plugin-multiple-subtitles.mjs @@ -3,6 +3,57 @@ * Github: https://github.com/zhw2590582/ArtPlayer * (c) 2017-2026 Harvey Zhao * Released under the MIT License. + * + * This package includes WebVTT parser and serializer code from w3c/webvtt.js. + * Reference revision: 380cfcce34ba8b472d3a31474874eb72a0e5f460 + * https://github.com/w3c/webvtt.js/tree/380cfcce34ba8b472d3a31474874eb72a0e5f460 + * The parser has a CC0 public-domain dedication. Local adaptations replace + * the IIFE/global exports with named ESM exports and format the code. + * The ArtPlayer plugin wrapper remains MIT licensed. + * + * ## creative commons + * + * # CC0 1.0 Universal + * + * CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + * + * ### Statement of Purpose + * + * The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + * + * Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + * + * For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + * + * 1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + * + * i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; + * + * ii. moral rights retained by the original author(s) and/or performer(s); + * + * iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; + * + * iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; + * + * v. rights protecting the extraction, dissemination, use and reuse of data in a Work; + * + * vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and + * + * vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + * + * 2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + * + * 3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + * + * 4. __Limitations and Disclaimers.__ + * + * a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. + * + * b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. + * + * c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. + * + * d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. */ var defaultCueSettings = { direction: "horizontal", diff --git a/package.json b/package.json index ed5ae9f46..b634d5eab 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "ci:build": "yarn build:types && yarn build all && yarn build:i18n && yarn build:ts && yarn build:docs && yarn test:imports", "test:imports": "node --test test/esm.test.js test/i18n.test.js test/ssr.test.js", "typecheck": "node scripts/typecheck.mjs", - "test:unit": "node --test test/vtt-thumbnail-parser.test.js test/vtt-thumbnail-lifecycle.test.js test/vtt-thumbnail.test.js test/auto-thumbnail-frames.test.js test/auto-thumbnail-lifecycle.test.js test/auto-thumbnail.test.js test/thumbnail-emitter.test.js test/thumbnail-runtime.test.js test/thumbnail-vendor.test.js test/thumbnail-lifecycle.test.js test/thumbnail-input.test.js test/thumbnail.test.js test/iframe-navigation.test.js test/iframe-boundaries.test.js test/iframe-lifecycle.test.js test/iframe.test.js test/mediabunny.test.js test/mediabunny-shim.test.js test/mediabunny-coordination.test.js test/mediabunny-video.test.js test/mediabunny-audio.test.js test/mediabunny-hls.test.js test/mediabunny-entry.test.js test/mediabunny-capability.test.js test/mediabunny-load.test.js test/mediabunny-input.test.js test/dpip.test.js test/dpip-lifecycle.test.js test/canvas.test.js test/canvas-lifecycle.test.js test/ambilight.test.js test/ambilight-lifecycle.test.js test/ambilight-proxy.test.js test/vast.test.js test/vast-lifecycle.test.js test/ads.test.js test/ads-lifecycle.test.js test/playback.test.js test/dash-control.test.js test/dash-contract.test.js test/dash-lifecycle.test.js test/dash-events.test.js test/hls-control.test.js test/audio-track.test.js test/public-behavior.test.js test/helpers.test.js test/chapter.test.js test/utils.test.js test/resource-scope.test.js test/instance-lifecycle.test.js test/options.test.js test/media-hosts.test.js test/plugins.test.js test/source.test.js test/playback-properties.test.js test/media-events.test.js test/template-resources.test.js test/core-vendor.test.js test/component-resources.test.js test/setting-model.test.js test/setting-layout.test.js test/setting-resources.test.js test/subtitle.test.js test/display-native.test.js test/display-video-fullscreen.test.js test/display-pip.test.js test/display-mini.test.js test/display-sizing.test.js test/display-orientation.test.js test/hotkey.test.js test/listener-registry.test.js test/global-events.test.js test/pointer-events.test.js test/gesture.test.js test/event-scheduling.test.js test/notice.test.js test/fast-forward.test.js test/auto-playback.test.js test/builtin-layers.test.js test/prompt-components.test.js test/screenshot.test.js test/thumbnails.test.js test/progress.test.js test/environment.test.js test/storage.test.js test/facade-properties.test.js test/dom-boundaries.test.js test/initialization.test.js test/entry.test.js test/accessibility-button.test.js test/accessibility-focus.test.js test/accessibility-slider.test.js", + "test:unit": "node --test test/multiple-subtitles.test.js test/multiple-subtitles-vendor.test.js test/vtt-thumbnail-parser.test.js test/vtt-thumbnail-lifecycle.test.js test/vtt-thumbnail.test.js test/auto-thumbnail-frames.test.js test/auto-thumbnail-lifecycle.test.js test/auto-thumbnail.test.js test/thumbnail-emitter.test.js test/thumbnail-runtime.test.js test/thumbnail-vendor.test.js test/thumbnail-lifecycle.test.js test/thumbnail-input.test.js test/thumbnail.test.js test/iframe-navigation.test.js test/iframe-boundaries.test.js test/iframe-lifecycle.test.js test/iframe.test.js test/mediabunny.test.js test/mediabunny-shim.test.js test/mediabunny-coordination.test.js test/mediabunny-video.test.js test/mediabunny-audio.test.js test/mediabunny-hls.test.js test/mediabunny-entry.test.js test/mediabunny-capability.test.js test/mediabunny-load.test.js test/mediabunny-input.test.js test/dpip.test.js test/dpip-lifecycle.test.js test/canvas.test.js test/canvas-lifecycle.test.js test/ambilight.test.js test/ambilight-lifecycle.test.js test/ambilight-proxy.test.js test/vast.test.js test/vast-lifecycle.test.js test/ads.test.js test/ads-lifecycle.test.js test/playback.test.js test/dash-control.test.js test/dash-contract.test.js test/dash-lifecycle.test.js test/dash-events.test.js test/hls-control.test.js test/audio-track.test.js test/public-behavior.test.js test/helpers.test.js test/chapter.test.js test/utils.test.js test/resource-scope.test.js test/instance-lifecycle.test.js test/options.test.js test/media-hosts.test.js test/plugins.test.js test/source.test.js test/playback-properties.test.js test/media-events.test.js test/template-resources.test.js test/core-vendor.test.js test/component-resources.test.js test/setting-model.test.js test/setting-layout.test.js test/setting-resources.test.js test/subtitle.test.js test/display-native.test.js test/display-video-fullscreen.test.js test/display-pip.test.js test/display-mini.test.js test/display-sizing.test.js test/display-orientation.test.js test/hotkey.test.js test/listener-registry.test.js test/global-events.test.js test/pointer-events.test.js test/gesture.test.js test/event-scheduling.test.js test/notice.test.js test/fast-forward.test.js test/auto-playback.test.js test/builtin-layers.test.js test/prompt-components.test.js test/screenshot.test.js test/thumbnails.test.js test/progress.test.js test/environment.test.js test/storage.test.js test/facade-properties.test.js test/dom-boundaries.test.js test/initialization.test.js test/entry.test.js test/accessibility-button.test.js test/accessibility-focus.test.js test/accessibility-slider.test.js", "test:coverage": "node --test test/coverage.test.js && node scripts/coverage.mjs", "test": "yarn test:node && yarn test:baseline", "test:browser": "playwright test", @@ -87,7 +87,8 @@ "test:thumbnail-types-package": "node refactor/scripts/thumbnail-package-types.mjs", "test:auto-thumbnail": "node --test test/auto-thumbnail-frames.test.js test/auto-thumbnail-lifecycle.test.js test/auto-thumbnail.test.js refactor/scripts/auto-thumbnail-contract.test.mjs", "test:vtt-thumbnail": "node --test test/vtt-thumbnail-parser.test.js test/vtt-thumbnail-lifecycle.test.js test/vtt-thumbnail.test.js refactor/scripts/vtt-thumbnail-contract.test.mjs refactor/scripts/vtt-thumbnail-types.test.mjs", - "test:vtt-thumbnail-types-package": "node refactor/scripts/vtt-thumbnail-package-types.mjs" + "test:vtt-thumbnail-types-package": "node refactor/scripts/vtt-thumbnail-package-types.mjs", + "test:multiple-subtitles": "node --test test/multiple-subtitles.test.js test/multiple-subtitles-vendor.test.js refactor/scripts/multiple-subtitles-contract.test.mjs" }, "browserslist": "last 1 Chrome version", "devDependencies": { diff --git a/packages/artplayer-plugin-multiple-subtitles/ARCHITECTURE.md b/packages/artplayer-plugin-multiple-subtitles/ARCHITECTURE.md new file mode 100644 index 000000000..48d72e881 --- /dev/null +++ b/packages/artplayer-plugin-multiple-subtitles/ARCHITECTURE.md @@ -0,0 +1,55 @@ +# Multiple subtitles maintenance + +The public factory is `artplayerPluginMultipleSubtitles({ subtitles })`. Registration is +asynchronous and resolves to `{ name: 'multipleSubtitles', tracks, reset }`. `tracks(names)` +selects names in caller order, `tracks()` clears, and `reset()` restores the original order. +Both methods return undefined. Current declarations incorrectly omit the Promise and methods; +task PKG-MULTI-SUB-04 owns that compatibility work. Do not infer runtime behavior from them. + +## Current module boundaries + +- `src/index.js` currently combines download/decode, conversion, parsing, merging, Blob URL + replacement and public registration. Task 03 will separate pure merge, requests and owned + resources while preserving the factory and CSS hooks. +- `src/parser.js` is vendored WebVTT parser/serializer code with a CC0 dedication. It is not + owned plugin code to mechanically migrate to TypeScript. Keep it distinct from task 04. + The pinned upstream reference and full adaptation check are in + `../../refactor/baselines/multiple-subtitles-vendor/` and + `../../refactor/scripts/multiple-subtitles-vendor.mjs`. +- `types/artplayer-plugin-multiple-subtitles.d.ts` is the historical public declaration. +- `../../docs/assets/example/multiple.subtitles.js` demonstrates the real plugin name, + `tracks/reset`, name order and `.art-subtitle-chinese/.art-subtitle-japanese` CSS hooks. + +All tracks download concurrently and decode through TextDecoder. Explicit type wins over +the URL extension; SRT/ASS conversion delegates to existing core utils. `onParser` appears +in declarations but is not called. Parsing runs in metadata mode. Each track's top-level +cue text receives a name-based div once; current merging concatenates cue arrays by track +order, whereas 1.0.0 merged by cue index and retained the first track's timestamps. + +Each selection serializes a new VTT, revokes the preceding URL, creates a text/vtt Blob, +sets the live subtitle option's escape to false and calls subtitle.init with the live +configuration plus URL/type/onVttLoad overrides. The latest URL and pending requests have +no destroy owner yet. These are explicit future fixes, not behavior to silently call safe. + +## Vendor boundary and validation + +The comparison revision is w3c/webvtt.js `380cfcce34ba8b472d3a31474874eb72a0e5f460`. +This is not proof of the original acquisition commit. Its execution body matches local +code after replacing the IIFE/global exports with named ESM exports and normalizing format. +Older shipped sources keep the IIFE. Preserve the CC0 source header and complete +THIRD_PARTY_NOTICES; the normal build places notices in all standalone bundle headers. + +Use the pinned Node and Yarn 1.22.22: + +```sh +yarn test:multiple-subtitles +yarn build artplayer-plugin-multiple-subtitles +``` + +Historical tests read verified npm bytes and frozen Git inputs. For current normal behavior, +set ARTPLAYER_MULTIPLE_SUBTITLES_CANDIDATE=1; optionally set +ARTPLAYER_MULTIPLE_SUBTITLES_ARTIFACT to an actual main/legacy file, then run +`node --test test/multiple-subtitles.test.js`. These tests use controlled subtitle hosts; +they do not prove native rendering, decoder coverage or the online editor. Tasks 02 and +05/06 own error/lifecycle reproduction, real core/device combinations and demo acceptance. +See `../../refactor/baselines/multiple-subtitles-contract.md` for exact historical differences. diff --git a/packages/artplayer-plugin-multiple-subtitles/THIRD_PARTY_NOTICES b/packages/artplayer-plugin-multiple-subtitles/THIRD_PARTY_NOTICES new file mode 100644 index 000000000..2321b1adf --- /dev/null +++ b/packages/artplayer-plugin-multiple-subtitles/THIRD_PARTY_NOTICES @@ -0,0 +1,50 @@ +This package includes WebVTT parser and serializer code from w3c/webvtt.js. +Reference revision: 380cfcce34ba8b472d3a31474874eb72a0e5f460 +https://github.com/w3c/webvtt.js/tree/380cfcce34ba8b472d3a31474874eb72a0e5f460 +The parser has a CC0 public-domain dedication. Local adaptations replace +the IIFE/global exports with named ESM exports and format the code. +The ArtPlayer plugin wrapper remains MIT licensed. + +## creative commons + +# CC0 1.0 Universal + +CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + +### Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + +1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + +2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + +3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + +4. __Limitations and Disclaimers.__ + + a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. diff --git a/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.js b/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.js index 749450150..5c7e6eafb 100644 --- a/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.js +++ b/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.js @@ -3,5 +3,56 @@ * Github: https://github.com/zhw2590582/ArtPlayer * (c) 2017-2026 Harvey Zhao * Released under the MIT License. + * + * This package includes WebVTT parser and serializer code from w3c/webvtt.js. + * Reference revision: 380cfcce34ba8b472d3a31474874eb72a0e5f460 + * https://github.com/w3c/webvtt.js/tree/380cfcce34ba8b472d3a31474874eb72a0e5f460 + * The parser has a CC0 public-domain dedication. Local adaptations replace + * the IIFE/global exports with named ESM exports and format the code. + * The ArtPlayer plugin wrapper remains MIT licensed. + * + * ## creative commons + * + * # CC0 1.0 Universal + * + * CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + * + * ### Statement of Purpose + * + * The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + * + * Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + * + * For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + * + * 1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + * + * i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; + * + * ii. moral rights retained by the original author(s) and/or performer(s); + * + * iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; + * + * iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; + * + * v. rights protecting the extraction, dissemination, use and reuse of data in a Work; + * + * vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and + * + * vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + * + * 2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + * + * 3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + * + * 4. __Limitations and Disclaimers.__ + * + * a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. + * + * b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. + * + * c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. + * + * d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. */ -!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(t.artplayerPluginMultipleSubtitles=t(),define(function(){return t.artplayerPluginMultipleSubtitles})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerPluginMultipleSubtitles=t()}(this,function(){"use strict";var e={direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center"},t=function(t){t||(t={"&":"&","<":"<",">":">","&lrm":"\u200e","&rlm":"\u200f"," ":"\xa0"}),this.entities=t,this.parse=function(a,s){a=a.replace(/\0/g,"\ufffd");var r=Date.now(),o=0,l=a.split(/\r\n|\r|\n/),f=!1,c=[],u=[],d=[];function p(e,t){d.push({message:e,line:o+1,col:t})}var m=l[o],g=m.length,h="WEBVTT",v=0,b=6;for("\ufeff"===m[0]&&(v=1,b+=1),(gb&&" "!==m[b]&&"\t"!==m[b])&&p('No valid signature. (File needs to start with "WEBVTT".)'),o++;""!=l[o]&&void 0!=l[o];){if(p("No blank line after the signature."),-1!=l[o].indexOf("--\x3e")){f=!0;break}o++}for(;void 0!=l[o];){for(var x;!f&&""==l[o];)o++;if(!f&&void 0==l[o])break;x=Object.assign({},e,{id:"",startTime:0,endTime:0,pauseOnExit:!1,direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center",text:"",tree:null});var T=!0;if(-1==l[o].indexOf("--\x3e")){if(x.id=l[o],/^NOTE($|[ \t])/.test(x.id)){for(o++;""!=l[o]&&void 0!=l[o];)-1!=l[o].indexOf("--\x3e")&&p("Cannot have timestamp in a comment."),o++;continue}if(/^STYLE($|[ \t])/.test(x.id)){var y=[],w=!1;for(o++;""!=l[o]&&void 0!=l[o];)-1!=l[o].indexOf("--\x3e")&&(p("Cannot have timestamp in a style block."),w=!0),y.push(l[o]),o++;if(u.length){p("Style blocks cannot appear after the first cue.");continue}w||c.push(y.join("\n"));continue}if(""==l[++o]||void 0==l[o]){p("Cue identifier cannot be standalone.");continue}if(-1==l[o].indexOf("--\x3e")){T=!1,p("Cue identifier needs to be followed by timestamp.");continue}}f=!1;var O=new n(l[o],p),L=0;if(u.length>0&&(L=u[u.length-1].startTime),!T||O.parse(x,L)){for(o++;""!=l[o]&&void 0!=l[o];){if(-1!=l[o].indexOf("--\x3e")){p("Blank line missing before cue."),f=!0;break}""!=x.text&&(x.text+="\n"),x.text+=l[o],o++}var I=new i(x.text,p,s,t);x.tree=I.parse(x.startTime,x.endTime),u.push(x)}else for(x=null,o++;""!=l[o]&&void 0!=l[o];){if(-1!=l[o].indexOf("--\x3e")){f=!0;break}o++}}return u.sort(function(e,t){return e.startTimet.startTime?1:e.endTime>t.endTime?-1:e.endTime2||parseInt(t,10)>59)&&(l="hours"),":"==e[a])if(a++,2==(n=o(/\d/)).length){if("hours"==l||":"==e[a]){if(":"!=e[a])return void s("No seconds found or minutes is greater than 59.");if(a++,2!=(i=o(/\d/)).length)return void s("Must be exactly two digits.")}else{if(2!=t.length)return void s("Must be exactly two digits.");i=n,n=t,t="0"}if("."==e[a])if(a++,3==(r=o(/\d/)).length)if(parseInt(n,10)>59)s("You cannot have more than 59 minutes.");else{if(!(parseInt(i,10)>59))return 60*parseInt(t,10)*60+60*parseInt(n,10)+parseInt(i,10)+parseInt(r,10)/1e3;s("You cannot have more than 59 seconds.")}else s("Milliseconds must be given in three digits.");else s('No decimal separator (".") found.')}else s("Must be exactly two digits.");else s("No time unit separator found.");else s("Timestamp must start with a character in the range 0-9.");else s("No timestamp found.")}this.parse=function(t,o){if(r(n),t.startTime=l(),void 0!=t.startTime)if(t.startTime"==e[a]){if(a++,i.test(e[a])&&s("'--\x3e' not separated from timestamp by whitespace."),r(n),t.endTime=l(),void 0!=t.endTime)return t.endTime<=t.startTime&&s("End timestamp is not greater than start timestamp."),i.test(e[a]),r(n),function(e,t){for(var i=e.split(n),a=[],r=0;r100)){s("Line position cannot be >100%.");continue}if(""===d||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==u){if(!["start","center","end"].includes(u)){s("Line alignment needs to be one of start, center or end");continue}t.lineAlign=u}t.snapToLines=!p,t.linePosition=parseFloat(d),parseFloat(d).toString()!==d&&(t.nonSerializable=!0)}else if("position"==l){if(/,/.test(f)){c=f.split(","),f=c[0];var m=c[1]}if("%"!=f[f.length-1]){s("Text position must be a percentage.");continue}if(parseInt(f,10)>100||parseInt(f,10)<0){s("Text position needs to be between 0 and 100%.");continue}if(""===(d=f.slice(0,f.length-1))||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==m){if(!["line-left","center","line-right"].includes(m)){s("Position alignment needs to be one of line-left, center or line-right");continue}t.positionAlign=m}t.textPosition=parseFloat(d)}else if("size"==l){if("%"!=f[f.length-1]){s("Size must be a percentage.");continue}if(parseInt(f,10)>100){s("Size cannot be >100%.");continue}var g=f.slice(0,f.length-1);if(void 0===g||""===g||isNaN(g)){s("Size needs to be a number"),g=100;continue}if((g=parseFloat(g))<0||g>100){s("Size needs to be between 0 and 100%.");continue}t.size=g}else if("align"==l){var h=["start","center","end","left","right"];if(-1==h.indexOf(f)){s("Alignment can only be set to one of "+h.join(", ")+".");continue}t.alignment=f}else s("Invalid setting.")}}(e.substring(a),t),!0}else s("No valid timestamp separator found.");else s("No valid timestamp separator found.");else s("No valid timestamp separator found.")},this.parseTimestamp=function(){var t=l();if(void 0==e[a])return t;s("Timestamp must not have trailing characters.")}},i=function(e,t,i,a){this.entities=a;var s=this,r=(e=e,0),o=function(e){"metadata"!=i&&t(e,r+1)};function l(){for(var t="data",n="",i="",l=[];void 0!=e[r-1]||0==r;){var f=e[r];if("data"==t)if("&"==f)i=f,t="escape";else if("<"==f&&""==n)t="tag";else{if("<"==f||void 0==f)return["text",n];n+=f}else if("escape"==t){if("<"==f||void 0==f){let e;return o("Incorrect escape."),(e=i.match(/^&#([0-9]+)$/))?n+=String.fromCharCode(e[1]):s.entities[i]?n+=s.entities[i]:n+=i,["text",n]}if("&"==f)o("Incorrect escape."),n+=i,i=f;else if(/[a-z#0-9]/i.test(f))i+=f;else if(";"==f){let e;(e=i.match(/^&#(x?[0-9]+)$/))?n+=String.fromCharCode("0"+e[1]):s.entities[i+f]?n+=s.entities[i+f]:(e=Object.keys(a).find(e=>i.startsWith(e)))?n+=s.entities[e]+i.slice(e.length)+f:(o("Incorrect escape."),n+=i+";"),t="data"}else o("Incorrect escape."),n+=i+f,t="data"}else if("tag"==t)if("\t"==f||"\n"==f||"\f"==f||" "==f)t="start tag annotation";else if("."==f)t="start tag class";else if("/"==f)t="end tag";else if(/\d/.test(f))n=f,t="timestamp tag";else{if(">"==f||void 0==f)return">"==f&&r++,["start tag","",[],""];n=f,t="start tag"}else if("start tag"==t)if("\t"==f||"\f"==f||" "==f)t="start tag annotation";else if("\n"==f)i=f,t="start tag annotation";else if("."==f)t="start tag class";else{if(">"==f||void 0==f)return">"==f&&r++,["start tag",n,[],""];n+=f}else if("start tag class"==t)if("\t"==f||"\f"==f||" "==f)i&&l.push(i),i="",t="start tag annotation";else if("\n"==f)i&&l.push(i),i=f,t="start tag annotation";else if("."==f)i&&l.push(i),i="";else{if(">"==f||void 0==f)return">"==f&&r++,i&&l.push(i),["start tag",n,l,""];i+=f}else if("start tag annotation"==t){if(">"==f||void 0==f)return">"==f&&r++,["start tag",n,l,i=i.split(/[\u0020\t\f\r\n]+/).filter(function(e){if(e)return!0}).join(" ")];i+=f}else if("end tag"==t){if(">"==f||void 0==f)return">"==f&&r++,["end tag",n];n+=f}else if("timestamp tag"==t){if(">"==f||void 0==f)return">"==f&&r++,["timestamp",n];n+=f}else o("Never happens.");r++}}this.parse=function(t,a){var s={children:[]},f=s,c=[];function u(e){f.children.push({type:"object",name:e[1],classes:e[2],children:[],parent:f}),f=f.children[f.children.length-1]}function d(e){for(var t=f;t;){if(t.name==e)return!0;t=t.parent}}for(;void 0!=e[r];){var p=l();if("text"==p[0])f.children.push({type:"text",value:p[1],parent:f});else if("start tag"==p[0]){"chapters"==i&&o("Start tags not allowed in chapter title text.");var m=p[1];"v"!=m&&"lang"!=m&&""!=p[3]&&o("Only and can have an annotation."),"c"==m||"i"==m||"b"==m||"u"==m||"ruby"==m||"rt"==m&&"ruby"==f.name?u(p):"v"==m?(d("v")&&o(" cannot be nested inside itself."),u(p),f.value=p[3],p[3]||o(" requires an annotation.")):"lang"==m?(u(p),f.value=p[3]):o("Incorrect start tag.")}else if("end tag"==p[0])"chapters"==i&&o("End tags not allowed in chapter title text."),p[1]==f.name?f=f.parent:"ruby"==p[1]&&"rt"==f.name?f=f.parent.parent:o("Incorrect end tag.");else if("timestamp"==p[0]){"chapters"==i&&o("Timestamp not allowed in chapter title text.");var g=new n(p[1],o).parseTimestamp();void 0!=g&&((g<=t||g>=a)&&o("Timestamp must be between start timestamp and end timestamp."),c.length>0&&c[c.length-1]>=g&&o("Timestamp must be greater than any previous timestamp."),f.children.push({type:"timestamp",value:g,parent:f}),c.push(g))}}for(;f.parent;)"v"!=f.name&&o("Required end tag missing."),f=f.parent;return function e(t){const n={...t};return t.children&&(n.children=t.children.map(e)),n.parent&&delete n.parent,n}(s)}},a=function(){function t(e){const t=("00"+1e3*(e-Math.floor(e)).toFixed(3)).slice(-3);let n=0,i=0,a=0;return e>=3600&&(n=Math.floor(e/3600)),i=Math.floor((e-3600*n)/60),a=Math.floor(e-3600*n-60*i),(n?n+":":"")+(""+i).padStart(2,"0")+":"+(""+a).padStart(2,"0")+"."+t}function n(e){for(var i="",a=0;a/g,">");else if("object"==s.type){if(i+="<"+s.name,s.classes)for(var r=0;r"}else"timestamp"==s.type?i+="<"+t(s.value)+">":i+="<"+s.value+">"}return i}function i(i){return(void 0!==i.id?i.id+"\n":"")+t(i.startTime)+" --\x3e "+t(i.endTime)+function(t){var n="";const i=Object.keys(e).filter(n=>t[n]!==e[n]);return i.includes("direction")&&(n+=" vertical:"+t.direction),i.includes("alignment")&&(n+=" align:"+t.alignment),i.includes("size")&&(n+=" size:"+t.size+"%"),(i.includes("lineAlign")||i.includes("linePosition"))&&(n+=" line:"+t.linePosition+(t.snapToLines?"":"%")+(t.lineAlign&&t.lineAlign!=e.lineAlign?","+t.lineAlign:"")),(i.includes("textPosition")||i.includes("positionAlign"))&&(n+=" position:"+t.textPosition+"%"+(t.positionAlign&&t.positionAlign!==e.positionAlign?","+t.positionAlign:"")),n}(i)+"\n"+n(i.tree.children)+"\n\n"}function a(e){return"STYLE\n"+e+"\n\n"}this.serialize=function(e,t){var n="WEBVTT\n\n";if(t)for(var s=0;s{const{unescape:i,getExt:s,srtToVtt:r,assToVtt:o}=n.constructor.utils,l=new t,f=new a,c=await Promise.all(e.map(e=>async function(e,{getExt:t,srtToVtt:n,assToVtt:i}){const a=await fetch(e.url),s=await a.arrayBuffer(),r=new TextDecoder(e.encoding||"utf-8").decode(s);switch(e.type||t(e.url)){case"srt":return n(r);case"ass":return i(r);case"vtt":return r;default:return""}}(e,{getExt:s,srtToVtt:r,assToVtt:o}))),u=c.map((t,n)=>{const i=l.parse(t,"metadata");return i.url=e[n].url,i.name=e[n].name,i});let d="";function p(e=[]){const a=function(e){const n=(new t).parse("","metadata");for(let t=0;t${n.value}`}}}n.cues.push(...i.cues)}return n}(e),s=f.serialize(a.cues);URL.revokeObjectURL(d);const r=URL.createObjectURL(new Blob([s],{type:"text/vtt"}));d=r,n.option.subtitle.escape=!1,n.subtitle.init({...n.option.subtitle,url:r,type:"vtt",onVttLoad:i})}return p(u),{name:"multipleSubtitles",tracks:(e=[])=>p(e.map(e=>u.find(t=>t.name===e))),reset:()=>p(u)}}}}); +!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerPluginMultipleSubtitles=t(),define(function(){return e.artplayerPluginMultipleSubtitles})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerPluginMultipleSubtitles=t()}(this,function(){"use strict";var e={direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center"},t=function(t){t||(t={"&":"&","<":"<",">":">","&lrm":"\u200e","&rlm":"\u200f"," ":"\xa0"}),this.entities=t,this.parse=function(a,s){a=a.replace(/\0/g,"\ufffd");var r=Date.now(),o=0,l=a.split(/\r\n|\r|\n/),f=!1,c=[],u=[],d=[];function p(e,t){d.push({message:e,line:o+1,col:t})}var m=l[o],g=m.length,h="WEBVTT",v=0,b=6;for("\ufeff"===m[0]&&(v=1,b+=1),(gb&&" "!==m[b]&&"\t"!==m[b])&&p('No valid signature. (File needs to start with "WEBVTT".)'),o++;""!=l[o]&&void 0!=l[o];){if(p("No blank line after the signature."),-1!=l[o].indexOf("--\x3e")){f=!0;break}o++}for(;void 0!=l[o];){for(var x;!f&&""==l[o];)o++;if(!f&&void 0==l[o])break;x=Object.assign({},e,{id:"",startTime:0,endTime:0,pauseOnExit:!1,direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center",text:"",tree:null});var T=!0;if(-1==l[o].indexOf("--\x3e")){if(x.id=l[o],/^NOTE($|[ \t])/.test(x.id)){for(o++;""!=l[o]&&void 0!=l[o];)-1!=l[o].indexOf("--\x3e")&&p("Cannot have timestamp in a comment."),o++;continue}if(/^STYLE($|[ \t])/.test(x.id)){var y=[],w=!1;for(o++;""!=l[o]&&void 0!=l[o];)-1!=l[o].indexOf("--\x3e")&&(p("Cannot have timestamp in a style block."),w=!0),y.push(l[o]),o++;if(u.length){p("Style blocks cannot appear after the first cue.");continue}w||c.push(y.join("\n"));continue}if(""==l[++o]||void 0==l[o]){p("Cue identifier cannot be standalone.");continue}if(-1==l[o].indexOf("--\x3e")){T=!1,p("Cue identifier needs to be followed by timestamp.");continue}}f=!1;var O=new n(l[o],p),L=0;if(u.length>0&&(L=u[u.length-1].startTime),!T||O.parse(x,L)){for(o++;""!=l[o]&&void 0!=l[o];){if(-1!=l[o].indexOf("--\x3e")){p("Blank line missing before cue."),f=!0;break}""!=x.text&&(x.text+="\n"),x.text+=l[o],o++}var I=new i(x.text,p,s,t);x.tree=I.parse(x.startTime,x.endTime),u.push(x)}else for(x=null,o++;""!=l[o]&&void 0!=l[o];){if(-1!=l[o].indexOf("--\x3e")){f=!0;break}o++}}return u.sort(function(e,t){return e.startTimet.startTime?1:e.endTime>t.endTime?-1:e.endTime2||parseInt(t,10)>59)&&(l="hours"),":"==e[a])if(a++,2==(n=o(/\d/)).length){if("hours"==l||":"==e[a]){if(":"!=e[a])return void s("No seconds found or minutes is greater than 59.");if(a++,2!=(i=o(/\d/)).length)return void s("Must be exactly two digits.")}else{if(2!=t.length)return void s("Must be exactly two digits.");i=n,n=t,t="0"}if("."==e[a])if(a++,3==(r=o(/\d/)).length)if(parseInt(n,10)>59)s("You cannot have more than 59 minutes.");else{if(!(parseInt(i,10)>59))return 60*parseInt(t,10)*60+60*parseInt(n,10)+parseInt(i,10)+parseInt(r,10)/1e3;s("You cannot have more than 59 seconds.")}else s("Milliseconds must be given in three digits.");else s('No decimal separator (".") found.')}else s("Must be exactly two digits.");else s("No time unit separator found.");else s("Timestamp must start with a character in the range 0-9.");else s("No timestamp found.")}this.parse=function(t,o){if(r(n),t.startTime=l(),void 0!=t.startTime)if(t.startTime"==e[a]){if(a++,i.test(e[a])&&s("'--\x3e' not separated from timestamp by whitespace."),r(n),t.endTime=l(),void 0!=t.endTime)return t.endTime<=t.startTime&&s("End timestamp is not greater than start timestamp."),i.test(e[a]),r(n),function(e,t){for(var i=e.split(n),a=[],r=0;r100)){s("Line position cannot be >100%.");continue}if(""===d||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==u){if(!["start","center","end"].includes(u)){s("Line alignment needs to be one of start, center or end");continue}t.lineAlign=u}t.snapToLines=!p,t.linePosition=parseFloat(d),parseFloat(d).toString()!==d&&(t.nonSerializable=!0)}else if("position"==l){if(/,/.test(f)){c=f.split(","),f=c[0];var m=c[1]}if("%"!=f[f.length-1]){s("Text position must be a percentage.");continue}if(parseInt(f,10)>100||parseInt(f,10)<0){s("Text position needs to be between 0 and 100%.");continue}if(""===(d=f.slice(0,f.length-1))||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==m){if(!["line-left","center","line-right"].includes(m)){s("Position alignment needs to be one of line-left, center or line-right");continue}t.positionAlign=m}t.textPosition=parseFloat(d)}else if("size"==l){if("%"!=f[f.length-1]){s("Size must be a percentage.");continue}if(parseInt(f,10)>100){s("Size cannot be >100%.");continue}var g=f.slice(0,f.length-1);if(void 0===g||""===g||isNaN(g)){s("Size needs to be a number"),g=100;continue}if((g=parseFloat(g))<0||g>100){s("Size needs to be between 0 and 100%.");continue}t.size=g}else if("align"==l){var h=["start","center","end","left","right"];if(-1==h.indexOf(f)){s("Alignment can only be set to one of "+h.join(", ")+".");continue}t.alignment=f}else s("Invalid setting.")}}(e.substring(a),t),!0}else s("No valid timestamp separator found.");else s("No valid timestamp separator found.");else s("No valid timestamp separator found.")},this.parseTimestamp=function(){var t=l();if(void 0==e[a])return t;s("Timestamp must not have trailing characters.")}},i=function(e,t,i,a){this.entities=a;var s=this,r=(e=e,0),o=function(e){"metadata"!=i&&t(e,r+1)};function l(){for(var t="data",n="",i="",l=[];void 0!=e[r-1]||0==r;){var f=e[r];if("data"==t)if("&"==f)i=f,t="escape";else if("<"==f&&""==n)t="tag";else{if("<"==f||void 0==f)return["text",n];n+=f}else if("escape"==t){if("<"==f||void 0==f){let e;return o("Incorrect escape."),(e=i.match(/^&#([0-9]+)$/))?n+=String.fromCharCode(e[1]):s.entities[i]?n+=s.entities[i]:n+=i,["text",n]}if("&"==f)o("Incorrect escape."),n+=i,i=f;else if(/[a-z#0-9]/i.test(f))i+=f;else if(";"==f){let e;(e=i.match(/^&#(x?[0-9]+)$/))?n+=String.fromCharCode("0"+e[1]):s.entities[i+f]?n+=s.entities[i+f]:(e=Object.keys(a).find(e=>i.startsWith(e)))?n+=s.entities[e]+i.slice(e.length)+f:(o("Incorrect escape."),n+=i+";"),t="data"}else o("Incorrect escape."),n+=i+f,t="data"}else if("tag"==t)if("\t"==f||"\n"==f||"\f"==f||" "==f)t="start tag annotation";else if("."==f)t="start tag class";else if("/"==f)t="end tag";else if(/\d/.test(f))n=f,t="timestamp tag";else{if(">"==f||void 0==f)return">"==f&&r++,["start tag","",[],""];n=f,t="start tag"}else if("start tag"==t)if("\t"==f||"\f"==f||" "==f)t="start tag annotation";else if("\n"==f)i=f,t="start tag annotation";else if("."==f)t="start tag class";else{if(">"==f||void 0==f)return">"==f&&r++,["start tag",n,[],""];n+=f}else if("start tag class"==t)if("\t"==f||"\f"==f||" "==f)i&&l.push(i),i="",t="start tag annotation";else if("\n"==f)i&&l.push(i),i=f,t="start tag annotation";else if("."==f)i&&l.push(i),i="";else{if(">"==f||void 0==f)return">"==f&&r++,i&&l.push(i),["start tag",n,l,""];i+=f}else if("start tag annotation"==t){if(">"==f||void 0==f)return">"==f&&r++,["start tag",n,l,i=i.split(/[\u0020\t\f\r\n]+/).filter(function(e){if(e)return!0}).join(" ")];i+=f}else if("end tag"==t){if(">"==f||void 0==f)return">"==f&&r++,["end tag",n];n+=f}else if("timestamp tag"==t){if(">"==f||void 0==f)return">"==f&&r++,["timestamp",n];n+=f}else o("Never happens.");r++}}this.parse=function(t,a){var s={children:[]},f=s,c=[];function u(e){f.children.push({type:"object",name:e[1],classes:e[2],children:[],parent:f}),f=f.children[f.children.length-1]}function d(e){for(var t=f;t;){if(t.name==e)return!0;t=t.parent}}for(;void 0!=e[r];){var p=l();if("text"==p[0])f.children.push({type:"text",value:p[1],parent:f});else if("start tag"==p[0]){"chapters"==i&&o("Start tags not allowed in chapter title text.");var m=p[1];"v"!=m&&"lang"!=m&&""!=p[3]&&o("Only and can have an annotation."),"c"==m||"i"==m||"b"==m||"u"==m||"ruby"==m||"rt"==m&&"ruby"==f.name?u(p):"v"==m?(d("v")&&o(" cannot be nested inside itself."),u(p),f.value=p[3],p[3]||o(" requires an annotation.")):"lang"==m?(u(p),f.value=p[3]):o("Incorrect start tag.")}else if("end tag"==p[0])"chapters"==i&&o("End tags not allowed in chapter title text."),p[1]==f.name?f=f.parent:"ruby"==p[1]&&"rt"==f.name?f=f.parent.parent:o("Incorrect end tag.");else if("timestamp"==p[0]){"chapters"==i&&o("Timestamp not allowed in chapter title text.");var g=new n(p[1],o).parseTimestamp();void 0!=g&&((g<=t||g>=a)&&o("Timestamp must be between start timestamp and end timestamp."),c.length>0&&c[c.length-1]>=g&&o("Timestamp must be greater than any previous timestamp."),f.children.push({type:"timestamp",value:g,parent:f}),c.push(g))}}for(;f.parent;)"v"!=f.name&&o("Required end tag missing."),f=f.parent;return function e(t){const n={...t};return t.children&&(n.children=t.children.map(e)),n.parent&&delete n.parent,n}(s)}},a=function(){function t(e){const t=("00"+1e3*(e-Math.floor(e)).toFixed(3)).slice(-3);let n=0,i=0,a=0;return e>=3600&&(n=Math.floor(e/3600)),i=Math.floor((e-3600*n)/60),a=Math.floor(e-3600*n-60*i),(n?n+":":"")+(""+i).padStart(2,"0")+":"+(""+a).padStart(2,"0")+"."+t}function n(e){for(var i="",a=0;a/g,">");else if("object"==s.type){if(i+="<"+s.name,s.classes)for(var r=0;r"}else"timestamp"==s.type?i+="<"+t(s.value)+">":i+="<"+s.value+">"}return i}function i(i){return(void 0!==i.id?i.id+"\n":"")+t(i.startTime)+" --\x3e "+t(i.endTime)+function(t){var n="";const i=Object.keys(e).filter(n=>t[n]!==e[n]);return i.includes("direction")&&(n+=" vertical:"+t.direction),i.includes("alignment")&&(n+=" align:"+t.alignment),i.includes("size")&&(n+=" size:"+t.size+"%"),(i.includes("lineAlign")||i.includes("linePosition"))&&(n+=" line:"+t.linePosition+(t.snapToLines?"":"%")+(t.lineAlign&&t.lineAlign!=e.lineAlign?","+t.lineAlign:"")),(i.includes("textPosition")||i.includes("positionAlign"))&&(n+=" position:"+t.textPosition+"%"+(t.positionAlign&&t.positionAlign!==e.positionAlign?","+t.positionAlign:"")),n}(i)+"\n"+n(i.tree.children)+"\n\n"}function a(e){return"STYLE\n"+e+"\n\n"}this.serialize=function(e,t){var n="WEBVTT\n\n";if(t)for(var s=0;s{const{unescape:i,getExt:s,srtToVtt:r,assToVtt:o}=n.constructor.utils,l=new t,f=new a,c=await Promise.all(e.map(e=>async function(e,{getExt:t,srtToVtt:n,assToVtt:i}){const a=await fetch(e.url),s=await a.arrayBuffer(),r=new TextDecoder(e.encoding||"utf-8").decode(s);switch(e.type||t(e.url)){case"srt":return n(r);case"ass":return i(r);case"vtt":return r;default:return""}}(e,{getExt:s,srtToVtt:r,assToVtt:o}))),u=c.map((t,n)=>{const i=l.parse(t,"metadata");return i.url=e[n].url,i.name=e[n].name,i});let d="";function p(e=[]){const a=function(e){const n=(new t).parse("","metadata");for(let t=0;t${n.value}`}}}n.cues.push(...i.cues)}return n}(e),s=f.serialize(a.cues);URL.revokeObjectURL(d);const r=URL.createObjectURL(new Blob([s],{type:"text/vtt"}));d=r,n.option.subtitle.escape=!1,n.subtitle.init({...n.option.subtitle,url:r,type:"vtt",onVttLoad:i})}return p(u),{name:"multipleSubtitles",tracks:(e=[])=>p(e.map(e=>u.find(t=>t.name===e))),reset:()=>p(u)}}}}); diff --git a/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.legacy.js b/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.legacy.js index f6b175bd8..14454c165 100644 --- a/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.legacy.js +++ b/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.legacy.js @@ -3,5 +3,56 @@ * Github: https://github.com/zhw2590582/ArtPlayer * (c) 2017-2026 Harvey Zhao * Released under the MIT License. + * + * This package includes WebVTT parser and serializer code from w3c/webvtt.js. + * Reference revision: 380cfcce34ba8b472d3a31474874eb72a0e5f460 + * https://github.com/w3c/webvtt.js/tree/380cfcce34ba8b472d3a31474874eb72a0e5f460 + * The parser has a CC0 public-domain dedication. Local adaptations replace + * the IIFE/global exports with named ESM exports and format the code. + * The ArtPlayer plugin wrapper remains MIT licensed. + * + * ## creative commons + * + * # CC0 1.0 Universal + * + * CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + * + * ### Statement of Purpose + * + * The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + * + * Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + * + * For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + * + * 1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + * + * i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; + * + * ii. moral rights retained by the original author(s) and/or performer(s); + * + * iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; + * + * iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; + * + * v. rights protecting the extraction, dissemination, use and reuse of data in a Work; + * + * vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and + * + * vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + * + * 2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + * + * 3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + * + * 4. __Limitations and Disclaimers.__ + * + * a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. + * + * b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. + * + * c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. + * + * d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. */ -!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(t.artplayerPluginMultipleSubtitles=t(),define(function(){return t.artplayerPluginMultipleSubtitles})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerPluginMultipleSubtitles=t()}(this,function(){"use strict";var e=Object.defineProperty,t=Object.defineProperties,n=Object.getOwnPropertyDescriptors,i=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,r=(t,n,i)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[n]=i,o=(e,t)=>{for(var n in t||(t={}))a.call(t,n)&&r(e,n,t[n]);if(i)for(var n of i(t))s.call(t,n)&&r(e,n,t[n]);return e},l=(e,t,n)=>new Promise((i,a)=>{var s=e=>{try{o(n.next(e))}catch(t){a(t)}},r=e=>{try{o(n.throw(e))}catch(t){a(t)}},o=e=>e.done?i(e.value):Promise.resolve(e.value).then(s,r);o((n=n.apply(e,t)).next())}),f={direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center"},c=function(e){e||(e={"&":"&","<":"<",">":">","&lrm":"\u200e","&rlm":"\u200f"," ":"\xa0"}),this.entities=e,this.parse=function(t,n){t=t.replace(/\0/g,"\ufffd");var i=Date.now(),a=0,s=t.split(/\r\n|\r|\n/),r=!1,o=[],l=[],c=[];function p(e,t){c.push({message:e,line:a+1,col:t})}var m=s[a],g=m.length,h="WEBVTT",v=0,b=6;for("\ufeff"===m[0]&&(v=1,b+=1),(gb&&" "!==m[b]&&"\t"!==m[b])&&p('No valid signature. (File needs to start with "WEBVTT".)'),a++;""!=s[a]&&void 0!=s[a];){if(p("No blank line after the signature."),-1!=s[a].indexOf("--\x3e")){r=!0;break}a++}for(;void 0!=s[a];){for(var x;!r&&""==s[a];)a++;if(!r&&void 0==s[a])break;x=Object.assign({},f,{id:"",startTime:0,endTime:0,pauseOnExit:!1,direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center",text:"",tree:null});var T=!0;if(-1==s[a].indexOf("--\x3e")){if(x.id=s[a],/^NOTE($|[ \t])/.test(x.id)){for(a++;""!=s[a]&&void 0!=s[a];)-1!=s[a].indexOf("--\x3e")&&p("Cannot have timestamp in a comment."),a++;continue}if(/^STYLE($|[ \t])/.test(x.id)){var y=[],w=!1;for(a++;""!=s[a]&&void 0!=s[a];)-1!=s[a].indexOf("--\x3e")&&(p("Cannot have timestamp in a style block."),w=!0),y.push(s[a]),a++;if(l.length){p("Style blocks cannot appear after the first cue.");continue}w||o.push(y.join("\n"));continue}if(""==s[++a]||void 0==s[a]){p("Cue identifier cannot be standalone.");continue}if(-1==s[a].indexOf("--\x3e")){T=!1,p("Cue identifier needs to be followed by timestamp.");continue}}r=!1;var O=new u(s[a],p),P=0;if(l.length>0&&(P=l[l.length-1].startTime),!T||O.parse(x,P)){for(a++;""!=s[a]&&void 0!=s[a];){if(-1!=s[a].indexOf("--\x3e")){p("Blank line missing before cue."),r=!0;break}""!=x.text&&(x.text+="\n"),x.text+=s[a],a++}var I=new d(x.text,p,n,e);x.tree=I.parse(x.startTime,x.endTime),l.push(x)}else for(x=null,a++;""!=s[a]&&void 0!=s[a];){if(-1!=s[a].indexOf("--\x3e")){r=!0;break}a++}}return l.sort(function(e,t){return e.startTimet.startTime?1:e.endTime>t.endTime?-1:e.endTime2||parseInt(t,10)>59)&&(l="hours"),":"==e[a])if(a++,2==(n=o(/\d/)).length){if("hours"==l||":"==e[a]){if(":"!=e[a])return void s("No seconds found or minutes is greater than 59.");if(a++,2!=(i=o(/\d/)).length)return void s("Must be exactly two digits.")}else{if(2!=t.length)return void s("Must be exactly two digits.");i=n,n=t,t="0"}if("."==e[a])if(a++,3==(r=o(/\d/)).length)if(parseInt(n,10)>59)s("You cannot have more than 59 minutes.");else{if(!(parseInt(i,10)>59))return 60*parseInt(t,10)*60+60*parseInt(n,10)+parseInt(i,10)+parseInt(r,10)/1e3;s("You cannot have more than 59 seconds.")}else s("Milliseconds must be given in three digits.");else s('No decimal separator (".") found.')}else s("Must be exactly two digits.");else s("No time unit separator found.");else s("Timestamp must start with a character in the range 0-9.");else s("No timestamp found.")}this.parse=function(t,o){if(r(n),t.startTime=l(),void 0!=t.startTime)if(t.startTime"==e[a]){if(a++,i.test(e[a])&&s("'--\x3e' not separated from timestamp by whitespace."),r(n),t.endTime=l(),void 0!=t.endTime)return t.endTime<=t.startTime&&s("End timestamp is not greater than start timestamp."),i.test(e[a]),r(n),function(e,t){for(var i=e.split(n),a=[],r=0;r100)){s("Line position cannot be >100%.");continue}if(""===d||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==u){if(!["start","center","end"].includes(u)){s("Line alignment needs to be one of start, center or end");continue}t.lineAlign=u}t.snapToLines=!p,t.linePosition=parseFloat(d),parseFloat(d).toString()!==d&&(t.nonSerializable=!0)}else if("position"==l){if(/,/.test(f)){c=f.split(","),f=c[0];var m=c[1]}if("%"!=f[f.length-1]){s("Text position must be a percentage.");continue}if(parseInt(f,10)>100||parseInt(f,10)<0){s("Text position needs to be between 0 and 100%.");continue}if(""===(d=f.slice(0,f.length-1))||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==m){if(!["line-left","center","line-right"].includes(m)){s("Position alignment needs to be one of line-left, center or line-right");continue}t.positionAlign=m}t.textPosition=parseFloat(d)}else if("size"==l){if("%"!=f[f.length-1]){s("Size must be a percentage.");continue}if(parseInt(f,10)>100){s("Size cannot be >100%.");continue}var g=f.slice(0,f.length-1);if(void 0===g||""===g||isNaN(g)){s("Size needs to be a number"),g=100;continue}if((g=parseFloat(g))<0||g>100){s("Size needs to be between 0 and 100%.");continue}t.size=g}else if("align"==l){var h=["start","center","end","left","right"];if(-1==h.indexOf(f)){s("Alignment can only be set to one of "+h.join(", ")+".");continue}t.alignment=f}else s("Invalid setting.")}}(e.substring(a),t),!0}else s("No valid timestamp separator found.");else s("No valid timestamp separator found.");else s("No valid timestamp separator found.")},this.parseTimestamp=function(){var t=l();if(void 0==e[a])return t;s("Timestamp must not have trailing characters.")}},d=function(e,t,n,i){this.entities=i;var a=this,s=(e=e,0),r=function(e){"metadata"!=n&&t(e,s+1)};function l(){for(var t="data",n="",o="",l=[];void 0!=e[s-1]||0==s;){var f=e[s];if("data"==t)if("&"==f)o=f,t="escape";else if("<"==f&&""==n)t="tag";else{if("<"==f||void 0==f)return["text",n];n+=f}else if("escape"==t){if("<"==f||void 0==f){let e;return r("Incorrect escape."),(e=o.match(/^&#([0-9]+)$/))?n+=String.fromCharCode(e[1]):a.entities[o]?n+=a.entities[o]:n+=o,["text",n]}if("&"==f)r("Incorrect escape."),n+=o,o=f;else if(/[a-z#0-9]/i.test(f))o+=f;else if(";"==f){let e;(e=o.match(/^&#(x?[0-9]+)$/))?n+=String.fromCharCode("0"+e[1]):a.entities[o+f]?n+=a.entities[o+f]:(e=Object.keys(i).find(e=>o.startsWith(e)))?n+=a.entities[e]+o.slice(e.length)+f:(r("Incorrect escape."),n+=o+";"),t="data"}else r("Incorrect escape."),n+=o+f,t="data"}else if("tag"==t)if("\t"==f||"\n"==f||"\f"==f||" "==f)t="start tag annotation";else if("."==f)t="start tag class";else if("/"==f)t="end tag";else if(/\d/.test(f))n=f,t="timestamp tag";else{if(">"==f||void 0==f)return">"==f&&s++,["start tag","",[],""];n=f,t="start tag"}else if("start tag"==t)if("\t"==f||"\f"==f||" "==f)t="start tag annotation";else if("\n"==f)o=f,t="start tag annotation";else if("."==f)t="start tag class";else{if(">"==f||void 0==f)return">"==f&&s++,["start tag",n,[],""];n+=f}else if("start tag class"==t)if("\t"==f||"\f"==f||" "==f)o&&l.push(o),o="",t="start tag annotation";else if("\n"==f)o&&l.push(o),o=f,t="start tag annotation";else if("."==f)o&&l.push(o),o="";else{if(">"==f||void 0==f)return">"==f&&s++,o&&l.push(o),["start tag",n,l,""];o+=f}else if("start tag annotation"==t){if(">"==f||void 0==f)return">"==f&&s++,["start tag",n,l,o=o.split(/[\u0020\t\f\r\n]+/).filter(function(e){if(e)return!0}).join(" ")];o+=f}else if("end tag"==t){if(">"==f||void 0==f)return">"==f&&s++,["end tag",n];n+=f}else if("timestamp tag"==t){if(">"==f||void 0==f)return">"==f&&s++,["timestamp",n];n+=f}else r("Never happens.");s++}}this.parse=function(t,i){var a={children:[]},f=a,c=[];function d(e){f.children.push({type:"object",name:e[1],classes:e[2],children:[],parent:f}),f=f.children[f.children.length-1]}function p(e){for(var t=f;t;){if(t.name==e)return!0;t=t.parent}}for(;void 0!=e[s];){var m=l();if("text"==m[0])f.children.push({type:"text",value:m[1],parent:f});else if("start tag"==m[0]){"chapters"==n&&r("Start tags not allowed in chapter title text.");var g=m[1];"v"!=g&&"lang"!=g&&""!=m[3]&&r("Only and can have an annotation."),"c"==g||"i"==g||"b"==g||"u"==g||"ruby"==g||"rt"==g&&"ruby"==f.name?d(m):"v"==g?(p("v")&&r(" cannot be nested inside itself."),d(m),f.value=m[3],m[3]||r(" requires an annotation.")):"lang"==g?(d(m),f.value=m[3]):r("Incorrect start tag.")}else if("end tag"==m[0])"chapters"==n&&r("End tags not allowed in chapter title text."),m[1]==f.name?f=f.parent:"ruby"==m[1]&&"rt"==f.name?f=f.parent.parent:r("Incorrect end tag.");else if("timestamp"==m[0]){"chapters"==n&&r("Timestamp not allowed in chapter title text.");var h=new u(m[1],r).parseTimestamp();void 0!=h&&((h<=t||h>=i)&&r("Timestamp must be between start timestamp and end timestamp."),c.length>0&&c[c.length-1]>=h&&r("Timestamp must be greater than any previous timestamp."),f.children.push({type:"timestamp",value:h,parent:f}),c.push(h))}}for(;f.parent;)"v"!=f.name&&r("Required end tag missing."),f=f.parent;return function e(t){const n=o({},t);return t.children&&(n.children=t.children.map(e)),n.parent&&delete n.parent,n}(a)}},p=function(){function e(e){const t=("00"+1e3*(e-Math.floor(e)).toFixed(3)).slice(-3);let n=0,i=0,a=0;return e>=3600&&(n=Math.floor(e/3600)),i=Math.floor((e-3600*n)/60),a=Math.floor(e-3600*n-60*i),(n?n+":":"")+(""+i).padStart(2,"0")+":"+(""+a).padStart(2,"0")+"."+t}function t(n){for(var i="",a=0;a/g,">");else if("object"==s.type){if(i+="<"+s.name,s.classes)for(var r=0;r"}else"timestamp"==s.type?i+="<"+e(s.value)+">":i+="<"+s.value+">"}return i}function n(n){return(void 0!==n.id?n.id+"\n":"")+e(n.startTime)+" --\x3e "+e(n.endTime)+function(e){var t="";const n=Object.keys(f).filter(t=>e[t]!==f[t]);return n.includes("direction")&&(t+=" vertical:"+e.direction),n.includes("alignment")&&(t+=" align:"+e.alignment),n.includes("size")&&(t+=" size:"+e.size+"%"),(n.includes("lineAlign")||n.includes("linePosition"))&&(t+=" line:"+e.linePosition+(e.snapToLines?"":"%")+(e.lineAlign&&e.lineAlign!=f.lineAlign?","+e.lineAlign:"")),(n.includes("textPosition")||n.includes("positionAlign"))&&(t+=" position:"+e.textPosition+"%"+(e.positionAlign&&e.positionAlign!==f.positionAlign?","+e.positionAlign:"")),t}(n)+"\n"+t(n.tree.children)+"\n\n"}function i(e){return"STYLE\n"+e+"\n\n"}this.serialize=function(e,t){var a="WEBVTT\n\n";if(t)for(var s=0;sl(null,null,function*(){const{unescape:a,getExt:s,srtToVtt:r,assToVtt:f}=i.constructor.utils,u=new c,d=new p,m=yield Promise.all(e.map(e=>function(e,t){return l(this,arguments,function*(e,{getExt:t,srtToVtt:n,assToVtt:i}){const a=yield fetch(e.url),s=yield a.arrayBuffer(),r=new TextDecoder(e.encoding||"utf-8").decode(s);switch(e.type||t(e.url)){case"srt":return n(r);case"ass":return i(r);case"vtt":return r;default:return""}})}(e,{getExt:s,srtToVtt:r,assToVtt:f}))),g=m.map((t,n)=>{const i=u.parse(t,"metadata");return i.url=e[n].url,i.name=e[n].name,i});let h="";function v(e=[]){const s=function(e){const t=(new c).parse("","metadata");for(let n=0;n${n.value}`}}}t.cues.push(...i.cues)}return t}(e),r=d.serialize(s.cues);URL.revokeObjectURL(h);const l=URL.createObjectURL(new Blob([r],{type:"text/vtt"}));var f;h=l,i.option.subtitle.escape=!1,i.subtitle.init((f=o({},i.option.subtitle),t(f,n({url:l,type:"vtt",onVttLoad:a}))))}return v(g),{name:"multipleSubtitles",tracks:(e=[])=>v(e.map(e=>g.find(t=>t.name===e))),reset:()=>v(g)}})}}); +!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerPluginMultipleSubtitles=t(),define(function(){return e.artplayerPluginMultipleSubtitles})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerPluginMultipleSubtitles=t()}(this,function(){"use strict";var e=Object.defineProperty,t=Object.defineProperties,n=Object.getOwnPropertyDescriptors,i=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,r=(t,n,i)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[n]=i,o=(e,t)=>{for(var n in t||(t={}))a.call(t,n)&&r(e,n,t[n]);if(i)for(var n of i(t))s.call(t,n)&&r(e,n,t[n]);return e},l=(e,t,n)=>new Promise((i,a)=>{var s=e=>{try{o(n.next(e))}catch(t){a(t)}},r=e=>{try{o(n.throw(e))}catch(t){a(t)}},o=e=>e.done?i(e.value):Promise.resolve(e.value).then(s,r);o((n=n.apply(e,t)).next())}),f={direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center"},c=function(e){e||(e={"&":"&","<":"<",">":">","&lrm":"\u200e","&rlm":"\u200f"," ":"\xa0"}),this.entities=e,this.parse=function(t,n){t=t.replace(/\0/g,"\ufffd");var i=Date.now(),a=0,s=t.split(/\r\n|\r|\n/),r=!1,o=[],l=[],c=[];function p(e,t){c.push({message:e,line:a+1,col:t})}var m=s[a],g=m.length,h="WEBVTT",v=0,b=6;for("\ufeff"===m[0]&&(v=1,b+=1),(gb&&" "!==m[b]&&"\t"!==m[b])&&p('No valid signature. (File needs to start with "WEBVTT".)'),a++;""!=s[a]&&void 0!=s[a];){if(p("No blank line after the signature."),-1!=s[a].indexOf("--\x3e")){r=!0;break}a++}for(;void 0!=s[a];){for(var x;!r&&""==s[a];)a++;if(!r&&void 0==s[a])break;x=Object.assign({},f,{id:"",startTime:0,endTime:0,pauseOnExit:!1,direction:"horizontal",snapToLines:!0,linePosition:"auto",lineAlign:"start",textPosition:"auto",positionAlign:"auto",size:100,alignment:"center",text:"",tree:null});var T=!0;if(-1==s[a].indexOf("--\x3e")){if(x.id=s[a],/^NOTE($|[ \t])/.test(x.id)){for(a++;""!=s[a]&&void 0!=s[a];)-1!=s[a].indexOf("--\x3e")&&p("Cannot have timestamp in a comment."),a++;continue}if(/^STYLE($|[ \t])/.test(x.id)){var y=[],w=!1;for(a++;""!=s[a]&&void 0!=s[a];)-1!=s[a].indexOf("--\x3e")&&(p("Cannot have timestamp in a style block."),w=!0),y.push(s[a]),a++;if(l.length){p("Style blocks cannot appear after the first cue.");continue}w||o.push(y.join("\n"));continue}if(""==s[++a]||void 0==s[a]){p("Cue identifier cannot be standalone.");continue}if(-1==s[a].indexOf("--\x3e")){T=!1,p("Cue identifier needs to be followed by timestamp.");continue}}r=!1;var O=new u(s[a],p),P=0;if(l.length>0&&(P=l[l.length-1].startTime),!T||O.parse(x,P)){for(a++;""!=s[a]&&void 0!=s[a];){if(-1!=s[a].indexOf("--\x3e")){p("Blank line missing before cue."),r=!0;break}""!=x.text&&(x.text+="\n"),x.text+=s[a],a++}var I=new d(x.text,p,n,e);x.tree=I.parse(x.startTime,x.endTime),l.push(x)}else for(x=null,a++;""!=s[a]&&void 0!=s[a];){if(-1!=s[a].indexOf("--\x3e")){r=!0;break}a++}}return l.sort(function(e,t){return e.startTimet.startTime?1:e.endTime>t.endTime?-1:e.endTime2||parseInt(t,10)>59)&&(l="hours"),":"==e[a])if(a++,2==(n=o(/\d/)).length){if("hours"==l||":"==e[a]){if(":"!=e[a])return void s("No seconds found or minutes is greater than 59.");if(a++,2!=(i=o(/\d/)).length)return void s("Must be exactly two digits.")}else{if(2!=t.length)return void s("Must be exactly two digits.");i=n,n=t,t="0"}if("."==e[a])if(a++,3==(r=o(/\d/)).length)if(parseInt(n,10)>59)s("You cannot have more than 59 minutes.");else{if(!(parseInt(i,10)>59))return 60*parseInt(t,10)*60+60*parseInt(n,10)+parseInt(i,10)+parseInt(r,10)/1e3;s("You cannot have more than 59 seconds.")}else s("Milliseconds must be given in three digits.");else s('No decimal separator (".") found.')}else s("Must be exactly two digits.");else s("No time unit separator found.");else s("Timestamp must start with a character in the range 0-9.");else s("No timestamp found.")}this.parse=function(t,o){if(r(n),t.startTime=l(),void 0!=t.startTime)if(t.startTime"==e[a]){if(a++,i.test(e[a])&&s("'--\x3e' not separated from timestamp by whitespace."),r(n),t.endTime=l(),void 0!=t.endTime)return t.endTime<=t.startTime&&s("End timestamp is not greater than start timestamp."),i.test(e[a]),r(n),function(e,t){for(var i=e.split(n),a=[],r=0;r100)){s("Line position cannot be >100%.");continue}if(""===d||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==u){if(!["start","center","end"].includes(u)){s("Line alignment needs to be one of start, center or end");continue}t.lineAlign=u}t.snapToLines=!p,t.linePosition=parseFloat(d),parseFloat(d).toString()!==d&&(t.nonSerializable=!0)}else if("position"==l){if(/,/.test(f)){c=f.split(","),f=c[0];var m=c[1]}if("%"!=f[f.length-1]){s("Text position must be a percentage.");continue}if(parseInt(f,10)>100||parseInt(f,10)<0){s("Text position needs to be between 0 and 100%.");continue}if(""===(d=f.slice(0,f.length-1))||isNaN(d)||!isFinite(d)){s("Line position needs to be a number");continue}if(void 0!==m){if(!["line-left","center","line-right"].includes(m)){s("Position alignment needs to be one of line-left, center or line-right");continue}t.positionAlign=m}t.textPosition=parseFloat(d)}else if("size"==l){if("%"!=f[f.length-1]){s("Size must be a percentage.");continue}if(parseInt(f,10)>100){s("Size cannot be >100%.");continue}var g=f.slice(0,f.length-1);if(void 0===g||""===g||isNaN(g)){s("Size needs to be a number"),g=100;continue}if((g=parseFloat(g))<0||g>100){s("Size needs to be between 0 and 100%.");continue}t.size=g}else if("align"==l){var h=["start","center","end","left","right"];if(-1==h.indexOf(f)){s("Alignment can only be set to one of "+h.join(", ")+".");continue}t.alignment=f}else s("Invalid setting.")}}(e.substring(a),t),!0}else s("No valid timestamp separator found.");else s("No valid timestamp separator found.");else s("No valid timestamp separator found.")},this.parseTimestamp=function(){var t=l();if(void 0==e[a])return t;s("Timestamp must not have trailing characters.")}},d=function(e,t,n,i){this.entities=i;var a=this,s=(e=e,0),r=function(e){"metadata"!=n&&t(e,s+1)};function l(){for(var t="data",n="",o="",l=[];void 0!=e[s-1]||0==s;){var f=e[s];if("data"==t)if("&"==f)o=f,t="escape";else if("<"==f&&""==n)t="tag";else{if("<"==f||void 0==f)return["text",n];n+=f}else if("escape"==t){if("<"==f||void 0==f){let e;return r("Incorrect escape."),(e=o.match(/^&#([0-9]+)$/))?n+=String.fromCharCode(e[1]):a.entities[o]?n+=a.entities[o]:n+=o,["text",n]}if("&"==f)r("Incorrect escape."),n+=o,o=f;else if(/[a-z#0-9]/i.test(f))o+=f;else if(";"==f){let e;(e=o.match(/^&#(x?[0-9]+)$/))?n+=String.fromCharCode("0"+e[1]):a.entities[o+f]?n+=a.entities[o+f]:(e=Object.keys(i).find(e=>o.startsWith(e)))?n+=a.entities[e]+o.slice(e.length)+f:(r("Incorrect escape."),n+=o+";"),t="data"}else r("Incorrect escape."),n+=o+f,t="data"}else if("tag"==t)if("\t"==f||"\n"==f||"\f"==f||" "==f)t="start tag annotation";else if("."==f)t="start tag class";else if("/"==f)t="end tag";else if(/\d/.test(f))n=f,t="timestamp tag";else{if(">"==f||void 0==f)return">"==f&&s++,["start tag","",[],""];n=f,t="start tag"}else if("start tag"==t)if("\t"==f||"\f"==f||" "==f)t="start tag annotation";else if("\n"==f)o=f,t="start tag annotation";else if("."==f)t="start tag class";else{if(">"==f||void 0==f)return">"==f&&s++,["start tag",n,[],""];n+=f}else if("start tag class"==t)if("\t"==f||"\f"==f||" "==f)o&&l.push(o),o="",t="start tag annotation";else if("\n"==f)o&&l.push(o),o=f,t="start tag annotation";else if("."==f)o&&l.push(o),o="";else{if(">"==f||void 0==f)return">"==f&&s++,o&&l.push(o),["start tag",n,l,""];o+=f}else if("start tag annotation"==t){if(">"==f||void 0==f)return">"==f&&s++,["start tag",n,l,o=o.split(/[\u0020\t\f\r\n]+/).filter(function(e){if(e)return!0}).join(" ")];o+=f}else if("end tag"==t){if(">"==f||void 0==f)return">"==f&&s++,["end tag",n];n+=f}else if("timestamp tag"==t){if(">"==f||void 0==f)return">"==f&&s++,["timestamp",n];n+=f}else r("Never happens.");s++}}this.parse=function(t,i){var a={children:[]},f=a,c=[];function d(e){f.children.push({type:"object",name:e[1],classes:e[2],children:[],parent:f}),f=f.children[f.children.length-1]}function p(e){for(var t=f;t;){if(t.name==e)return!0;t=t.parent}}for(;void 0!=e[s];){var m=l();if("text"==m[0])f.children.push({type:"text",value:m[1],parent:f});else if("start tag"==m[0]){"chapters"==n&&r("Start tags not allowed in chapter title text.");var g=m[1];"v"!=g&&"lang"!=g&&""!=m[3]&&r("Only and can have an annotation."),"c"==g||"i"==g||"b"==g||"u"==g||"ruby"==g||"rt"==g&&"ruby"==f.name?d(m):"v"==g?(p("v")&&r(" cannot be nested inside itself."),d(m),f.value=m[3],m[3]||r(" requires an annotation.")):"lang"==g?(d(m),f.value=m[3]):r("Incorrect start tag.")}else if("end tag"==m[0])"chapters"==n&&r("End tags not allowed in chapter title text."),m[1]==f.name?f=f.parent:"ruby"==m[1]&&"rt"==f.name?f=f.parent.parent:r("Incorrect end tag.");else if("timestamp"==m[0]){"chapters"==n&&r("Timestamp not allowed in chapter title text.");var h=new u(m[1],r).parseTimestamp();void 0!=h&&((h<=t||h>=i)&&r("Timestamp must be between start timestamp and end timestamp."),c.length>0&&c[c.length-1]>=h&&r("Timestamp must be greater than any previous timestamp."),f.children.push({type:"timestamp",value:h,parent:f}),c.push(h))}}for(;f.parent;)"v"!=f.name&&r("Required end tag missing."),f=f.parent;return function e(t){const n=o({},t);return t.children&&(n.children=t.children.map(e)),n.parent&&delete n.parent,n}(a)}},p=function(){function e(e){const t=("00"+1e3*(e-Math.floor(e)).toFixed(3)).slice(-3);let n=0,i=0,a=0;return e>=3600&&(n=Math.floor(e/3600)),i=Math.floor((e-3600*n)/60),a=Math.floor(e-3600*n-60*i),(n?n+":":"")+(""+i).padStart(2,"0")+":"+(""+a).padStart(2,"0")+"."+t}function t(n){for(var i="",a=0;a/g,">");else if("object"==s.type){if(i+="<"+s.name,s.classes)for(var r=0;r"}else"timestamp"==s.type?i+="<"+e(s.value)+">":i+="<"+s.value+">"}return i}function n(n){return(void 0!==n.id?n.id+"\n":"")+e(n.startTime)+" --\x3e "+e(n.endTime)+function(e){var t="";const n=Object.keys(f).filter(t=>e[t]!==f[t]);return n.includes("direction")&&(t+=" vertical:"+e.direction),n.includes("alignment")&&(t+=" align:"+e.alignment),n.includes("size")&&(t+=" size:"+e.size+"%"),(n.includes("lineAlign")||n.includes("linePosition"))&&(t+=" line:"+e.linePosition+(e.snapToLines?"":"%")+(e.lineAlign&&e.lineAlign!=f.lineAlign?","+e.lineAlign:"")),(n.includes("textPosition")||n.includes("positionAlign"))&&(t+=" position:"+e.textPosition+"%"+(e.positionAlign&&e.positionAlign!==f.positionAlign?","+e.positionAlign:"")),t}(n)+"\n"+t(n.tree.children)+"\n\n"}function i(e){return"STYLE\n"+e+"\n\n"}this.serialize=function(e,t){var a="WEBVTT\n\n";if(t)for(var s=0;sl(null,null,function*(){const{unescape:a,getExt:s,srtToVtt:r,assToVtt:f}=i.constructor.utils,u=new c,d=new p,m=yield Promise.all(e.map(e=>function(e,t){return l(this,arguments,function*(e,{getExt:t,srtToVtt:n,assToVtt:i}){const a=yield fetch(e.url),s=yield a.arrayBuffer(),r=new TextDecoder(e.encoding||"utf-8").decode(s);switch(e.type||t(e.url)){case"srt":return n(r);case"ass":return i(r);case"vtt":return r;default:return""}})}(e,{getExt:s,srtToVtt:r,assToVtt:f}))),g=m.map((t,n)=>{const i=u.parse(t,"metadata");return i.url=e[n].url,i.name=e[n].name,i});let h="";function v(e=[]){const s=function(e){const t=(new c).parse("","metadata");for(let n=0;n${n.value}`}}}t.cues.push(...i.cues)}return t}(e),r=d.serialize(s.cues);URL.revokeObjectURL(h);const l=URL.createObjectURL(new Blob([r],{type:"text/vtt"}));var f;h=l,i.option.subtitle.escape=!1,i.subtitle.init((f=o({},i.option.subtitle),t(f,n({url:l,type:"vtt",onVttLoad:a}))))}return v(g),{name:"multipleSubtitles",tracks:(e=[])=>v(e.map(e=>g.find(t=>t.name===e))),reset:()=>v(g)}})}}); diff --git a/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.mjs b/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.mjs index 8a9d230f3..4befa73d6 100644 --- a/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.mjs +++ b/packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.mjs @@ -3,6 +3,57 @@ * Github: https://github.com/zhw2590582/ArtPlayer * (c) 2017-2026 Harvey Zhao * Released under the MIT License. + * + * This package includes WebVTT parser and serializer code from w3c/webvtt.js. + * Reference revision: 380cfcce34ba8b472d3a31474874eb72a0e5f460 + * https://github.com/w3c/webvtt.js/tree/380cfcce34ba8b472d3a31474874eb72a0e5f460 + * The parser has a CC0 public-domain dedication. Local adaptations replace + * the IIFE/global exports with named ESM exports and format the code. + * The ArtPlayer plugin wrapper remains MIT licensed. + * + * ## creative commons + * + * # CC0 1.0 Universal + * + * CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + * + * ### Statement of Purpose + * + * The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + * + * Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + * + * For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + * + * 1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + * + * i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; + * + * ii. moral rights retained by the original author(s) and/or performer(s); + * + * iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; + * + * iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; + * + * v. rights protecting the extraction, dissemination, use and reuse of data in a Work; + * + * vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and + * + * vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + * + * 2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + * + * 3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + * + * 4. __Limitations and Disclaimers.__ + * + * a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. + * + * b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. + * + * c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. + * + * d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. */ var defaultCueSettings = { direction: "horizontal", diff --git a/refactor/baselines/multiple-subtitles-contract-validation.json b/refactor/baselines/multiple-subtitles-contract-validation.json new file mode 100644 index 000000000..6b9958a58 --- /dev/null +++ b/refactor/baselines/multiple-subtitles-contract-validation.json @@ -0,0 +1,153 @@ +{ + "schemaVersion": 1, + "task": "PKG-MULTI-SUB-01", + "status": "done", + "parentCommit": "0c5bb2bd7ac6d76b0b5f42dcdfb71ccdb31fb8d5", + "checks": [ + { + "command": "yarn test:multiple-subtitles", + "tests": 53, + "pass": 53, + "file": "refactor/.cache/multiple-subtitles01-suite.log", + "sha256": "36af923592894ee482aacf7af6292ddf3bafac1c571603359b86ab4186f2df5d" + }, + { + "command": "pinned upstream parser adaptation and complete license", + "result": { + "provenance": { + "revision": "380cfcce34ba8b472d3a31474874eb72a0e5f460", + "packageVersionAtRevision": "2.1.2", + "scope": "Pinned comparison revision, not proof of historical acquisition commit. After removing IIFE/global exportify and adding named ESM exports, normalized executable content matches local parser.", + "sources": [ + { + "file": "refactor/baselines/multiple-subtitles-vendor/parser.txt", + "upstream": "https://raw.githubusercontent.com/w3c/webvtt.js/380cfcce34ba8b472d3a31474874eb72a0e5f460/parser.js", + "sha256": "35a112e585b7cb1b4fd30350b0e8c8f6d1efa2670a6008c4a6038e07c9f8d727" + }, + { + "file": "refactor/baselines/multiple-subtitles-vendor/license.txt", + "upstream": "https://raw.githubusercontent.com/w3c/webvtt.js/380cfcce34ba8b472d3a31474874eb72a0e5f460/LICENSE.md", + "sha256": "6cc655a5df52fefac69058311c090f4e70b7c37b8f6488f9498420a930b8275d" + }, + { + "file": "refactor/baselines/multiple-subtitles-vendor/package.json.txt", + "upstream": "https://raw.githubusercontent.com/w3c/webvtt.js/380cfcce34ba8b472d3a31474874eb72a0e5f460/package.json", + "sha256": "d0102b9276839f1136ecafd9527102a28b44643e8ff403b3ddb1e51c04777a7b" + } + ] + }, + "normalizedSha256": "e71dc5073db409dcb8eef66a0d6bfe6c8d96fa7d157ff51a68decf6f05a7c80f", + "localSha256LF": "ba582074d57fa2d72880e6e4253fe14646787916b2b68e2a1e748e685cf96ab1", + "noticesSha256LF": "50755f38458d41151c7f0b1675c744aa365f0510dc11f53832691ef5c14ce6b6" + } + }, + { + "command": "yarn build artplayer-plugin-multiple-subtitles", + "file": "refactor/.cache/multiple-subtitles01-build.log", + "sha256": "81b37121fe29916391a899d047b30ed6ad73faadfe2327474f235c48321cf5b6", + "artifacts": { + "packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.js": "fa21ea1ac923cd4d9085828631b9f89988490d0302d3a5436059317a6ebf96d8", + "packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.legacy.js": "bd686716cfe2d7b23d1739ae59bc1934cab2d7c346e36f2690f79a439144a8e4", + "packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.mjs": "a4a04affca97f673b881b20d27641516d854dee734d445c41c4a906777802cd2" + } + }, + { + "command": "actual yarn pack and standalone headers", + "archive": "refactor/.cache/multiple-subtitles01-package-final.tgz", + "sha256": "6e83785d8348f021ba5df6e3a1f6828f238b519bd7985e4c1b1c887d6c491e20", + "manifest": { + "name": "artplayer-plugin-multiple-subtitles", + "version": "1.2.0", + "description": "multiple subtitles plugin for ArtPlayer", + "author": "Harvey Zhao ", + "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-multiple-subtitles.d.ts", + "import": "./dist/artplayer-plugin-multiple-subtitles.mjs", + "require": "./dist/artplayer-plugin-multiple-subtitles.js" + }, + "./legacy": { + "types": "./types/artplayer-plugin-multiple-subtitles.d.ts", + "import": "./dist/artplayer-plugin-multiple-subtitles.legacy.js", + "require": "./dist/artplayer-plugin-multiple-subtitles.legacy.js" + } + }, + "main": "./dist/artplayer-plugin-multiple-subtitles.js", + "module": "./dist/artplayer-plugin-multiple-subtitles.mjs", + "types": "./types/artplayer-plugin-multiple-subtitles.d.ts", + "legacy": "./dist/artplayer-plugin-multiple-subtitles.legacy.js", + "browserslist": "last 1 Chrome version" + }, + "members": { + "package/ARCHITECTURE.md": "6df20ecf8a537aad42ec44a471b79d612e93e9dc1068ae475d0db78dc6f8d285", + "package/README.md": "6b969577a9a842aded237d75de7b502e5a589b93ba6aca1f51d6d64ff8cc5c47", + "package/THIRD_PARTY_NOTICES": "50755f38458d41151c7f0b1675c744aa365f0510dc11f53832691ef5c14ce6b6", + "package/dist/artplayer-plugin-multiple-subtitles.js": "fa21ea1ac923cd4d9085828631b9f89988490d0302d3a5436059317a6ebf96d8", + "package/dist/artplayer-plugin-multiple-subtitles.legacy.js": "bd686716cfe2d7b23d1739ae59bc1934cab2d7c346e36f2690f79a439144a8e4", + "package/dist/artplayer-plugin-multiple-subtitles.mjs": "a4a04affca97f673b881b20d27641516d854dee734d445c41c4a906777802cd2", + "package/package.json": "77c93bc94154db46bdc2b2a3d02a03421ea0a49af54728bead91896dfae1092a", + "package/types/artplayer-plugin-multiple-subtitles.d.ts": "ab5dae1d0bdfcf2515cb842b1d465edf21dd195fe2fc5b0cfe351a8c06eb965c" + }, + "scope": "Actual tarball members and complete notices verified; not an installed consumer or native browser claim." + }, + { + "command": "candidate normal behavior source", + "tests": 5, + "pass": 5, + "file": "refactor/.cache/multiple-subtitles01-candidate-source.log", + "sha256": "5a9b041f56b47cc464cca0dbd6157a0c20d760488371343fac6ade25123f3aad" + }, + { + "command": "candidate normal behavior main", + "tests": 5, + "pass": 5, + "file": "refactor/.cache/multiple-subtitles01-candidate-main.log", + "sha256": "bd4f784ac1c78fefd5f70c94198d4f6eeb0c5afb022fcf4f6be9b9400f3acc48" + }, + { + "command": "candidate normal behavior legacy", + "tests": 5, + "pass": 5, + "file": "refactor/.cache/multiple-subtitles01-candidate-legacy.log", + "sha256": "50ba47e12a7d5f94223cb9797115cf3ddd593fdca9a8b1f828fd132e66864f61" + }, + { + "command": "yarn ci:check", + "tests": { + "unit": 1775, + "engineering": 14, + "baseline": 334, + "total": 2123 + }, + "strictProductionTypeScriptFiles": 346, + "file": "refactor/.cache/multiple-subtitles01-ci-final.log", + "sha256": "b4e02860bdc35bb25db4fd1e4ab36e499346a56d5eaa1abf5071fa8c19c45d06", + "registration": "Both new root test files are registered in test:unit; the contract suite is included by test:baseline." + }, + { + "command": "explicit lint including new helpers and refactor scripts", + "file": "refactor/.cache/multiple-subtitles01-lint-verified.log", + "sha256": "ee9dad77469369fbd40e8269ac7cb666ee3790e877977aa5e27e4cd60f1530cb" + } + ], + "publicSourceAndTypes": { + "packages/artplayer-plugin-multiple-subtitles/src/index.js": "02d7019e92bed7817d815f04df80605ae0bd94f03e2b8c52022b5f622ba2e2ba", + "packages/artplayer-plugin-multiple-subtitles/src/parser.js": "ba582074d57fa2d72880e6e4253fe14646787916b2b68e2a1e748e685cf96ab1", + "packages/artplayer-plugin-multiple-subtitles/types/artplayer-plugin-multiple-subtitles.d.ts": "6fc3107127b93b5107d679183dadd5740d4b7d5ea2cf2e51d877d576957e1386" + }, + "remaining": "Public type migration, error/lifecycle reproduction, native core/device combinations and complete distribution/demo consumers belong to tasks 02-06. Git core association is not support evidence. The pinned parser revision is a comparison source, not a proven historical acquisition commit." +} diff --git a/refactor/baselines/multiple-subtitles-contract.md b/refactor/baselines/multiple-subtitles-contract.md new file mode 100644 index 000000000..5c12f5213 --- /dev/null +++ b/refactor/baselines/multiple-subtitles-contract.md @@ -0,0 +1,50 @@ +# Multiple-subtitles 历史兼容契约 + +任务 PKG-MULTI-SUB-01。输入固定在 Git `0c5bb2bd7ac6d76b0b5f42dcdfb71ccdb31fb8d5`, +包括源码、声明、README、三个产物和 multiple.subtitles demo,共 9 份输入。 +真实 npm 1.0.0、1.1.0、1.2.0 共 20 个成员逐项保存 SHA-256,归档验证 registry SHA-512。 +下载来源、版本和完整成员见 [发布记录](multiple-subtitles-release.json)。三个历史 gitHead +关联的核心分别为 5.1.2、5.1.7、5.3.1;这是历史关联,不是全部已支持核心范围的证明。 + +| 维度 | 冻结事实 | +| --- | --- | +| 工厂 | artplayerPluginMultipleSubtitles({ subtitles = [] });整个参数不能省略,JS 可传 {} | +| 加载 | 异步注册;并行 fetch 全部 URL,arrayBuffer 后按 encoding 或 utf-8 解码 | +| 转换 | type 优先于 getExt(url);vtt 原文,srt/ass 使用核心转换器,其他扩展名产生空字幕文本 | +| 解析 | WebVTTParser metadata 模式;parser 各轨排序,不代表合并后按全局时间排序 | +| 1.0.0 合并 | 按 cue 数组下标把后续轨文字拼入首轨对应 cue,保留首轨时间 | +| 1.1.0 起合并 | 依次连接各轨 cue 数组,保留每轨自己的 cue 时间 | +| 样式 | 每轨顶层文本写入 art-subtitle-{name} div,reset 不重复套 div | +| 返回值 | Promise 最终结果有 name: multipleSubtitles、tracks(names = [])、reset() | +| 切换 | 按 name 查找并按调用者顺序输出;tracks() 或 [] 清空;reset 恢复初始轨顺序;不重新 fetch | +| 更新 | setTracks 返回 undefined;每次先 revoke 旧 URL,再创建 text/vtt Blob URL,调用 subtitle.init | +| 配置 | 永久把 art.option.subtitle.escape 改为 false;init 继承调用时 subtitle 配置,覆盖 url/type/onVttLoad | +| onParser | 三个版本都在声明中出现,但已执行的真实工厂没有调用它 | +| 类型 | subtitles 数组在声明中必需、其条目的 url/name/encoding 可选;声明没有 Promise、tracks/reset | +| 旧导出 | 1.0.0/1.1.0 实际 CommonJS 为含 default 的对象,声明却使用 export=;都有脚本全局 | +| 新导出 | 1.2.0 实际 CJS 直接函数,ESM default-only,声明使用默认导出;新增 exports/legacy 路径 | + +## Parser 来源与保留范围 + +固定比较源为 [w3c/webvtt.js 的 380cfcce 修订](https://github.com/w3c/webvtt.js/tree/380cfcce34ba8b472d3a31474874eb72a0e5f460), +该修订 package.json 的 version 为 2.1.2,不能把它误称为已验证的 npm 2.1.2 归档。 +原始文件和指纹在 [来源目录](multiple-subtitles-vendor/sources.json)。当前本地 parser 只 +改变 IIFE/global 导出为 ESM 导出、增加 eslint 说明并格式化;剥离这组明确适配后, +esbuild 规范化的完整执行代码相同。两个旧 npm 包保留 IIFE/exportify,经过同样边界比较 +后也一致。历史真正下载时使用的 commit 没有直接证据,此修订是固定比较源。 + +原始 CC0 头保留,完整 dedication 放入包内 THIRD_PARTY_NOTICES,由现有构建脚本放入 +main/legacy/mjs 独立文件头。parser/serializer 的 metadata、实体、样式、cue 0、排序和 +无效 timing 输入与固定上游对照。此项不声称所有 WebVTT 浏览器渲染或设备已经验收。 + +## 复现与后续任务 + +`yarn test:multiple-subtitles` 验证 53 项:9 份实现的 45 个正常行为、6 个发布契约、 +2 个 vendor/分发测试。源实现与实际 main/legacy 候选还分别执行 5 项正常调用回归。 +converter stub 只证明调用/类型选择,不等于验证实际 SRT/ASS 解析正确性。 +实际 ESM 验证入口及空轨注册,不能当作真实视频字幕显示验证。 + +02 继续复现错误、编码、重叠/空轨、失败和切换;03 负责拆分及请求/URL生命周期; +04 负责公开类型差异,05 负责原生核心/字幕/设备组合,06 负责安装消费者和实际 demo。 +源码目前缺少 fetch 取消及 destroy 的最后 URL 释放,仅从源码观察,未计作已修复。 +未知名字、轨道长度不等、HTML 样式节点、宿主失败等还需 02 系统复现。 diff --git a/refactor/baselines/multiple-subtitles-release.json b/refactor/baselines/multiple-subtitles-release.json new file mode 100644 index 000000000..a0d8b707f --- /dev/null +++ b/refactor/baselines/multiple-subtitles-release.json @@ -0,0 +1,199 @@ +{ + "schemaVersion": 1, + "task": "PKG-MULTI-SUB-01", + "capturedAt": "2026-09-13T01:46:21.521Z", + "sourceCommit": "0c5bb2bd7ac6d76b0b5f42dcdfb71ccdb31fb8d5", + "registryObservation": { + "url": "https://registry.npmjs.org/artplayer-plugin-multiple-subtitles", + "status": 200, + "sha256": "42f87af15439205eb6d3c114039b33a148dd7340d9be5ea859da0bacc02faa26", + "versions": [ + "1.0.0", + "1.1.0", + "1.2.0" + ], + "latest": "1.2.0", + "workspaceVersion": "1.2.0" + }, + "release": { + "name": "artplayer-plugin-multiple-subtitles", + "version": "1.2.0", + "metadataUrl": "https://registry.npmjs.org/artplayer-plugin-multiple-subtitles/1.2.0", + "tarball": "https://registry.npmjs.org/artplayer-plugin-multiple-subtitles/-/artplayer-plugin-multiple-subtitles-1.2.0.tgz", + "integrity": "sha512-3mzoHkgKx3KVdxKQBwLkjetPF6WjJtro5uQNdse8FqUeiV0afbywLnP6H8lcDN/Fwgp2VlBknrs2+COiyFdV8g==", + "sha256": "a013fbe0772bf560d177449fc80e848c41f16ae2f72ace86f8fb0d5b1000a54e", + "archiveBytes": 12209, + "publishedAt": "2026-03-12T14:20:38.214Z", + "registryGitHead": "daf133b22630b4a0eecfa3336bbddab0e9119d96", + "files": { + "package/README.md": "c811dabe9b0baa8739497b26ec287ad13beda59f996dec8e96f8d9244b612e86", + "package/dist/artplayer-plugin-multiple-subtitles.js": "c1cb0b511da88347165cc855185de9450a44835bb34bb802281ccdb854ef603c", + "package/dist/artplayer-plugin-multiple-subtitles.legacy.js": "0b17644827e5b199afe8293093c44bfda571821014ff5b087c7c918c630dcc18", + "package/dist/artplayer-plugin-multiple-subtitles.mjs": "e867c64303299a53d2bf6af62cc1e59044f1c7355aeb55e45b15ab2703448cb0", + "package/package.json": "3f8b631444e51da259f86d6cc83095df788eb3c41843724ad2a35d8b896b985f", + "package/types/artplayer-plugin-multiple-subtitles.d.ts": "6fc3107127b93b5107d679183dadd5740d4b7d5ea2cf2e51d877d576957e1386" + }, + "manifest": { + "name": "artplayer-plugin-multiple-subtitles", + "version": "1.2.0", + "description": "multiple subtitles plugin for ArtPlayer", + "author": "Harvey Zhao ", + "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-multiple-subtitles.d.ts", + "import": "./dist/artplayer-plugin-multiple-subtitles.mjs", + "require": "./dist/artplayer-plugin-multiple-subtitles.js" + }, + "./legacy": { + "types": "./types/artplayer-plugin-multiple-subtitles.d.ts", + "import": "./dist/artplayer-plugin-multiple-subtitles.legacy.js", + "require": "./dist/artplayer-plugin-multiple-subtitles.legacy.js" + } + }, + "main": "./dist/artplayer-plugin-multiple-subtitles.js", + "module": "./dist/artplayer-plugin-multiple-subtitles.mjs", + "types": "./types/artplayer-plugin-multiple-subtitles.d.ts", + "legacy": "./dist/artplayer-plugin-multiple-subtitles.legacy.js", + "browserslist": "last 1 Chrome version" + }, + "missingEntrypoints": {}, + "historicalCore": { + "version": "5.3.1", + "commit": "daf133b22630b4a0eecfa3336bbddab0e9119d96", + "file": "packages/artplayer/package.json", + "sha256LF": "862f3697876fe915dd0ada178da766ce823aae7563ed30b3e5b11b811202929c", + "scope": "Git association only; no npm core integration result is implied." + } + }, + "previous": [ + { + "name": "artplayer-plugin-multiple-subtitles", + "version": "1.1.0", + "metadataUrl": "https://registry.npmjs.org/artplayer-plugin-multiple-subtitles/1.1.0", + "tarball": "https://registry.npmjs.org/artplayer-plugin-multiple-subtitles/-/artplayer-plugin-multiple-subtitles-1.1.0.tgz", + "integrity": "sha512-gXbCTK09LKfxs4rXv5lkJiiEJj5NDBcAoCD6DMzFLTtw88nZs81Al5HMhvnNfm5lqcmF77LFhk8YYDChSGcWoA==", + "sha256": "b5e8cfa9671496b08a6f1377bace4ce557c865335dc2f746156707c03c8d9d16", + "archiveBytes": 22044, + "publishedAt": "2024-10-19T06:09:16.790Z", + "registryGitHead": "9221d42964700e6a3190943d288a6e6822596790", + "files": { + "package/README.md": "26b4d8914fd19976a1c5e2999a4146cb76a693f32dd874de4d8322b0da52829a", + "package/dist/artplayer-plugin-multiple-subtitles.js": "df40c0728decb7e39779d0f22cad0a32d5586a66bfdb19bcfecffbecca083a83", + "package/dist/artplayer-plugin-multiple-subtitles.legacy.js": "580514627926d94e8e085bc662fed693951250069bb8db6513709753bde33b5a", + "package/package.json": "6b044fa3bb2674ab94a930d8df4695dbb484f8b47cfc6b0cc193e820a2b0afd3", + "package/src/index.js": "b79aa2ef836902b7b99d80d1789cb3c5c400a8e3b50c01f29114c52be31e3a07", + "package/src/parser.js": "ce10bee2c21c59fd32230b253581738b59f103fcd2b350b74a245d630642e777", + "package/types/artplayer-plugin-multiple-subtitles.d.ts": "ddd581ac12fc6285f583f2f97c061ef013e6dc0fccab043ca450a9639bb0ea47" + }, + "manifest": { + "license": "MIT", + "version": "1.1.0", + "name": "artplayer-plugin-multiple-subtitles", + "types": "types/artplayer-plugin-multiple-subtitles.d.ts", + "description": "multiple subtitles plugin for ArtPlayer", + "main": "dist/artplayer-plugin-multiple-subtitles.js", + "legacy": "dist/artplayer-plugin-multiple-subtitles.legacy.js", + "author": "Harvey Zack ", + "browserslist": "last 1 Chrome version", + "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" + ] + }, + "missingEntrypoints": {}, + "historicalCore": { + "version": "5.1.7", + "commit": "9221d42964700e6a3190943d288a6e6822596790", + "file": "packages/artplayer/package.json", + "sha256LF": "8bd532103099c367fb2c289e0d410f144fdeb00b1b62cf850762a24b61e63c8a", + "scope": "Git association only; no npm core integration result is implied." + } + }, + { + "name": "artplayer-plugin-multiple-subtitles", + "version": "1.0.0", + "metadataUrl": "https://registry.npmjs.org/artplayer-plugin-multiple-subtitles/1.0.0", + "tarball": "https://registry.npmjs.org/artplayer-plugin-multiple-subtitles/-/artplayer-plugin-multiple-subtitles-1.0.0.tgz", + "integrity": "sha512-BF3nQDkXtFXt+TnGZSXM711Sc9b1lIUQEzMjp1YGnI8p+CFbiDW7EJDmRNy3psZXqRoUXVmpZ86FtZjqra8UPw==", + "sha256": "9b584f27287dbda1722315c07d05e1d7391453130b8fd9f952669e809e662ef5", + "archiveBytes": 22428, + "publishedAt": "2024-05-27T03:33:19.759Z", + "registryGitHead": "43309b72cff84344bd61f4de505aee0e10a83e6b", + "files": { + "package/README.md": "734d156e18a2b577d0ca9e85f5599cbb221ffc694195d79a9ccbe4f715224d9d", + "package/dist/artplayer-plugin-multiple-subtitles.js": "89ba01b678b5ca5e5277482718f55f496317ca9416d0d7b3d46b5c306f399c42", + "package/dist/artplayer-plugin-multiple-subtitles.legacy.js": "1ed7790a910dec50846304a8869a8ea3f8ab61fbb49de1afbf7c426312831f12", + "package/package.json": "70e5dfbfae4d6e7590223b22651750a65940c006b64faa0b9ac47eaeaad22be0", + "package/src/index.js": "ecf74ed0f5f7760f906e818883fbf5a58339b41a13ceb6080e224d4815a94502", + "package/src/parser.js": "ce10bee2c21c59fd32230b253581738b59f103fcd2b350b74a245d630642e777", + "package/types/artplayer-plugin-multiple-subtitles.d.ts": "33aab7b7c098e39f3a11cfa264c07452b2e3ad0dc3a7a8c8c3c95dae6856bd74" + }, + "manifest": { + "license": "MIT", + "version": "1.0.0", + "name": "artplayer-plugin-multiple-subtitles", + "types": "types/artplayer-plugin-multiple-subtitles.d.ts", + "description": "multiple subtitles plugin for ArtPlayer", + "main": "dist/artplayer-plugin-multiple-subtitles.js", + "legacy": "dist/artplayer-plugin-multiple-subtitles.legacy.js", + "author": "Harvey Zack ", + "browserslist": "last 1 Chrome version", + "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" + ] + }, + "missingEntrypoints": {}, + "historicalCore": { + "version": "5.1.2", + "commit": "43309b72cff84344bd61f4de505aee0e10a83e6b", + "file": "packages/artplayer/package.json", + "sha256LF": "aaf3ba9c7beaaea31170cc50e3958c0bb5d779ab4f90b6a213994ce8c9aace36", + "scope": "Git association only; no npm core integration result is implied." + } + } + ], + "source": { + "packages/artplayer-plugin-multiple-subtitles/package.json": "3f8b631444e51da259f86d6cc83095df788eb3c41843724ad2a35d8b896b985f", + "packages/artplayer-plugin-multiple-subtitles/README.md": "c811dabe9b0baa8739497b26ec287ad13beda59f996dec8e96f8d9244b612e86", + "packages/artplayer-plugin-multiple-subtitles/src/index.js": "02d7019e92bed7817d815f04df80605ae0bd94f03e2b8c52022b5f622ba2e2ba", + "packages/artplayer-plugin-multiple-subtitles/src/parser.js": "ba582074d57fa2d72880e6e4253fe14646787916b2b68e2a1e748e685cf96ab1", + "packages/artplayer-plugin-multiple-subtitles/types/artplayer-plugin-multiple-subtitles.d.ts": "6fc3107127b93b5107d679183dadd5740d4b7d5ea2cf2e51d877d576957e1386", + "packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.js": "c1cb0b511da88347165cc855185de9450a44835bb34bb802281ccdb854ef603c", + "packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.legacy.js": "0b17644827e5b199afe8293093c44bfda571821014ff5b087c7c918c630dcc18", + "packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.mjs": "e867c64303299a53d2bf6af62cc1e59044f1c7355aeb55e45b15ab2703448cb0", + "docs/assets/example/multiple.subtitles.js": "d9ccbd334d4c77f26826144870d6700e4b62f1f00b7f8f49817b3ac2583e5cc4" + } +} diff --git a/refactor/baselines/multiple-subtitles-vendor/license.txt b/refactor/baselines/multiple-subtitles-vendor/license.txt new file mode 100644 index 000000000..3593e7c00 --- /dev/null +++ b/refactor/baselines/multiple-subtitles-vendor/license.txt @@ -0,0 +1,44 @@ +## creative commons + +# CC0 1.0 Universal + +CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + +### Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + +1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + +2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + +3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + +4. __Limitations and Disclaimers.__ + + a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. + diff --git a/refactor/baselines/multiple-subtitles-vendor/package.json.txt b/refactor/baselines/multiple-subtitles-vendor/package.json.txt new file mode 100644 index 000000000..0f9b7cb82 --- /dev/null +++ b/refactor/baselines/multiple-subtitles-vendor/package.json.txt @@ -0,0 +1,29 @@ +{ + "name": "webvtt-parser", + "version": "2.1.2", + "description": "WebVTT parser and validator", + "main": "parser.js", + "files": ["parser.js", "html-entities.json"], + "scripts": { + "test": "mocha" + }, + "repository": { + "type": "git", + "url": "https://github.com/w3c/webvtt.js.git" + }, + "keywords": [ + "WebVTT" + ], + "author": "Anne van Kesteren ", + "contributors": [], + "license": "CC0-1.0", + "bugs": { + "url": "https://github.com/w3c/webvtt.js/issues" + }, + "homepage": "https://github.com/w3c/webvtt.js", + "devDependencies": { + "chai": "^4.2.0", + "mocha": "^8.0.1" + }, + "dependencies": {} +} diff --git a/refactor/baselines/multiple-subtitles-vendor/parser.txt b/refactor/baselines/multiple-subtitles-vendor/parser.txt new file mode 100644 index 000000000..07a130b9b --- /dev/null +++ b/refactor/baselines/multiple-subtitles-vendor/parser.txt @@ -0,0 +1,888 @@ +// Any copyright is dedicated to the Public Domain. +// http://creativecommons.org/publicdomain/zero/1.0/ + +// Not intended to be fast, but if you can make it faster, please help out! + +(function () { + var defaultCueSettings = { + direction:"horizontal", + snapToLines:true, + linePosition:"auto", + lineAlign:"start", + textPosition:"auto", + positionAlign:"auto", + size:100, + alignment:"center", + }; + + var WebVTTParser = function(entities) { + if (!entities) { + entities = { + "&": "&", + "<": "<", + ">": ">", + "&lrm": "\u200e", + "&rlm": "\u200f", + " ": "\u00A0" + } + } + this.entities = entities + this.parse = function(input, mode) { + // global search and replace for \0 + input = input.replace(/\0/g, '\uFFFD'); + var NEWLINE = /\r\n|\r|\n/, + startTime = Date.now(), + linePos = 0, + lines = input.split(NEWLINE), + alreadyCollected = false, + styles = [], + cues = [], + errors = [] + function err(message, col) { + errors.push({message:message, line:linePos+1, col:col}) + } + + var line = lines[linePos], + lineLength = line.length, + signature = "WEBVTT", + bom = 0, + signature_length = signature.length + + /* Byte order mark */ + if (line[0] === "\ufeff") { + bom = 1 + signature_length += 1 + } + /* SIGNATURE */ + if ( + lineLength < signature_length || + line.indexOf(signature) !== 0+bom || + lineLength > signature_length && + line[signature_length] !== " " && + line[signature_length] !== "\t" + ) { + err("No valid signature. (File needs to start with \"WEBVTT\".)") + } + + linePos++ + + /* HEADER */ + while(lines[linePos] != "" && lines[linePos] != undefined) { + err("No blank line after the signature.") + if(lines[linePos].indexOf("-->") != -1) { + alreadyCollected = true + break + } + linePos++ + } + + /* CUE LOOP */ + while(lines[linePos] != undefined) { + var cue + while(!alreadyCollected && lines[linePos] == "") { + linePos++ + } + if(!alreadyCollected && lines[linePos] == undefined) + break + + /* CUE CREATION */ + cue = Object.assign({}, defaultCueSettings, { + id:"", + startTime:0, + endTime:0, + pauseOnExit:false, + direction:"horizontal", + snapToLines:true, + linePosition:"auto", + lineAlign:"start", + textPosition:"auto", + positionAlign:"auto", + size:100, + alignment:"center", + text:"", + tree:null + }) + + var parseTimings = true + + if(lines[linePos].indexOf("-->") == -1) { + cue.id = lines[linePos] + + /* COMMENTS + Not part of the specification's parser as these would just be ignored. However, + we want them to be conforming and not get "Cue identifier cannot be standalone". + */ + if(/^NOTE($|[ \t])/.test(cue.id)) { // .startsWith fails in Chrome + linePos++ + while(lines[linePos] != "" && lines[linePos] != undefined) { + if(lines[linePos].indexOf("-->") != -1) + err("Cannot have timestamp in a comment.") + linePos++ + } + continue + } + + /* STYLES */ + if(/^STYLE($|[ \t])/.test(cue.id)) { + var style = [] + var invalid = false + linePos++ + while(lines[linePos] != "" && lines[linePos] != undefined) { + if(lines[linePos].indexOf("-->") != -1) { + err("Cannot have timestamp in a style block.") + invalid = true + } + style.push(lines[linePos]) + linePos++ + } + if(cues.length) { + err("Style blocks cannot appear after the first cue.") + continue + } + if (!invalid) { + styles.push(style.join('\n')) + } + continue + } + + linePos++ + + if(lines[linePos] == "" || lines[linePos] == undefined) { + err("Cue identifier cannot be standalone.") + continue + } + + if(lines[linePos].indexOf("-->") == -1) { + parseTimings = false + err("Cue identifier needs to be followed by timestamp.") + continue + } + } + + /* TIMINGS */ + alreadyCollected = false + var timings = new WebVTTCueTimingsAndSettingsParser(lines[linePos], err) + var previousCueStart = 0 + if(cues.length > 0) { + previousCueStart = cues[cues.length-1].startTime + } + if(parseTimings && !timings.parse(cue, previousCueStart)) { + /* BAD CUE */ + + cue = null + linePos++ + + /* BAD CUE LOOP */ + while(lines[linePos] != "" && lines[linePos] != undefined) { + if(lines[linePos].indexOf("-->") != -1) { + alreadyCollected = true + break + } + linePos++ + } + continue + } + linePos++ + + /* CUE TEXT LOOP */ + while(lines[linePos] != "" && lines[linePos] != undefined) { + if(lines[linePos].indexOf("-->") != -1) { + err("Blank line missing before cue.") + alreadyCollected = true + break + } + if(cue.text != "") + cue.text += "\n" + cue.text += lines[linePos] + linePos++ + } + + /* CUE TEXT PROCESSING */ + var cuetextparser = new WebVTTCueTextParser(cue.text, err, mode, entities) + cue.tree = cuetextparser.parse(cue.startTime, cue.endTime) + cues.push(cue) + } + cues.sort(function(a, b) { + if (a.startTime < b.startTime) + return -1 + if (a.startTime > b.startTime) + return 1 + if (a.endTime > b.endTime) + return -1 + if (a.endTime < b.endTime) + return 1 + return 0 + }) + /* END */ + return {cues:cues, errors:errors, time:Date.now()-startTime, styles: styles} + } + } + + var WebVTTCueTimingsAndSettingsParser = function(line, errorHandler) { + var SPACE = /[\u0020\t\f]/, + NOSPACE = /[^\u0020\t\f]/, + line = line, + pos = 0, + err = function(message) { + errorHandler(message, pos+1) + }, + spaceBeforeSetting = true + function skip(pattern) { + while( + line[pos] != undefined && + pattern.test(line[pos]) + ) { + pos++ + } + } + function collect(pattern) { + var str = "" + while( + line[pos] != undefined && + pattern.test(line[pos]) + ) { + str += line[pos] + pos++ + } + return str + } + /* http://dev.w3.org/html5/webvtt/#collect-a-webvtt-timestamp */ + function timestamp() { + var units = "minutes", + val1, + val2, + val3, + val4 + // 3 + if(line[pos] == undefined) { + err("No timestamp found.") + return + } + // 4 + if(!/\d/.test(line[pos])) { + err("Timestamp must start with a character in the range 0-9.") + return + } + // 5-7 + val1 = collect(/\d/) + if(val1.length > 2 || parseInt(val1, 10) > 59) { + units = "hours" + } + // 8 + if(line[pos] != ":") { + err("No time unit separator found.") + return + } + pos++ + // 9-11 + val2 = collect(/\d/) + if(val2.length != 2) { + err("Must be exactly two digits.") + return + } + // 12 + if(units == "hours" || line[pos] == ":") { + if(line[pos] != ":") { + err("No seconds found or minutes is greater than 59.") + return + } + pos++ + val3 = collect(/\d/) + if(val3.length != 2) { + err("Must be exactly two digits.") + return + } + } else { + if (val1.length != 2) { + err("Must be exactly two digits.") + return + } + val3 = val2 + val2 = val1 + val1 = "0" + } + // 13 + if(line[pos] != ".") { + err("No decimal separator (\".\") found.") + return + } + pos++ + // 14-16 + val4 = collect(/\d/) + if(val4.length != 3) { + err("Milliseconds must be given in three digits.") + return + } + // 17 + if(parseInt(val2, 10) > 59) { + err("You cannot have more than 59 minutes.") + return + } + if(parseInt(val3, 10) > 59) { + err("You cannot have more than 59 seconds.") + return + } + return parseInt(val1, 10) * 60 * 60 + parseInt(val2, 10) * 60 + parseInt(val3, 10) + parseInt(val4, 10) / 1000 + } + + /* http://dev.w3.org/html5/webvtt/#parse-the-webvtt-settings */ + function parseSettings(input, cue) { + var settings = input.split(SPACE), + seen = [] + for(var i=0; i < settings.length; i++) { + if(settings[i] == "") + continue + + var index = settings[i].indexOf(':'), + setting = settings[i].slice(0, index), + value = settings[i].slice(index + 1) + + if(seen.indexOf(setting) != -1) { + err("Duplicate setting.") + } + seen.push(setting) + + if(value == "") { + err("No value for setting defined.") + return + } + + if(setting == "vertical") { // writing direction + if(value != "rl" && value != "lr") { + err("Writing direction can only be set to 'rl' or 'rl'.") + continue + } + cue.direction = value + } else if(setting == "line") { // line position and optionally line alignment + if (/,/.test(value)) { + var comp = value.split(',') + value = comp[0] + var lineAlign = comp[1] + } + if(!/^[-\d](\d*)(\.\d+)?%?$/.test(value)) { + err("Line position takes a number or percentage.") + continue + } + if(value.indexOf("-", 1) != -1) { + err("Line position can only have '-' at the start.") + continue + } + if(value.indexOf("%") != -1 && value.indexOf("%") != value.length-1) { + err("Line position can only have '%' at the end.") + continue + } + if(value[0] == "-" && value[value.length-1] == "%") { + err("Line position cannot be a negative percentage.") + continue + } + var numVal = value; + var isPercent = false; + if(value[value.length-1] == "%") { + isPercent = true; + numVal = value.slice(0, value.length-1) + if(parseInt(value, 10) > 100) { + err("Line position cannot be >100%.") + continue + } + } + if (numVal === '' || isNaN(numVal) || !isFinite(numVal)) { + err("Line position needs to be a number") + continue + } + if (lineAlign !== undefined) { + if (!["start", "center", "end"].includes(lineAlign)) { + err("Line alignment needs to be one of start, center or end") + continue + } + cue.lineAlign = lineAlign + } + cue.snapToLines = !isPercent; + cue.linePosition = parseFloat(numVal) + if (parseFloat(numVal).toString() !== numVal) { + cue.nonSerializable = true; + } + } else if(setting == "position") { // text position and optional positionAlign + if (/,/.test(value)) { + var comp = value.split(',') + value = comp[0] + var positionAlign = comp[1] + } + if(value[value.length-1] != "%") { + err("Text position must be a percentage.") + continue + } + if(parseInt(value, 10) > 100 || parseInt(value, 10) < 0) { + err("Text position needs to be between 0 and 100%.") + continue + } + numVal = value.slice(0, value.length-1) + if (numVal === '' || isNaN(numVal) || !isFinite(numVal)) { + err("Line position needs to be a number") + continue + } + if (positionAlign !== undefined) { + if (!["line-left", "center", "line-right"].includes(positionAlign)) { + err("Position alignment needs to be one of line-left, center or line-right") + continue + } + cue.positionAlign = positionAlign + } + cue.textPosition = parseFloat(numVal) + } else if(setting == "size") { // size + if(value[value.length-1] != "%") { + err("Size must be a percentage.") + continue + } + if(parseInt(value, 10) > 100) { + err("Size cannot be >100%.") + continue + } + var size = value.slice(0, value.length -1) + if (size === undefined || size === "" || isNaN(size)) { + err("Size needs to be a number") + size = 100 + continue + } else { + size = parseFloat(size) + if (size < 0 || size > 100) { + err("Size needs to be between 0 and 100%.") + continue; + } + } + cue.size = size + } else if(setting == "align") { // alignment + var alignValues = ["start", "center", "end", "left", "right"] + if(alignValues.indexOf(value) == -1) { + err("Alignment can only be set to one of " + alignValues.join(", ") + ".") + continue + } + cue.alignment = value + } else { + err("Invalid setting.") + } + } + } + + this.parse = function(cue, previousCueStart) { + skip(SPACE) + cue.startTime = timestamp() + if(cue.startTime == undefined) { + return + } + if(cue.startTime < previousCueStart) { + err("Start timestamp is not greater than or equal to start timestamp of previous cue.") + } + if(NOSPACE.test(line[pos])) { + err("Timestamp not separated from '-->' by whitespace.") + } + skip(SPACE) + // 6-8 + if(line[pos] != "-") { + err("No valid timestamp separator found.") + return + } + pos++ + if(line[pos] != "-") { + err("No valid timestamp separator found.") + return + } + pos++ + if(line[pos] != ">") { + err("No valid timestamp separator found.") + return + } + pos++ + if(NOSPACE.test(line[pos])) { + err("'-->' not separated from timestamp by whitespace.") + } + skip(SPACE) + cue.endTime = timestamp() + if(cue.endTime == undefined) { + return + } + if(cue.endTime <= cue.startTime) { + err("End timestamp is not greater than start timestamp.") + } + + if(NOSPACE.test(line[pos])) { + spaceBeforeSetting = false + } + skip(SPACE) + parseSettings(line.substring(pos), cue) + return true + } + this.parseTimestamp = function() { + var ts = timestamp() + if(line[pos] != undefined) { + err("Timestamp must not have trailing characters.") + return + } + return ts + } + } + + var WebVTTCueTextParser = function(line, errorHandler, mode, entities) { + this.entities = entities + var self = this + var line = line, + pos = 0, + err = function(message) { + if(mode == "metadata") + return + errorHandler(message, pos+1) + } + + this.parse = function(cueStart, cueEnd) { + function removeCycles(tree) { + const cyclelessTree = {...tree}; + if (tree.children) { + cyclelessTree.children = tree.children.map(removeCycles); + } + if (cyclelessTree.parent) { + delete cyclelessTree.parent; + } + return cyclelessTree; + } + + var result = {children:[]}, + current = result, + timestamps = [] + + function attach(token) { + current.children.push({type:"object", name:token[1], classes:token[2], children:[], parent:current}) + current = current.children[current.children.length-1] + } + function inScope(name) { + var node = current + while(node) { + if(node.name == name) + return true + node = node.parent + } + return + } + + while(line[pos] != undefined) { + var token = nextToken() + if(token[0] == "text") { + current.children.push({type:"text", value:token[1], parent:current}) + } else if(token[0] == "start tag") { + if(mode == "chapters") + err("Start tags not allowed in chapter title text.") + var name = token[1] + if(name != "v" && name != "lang" && token[3] != "") { + err("Only and can have an annotation.") + } + if( + name == "c" || + name == "i" || + name == "b" || + name == "u" || + name == "ruby" + ) { + attach(token) + } else if(name == "rt" && current.name == "ruby") { + attach(token) + } else if(name == "v") { + if(inScope("v")) { + err(" cannot be nested inside itself.") + } + attach(token) + current.value = token[3] // annotation + if(!token[3]) { + err(" requires an annotation.") + } + } else if(name == "lang") { + attach(token) + current.value = token[3] // language + } else { + err("Incorrect start tag.") + } + } else if(token[0] == "end tag") { + if(mode == "chapters") + err("End tags not allowed in chapter title text.") + // XXX check content + if(token[1] == current.name) { + current = current.parent + } else if(token[1] == "ruby" && current.name == "rt") { + current = current.parent.parent + } else { + err("Incorrect end tag.") + } + } else if(token[0] == "timestamp") { + if(mode == "chapters") + err("Timestamp not allowed in chapter title text.") + var timings = new WebVTTCueTimingsAndSettingsParser(token[1], err), + timestamp = timings.parseTimestamp() + if(timestamp != undefined) { + if(timestamp <= cueStart || timestamp >= cueEnd) { + err("Timestamp must be between start timestamp and end timestamp.") + } + if(timestamps.length > 0 && timestamps[timestamps.length-1] >= timestamp) { + err("Timestamp must be greater than any previous timestamp.") + } + current.children.push({type:"timestamp", value:timestamp, parent:current}) + timestamps.push(timestamp) + } + } + } + while(current.parent) { + if(current.name != "v") { + err("Required end tag missing.") + } + current = current.parent + } + return removeCycles(result) + } + + function nextToken() { + var state = "data", + result = "", + buffer = "", + classes = [] + while(line[pos-1] != undefined || pos == 0) { + var c = line[pos] + if(state == "data") { + if(c == "&") { + buffer = c + state = "escape" + } else if(c == "<" && result == "") { + state = "tag" + } else if(c == "<" || c == undefined) { + return ["text", result] + } else { + result += c + } + } else if(state == "escape") { + if(c == "<" || c == undefined) { + err("Incorrect escape.") + let m; + if (m = buffer.match(/^&#([0-9]+)$/)) { + result += String.fromCharCode(m[1]) + } else { + if(self.entities[buffer]) { + result += self.entities[buffer] + } else { + result += buffer + } + } + return ["text", result] + } else if(c == "&") { + err("Incorrect escape.") + result += buffer + buffer = c + } else if(/[a-z#0-9]/i.test(c)) { + buffer += c + } else if(c == ";") { + let m; + if (m = buffer.match(/^&#(x?[0-9]+)$/)) { + // we prepend "0" so that x20 be interpreted as hexadecim (0x20) + result += String.fromCharCode("0" + m[1]) + } else if(self.entities[buffer + c]) { + result += self.entities[buffer + c] + } else if (m = Object.keys(entities).find(n => buffer.startsWith(n))) { // partial match + result += self.entities[m] + buffer.slice(m.length) + c + } else { + err("Incorrect escape.") + result += buffer + ";" + } + state = "data" + } else { + err("Incorrect escape.") + result += buffer + c + state = "data" + } + } else if(state == "tag") { + if(c == "\t" || c == "\n" || c == "\f" || c == " ") { + state = "start tag annotation" + } else if(c == ".") { + state = "start tag class" + } else if(c == "/") { + state = "end tag" + } else if(/\d/.test(c)) { + result = c + state = "timestamp tag" + } else if(c == ">" || c == undefined) { + if(c == ">") { + pos++ + } + return ["start tag", "", [], ""] + } else { + result = c + state = "start tag" + } + } else if(state == "start tag") { + if(c == "\t" || c == "\f" || c == " ") { + state = "start tag annotation" + } else if(c == "\n") { + buffer = c + state = "start tag annotation" + } else if(c == ".") { + state = "start tag class" + } else if(c == ">" || c == undefined) { + if(c == ">") { + pos++ + } + return ["start tag", result, [], ""] + } else { + result += c + } + } else if(state == "start tag class") { + if(c == "\t" || c == "\f" || c == " ") { + if (buffer) { + classes.push(buffer) + } + buffer = "" + state = "start tag annotation" + } else if(c == "\n") { + if (buffer) { + classes.push(buffer) + } + buffer = c + state = "start tag annotation" + } else if(c == ".") { + if (buffer) { + classes.push(buffer) + } + buffer = "" + } else if(c == ">" || c == undefined) { + if(c == ">") { + pos++ + } + if (buffer) { + classes.push(buffer) + } + return ["start tag", result, classes, ""] + } else { + buffer += c + } + } else if(state == "start tag annotation") { + if(c == ">" || c == undefined) { + if(c == ">") { + pos++ + } + buffer = buffer.split(/[\u0020\t\f\r\n]+/).filter(function(item) { if(item) return true }).join(" ") + return ["start tag", result, classes, buffer] + } else { + buffer +=c + } + } else if(state == "end tag") { + if(c == ">" || c == undefined) { + if(c == ">") { + pos++ + } + return ["end tag", result] + } else { + result += c + } + } else if(state == "timestamp tag") { + if(c == ">" || c == undefined) { + if(c == ">") { + pos++ + } + return ["timestamp", result] + } else { + result += c + } + } else { + err("Never happens.") // The joke is it might. + } + // 8 + pos++ + } + } + } + + var WebVTTSerializer = function() { + function serializeTimestamp(seconds) { + const ms = ("00" + (seconds - Math.floor(seconds)).toFixed(3)*1000).slice(-3); + let h = 0, m = 0, s = 0; + if (seconds >= 3600) { + h = Math.floor(seconds/3600); + } + m = Math.floor((seconds - 3600*h) / 60); + s = Math.floor(seconds - 3600*h - 60*m); + return (h ? h + ":" : "") + ("" + m).padStart(2, "0") + ":" + ("" + s).padStart(2, "0") + "." + ms; + } + function serializeCueSettings(cue) { + var result = "" + const nonDefaultSettings = Object.keys(defaultCueSettings).filter(s => cue[s] !== defaultCueSettings[s]); + if (nonDefaultSettings.includes("direction")) { + result+= " vertical:" + cue.direction + } + if (nonDefaultSettings.includes("alignment")) { + result+= " align:" + cue.alignment + } + if (nonDefaultSettings.includes("size")) { + result+= " size:" + cue.size + "%" + } + if (nonDefaultSettings.includes("lineAlign") || nonDefaultSettings.includes("linePosition")) { + result += " line:" + cue.linePosition + (cue.snapToLines ? "" : "%") + (cue.lineAlign && cue.lineAlign != defaultCueSettings.lineAlign ? "," + cue.lineAlign : "") + } + if (nonDefaultSettings.includes("textPosition") || nonDefaultSettings.includes("positionAlign")) { + result += " position:" + cue.textPosition + "%" + (cue.positionAlign && cue.positionAlign !== defaultCueSettings.positionAlign ? "," + cue.positionAlign : "") + } + return result + } + function serializeTree(tree) { + var result = "" + for (var i = 0; i < tree.length; i++) { + var node = tree[i] + if(node.type == "text") { + result += node.value.replace(/&/g, '&').replace(//g, '>'); + } else if(node.type == "object") { + result += "<" + node.name + if(node.classes) { + for(var y = 0; y < node.classes.length; y++) { + result += "." + node.classes[y] + } + } + if(node.value) { + result += " " + node.value + } + result += ">" + if(node.children) + result += serializeTree(node.children) + result += "" + } else if(node.type == "timestamp") { + result += "<" + serializeTimestamp(node.value) + ">" + } else { + result += "<" + node.value + ">" + } + } + return result + } + function serializeCue(cue) { + return (cue.id !== undefined ? cue.id + "\n" : "") + + serializeTimestamp(cue.startTime) + + " --> " + + serializeTimestamp(cue.endTime) + + serializeCueSettings(cue) + + "\n" + serializeTree(cue.tree.children) + "\n\n" + } + function serializeStyle(style) { + return "STYLE\n" + style + "\n\n" + } + this.serialize = function(cues, styles) { + var result = "WEBVTT\n\n" + if (styles) { + for(var i=0;i核对包契约与历史用法 | BASE-05 | subtitles/onParser、multipleSubtitles 名称及实际返回方法 | 源码/声明/README/demo/发布包差异已登记;公开形状和版本范围冻结;接续 VENDOR-03,定位 WebVTT parser 来源/修订及 CC0 头,保留解析/序列化行为 | H | todo | +| PKG-MULTI-SUB-01 | artplayer-plugin-multiple-subtitles
核对包契约与历史用法 | BASE-05 | subtitles/onParser、multipleSubtitles 名称及实际返回方法 | 源码/声明/README/demo/发布包差异已登记;公开形状和版本范围冻结;接续 VENDOR-03,定位 WebVTT parser 来源/修订及 CC0 头,保留解析/序列化行为 | H | done | | PKG-MULTI-SUB-02 | artplayer-plugin-multiple-subtitles
建立特有行为与错误测试 | PKG-MULTI-SUB-01, ENG-03, ENG-05 | VTT/SRT/ASS、编码/重叠 cue/排序/空轨/失败与切换 | 旧版本行为可重跑,成功/失败/切源/销毁有必要断言 | H | todo | | PKG-MULTI-SUB-03 | artplayer-plugin-multiple-subtitles
整理内部职责与资源 | PKG-MULTI-SUB-02, CORE-15 | 解析与合并/获取/渲染分离,过期请求及对象 URL 清理 | 结构变化和缺陷修复分开记录;原 API/事件/资源生命周期通过 | H | todo | | PKG-MULTI-SUB-04 | artplayer-plugin-multiple-subtitles
迁移自有源码和公开类型 | PKG-MULTI-SUB-03, ENG-04, ENG-06, CORE-07 | 准确 parser/cue/tree/result 类型与真实异步形状 | 严格类型检查、旧消费样例通过;声明路径/导出和同步异步兼容 | H | todo | @@ -511,6 +511,7 @@ - PKG-DASH-03: [记录](changes/2026-09-12-PKG-DASH-03-runtime.md) [记录](baselines/dash-runtime.json) [记录](dash-validation.md) - PKG-DASH-04: [记录](changes/2026-09-12-PKG-DASH-04-types.md) [记录](baselines/dash-types-validation.json) [记录](dash-validation.md) - PKG-DASH-05: [记录](changes/2026-09-12-PKG-DASH-05-sdk-checkpoint.md) [记录](baselines/dash-sdk.json) [记录](baselines/dash-sdk-checkpoint.json) [记录](dash-validation.md) [记录](changes/2026-09-12-PKG-DASH-05-sdk-types.md) [记录](baselines/dash-sdk-types-validation.json) [记录](changes/2026-09-12-PKG-DASH-05-sdk-events.md) [记录](baselines/dash-sdk-events-validation.json) [记录](changes/2026-09-12-PKG-DASH-05-seek-diagnosis.md) [记录](baselines/dash-seek-diagnosis.json) +- PKG-MULTI-SUB-01: [记录](baselines/multiple-subtitles-release.json) [记录](baselines/multiple-subtitles-contract.md) [记录](baselines/multiple-subtitles-contract-validation.json) [记录](changes/2026-09-13-PKG-MULTI-SUB-01-contract.md) - PKG-ADS-01: [记录](baselines/ads-release.json) [记录](baselines/ads-contract.md) [记录](baselines/ads-contract-validation.json) [记录](changes/2026-09-12-PKG-ADS-01-contract.md) [记录](scripts/ads-contract.test.mjs) - PKG-ADS-02: [记录](changes/2026-09-12-PKG-ADS-02-tests.md) [记录](ads-validation.md) [记录](baselines/ads-validation.json) - PKG-ADS-03: [记录](changes/2026-09-12-PKG-ADS-03-lifecycle.md) [记录](ads-validation.md) [记录](baselines/ads-lifecycle-validation.json) diff --git a/refactor/progress.md b/refactor/progress.md index a7bf90071..07de61d60 100644 --- a/refactor/progress.md +++ b/refactor/progress.md @@ -1,5 +1,20 @@ # 进度与证据 +## PKG-MULTI-SUB-01 历史契约与 parser 来源完成 + +冻结三个实际 npm 版本、20 成员与 9 份 Git 输入;53 项本包契约/vendor 测试通过, +当前源码/main/legacy 各 5 项正常行为通过。区分 1.0.0 按 cue 下标合并与 1.1.0 起连接轨道, +记录 async/tracks/reset/onParser 声明差异及旧 CJS 形状,后续错误/类型/原生验收仍待 02–06。 +固定 w3c/webvtt.js 比较修订,完整执行体仅封装/导出/格式适配,CC0 全文进入 notices、 +实际 tarball 和三个独立文件头,VENDOR-03 关闭;原始取得修订仍明确未知。 +完整 CI 最终 2123 项通过(含已接入主 test:unit 的 47 项新测试),严格生产 TS 仍 346 文件。 +首次 CI 日志发现两个新测试文件未接入显式清单,已修复后完整重跑,没有沿用较窄结果。 +见[契约](baselines/multiple-subtitles-contract.md)、[验证](baselines/multiple-subtitles-contract-validation.json) +和[变更](changes/2026-09-13-PKG-MULTI-SUB-01-contract.md)。生产工厂/声明未改,新增 4 项后续风险。 +222 项:118 done、13 doing、91 todo;独立本地任务提交,不推送、不发布。 +下一步 MULTI-SUB-02 复现错误和生命周期。VTT 的历史类型取舍仍待用户决定。 + + ## PKG-VTT-THUMB-04 历史模块形式核对(doing,类型取舍待用户决定) 实际仓库外安装矩阵扩至 32 格默认导入:31 编译通过,1 格复现 1.1.0 NodeNext ESM diff --git a/refactor/risk-table.md b/refactor/risk-table.md index dc251eb55..e0fb2348e 100644 --- a/refactor/risk-table.md +++ b/refactor/risk-table.md @@ -27,7 +27,7 @@ | BASE-MEDIA-01 | open / 待取证 | 示例媒体和字体的完整来源/授权链待核实 | BASE-08, SITE-01, EX-03 | | VENDOR-01 | resolved / 源码/产物事实 | screenfull 来源、版本与许可闭环 | CORE-12 | | VENDOR-02 | resolved / 源码/产物事实 | hint.css 来源、版本与许可闭环 | CORE-12 | -| VENDOR-03 | open / 待取证 | webvtt-parser 来源、版本与许可闭环 | PKG-MULTI-SUB-01 | +| VENDOR-03 | resolved / 已复现 | webvtt-parser 来源、版本与许可闭环 | PKG-MULTI-SUB-01 | | VENDOR-04 | open / 待取证 | jassub-code-and-workers 来源、版本与许可闭环 | PKG-JASSUB-01 | | VENDOR-05 | open / 待取证 | jassub-font-assets 来源、版本与许可闭环 | PKG-JASSUB-01, SITE-01 | | VENDOR-06 | open / 待取证 | monaco-static-assets 来源、版本与许可闭环 | SITE-01, SITE-05 | @@ -194,3 +194,7 @@ | VTT-THUMB-LIFE-01 | open / 已复现 | Fetch completion, setBar listeners and mobile timers have no destroy ownership | PKG-VTT-THUMB-02, PKG-VTT-THUMB-03, PKG-VTT-THUMB-05 | | VTT-THUMB-TYPE-01 | open / 已复现 | Published declarations falsely describe async registration as a synchronous result | PKG-VTT-THUMB-04 | | VTT-THUMB-EXPORT-01 | open / 已复现 | Older CommonJS default objects and thumbnails control names differ from latest direct export and vtt-thumbnail name | PKG-VTT-THUMB-04, PKG-VTT-THUMB-05, PKG-VTT-THUMB-06 | +| MULTI-SUB-TYPE-01 | open / 已复现 | Declarations omit async registration, tracks/reset and make the subtitles array required | PKG-MULTI-SUB-04 | +| MULTI-SUB-MERGE-01 | open / 已复现 | 1.0.0 merges cues by index while later versions concatenate independently timed track cues | PKG-MULTI-SUB-02, PKG-MULTI-SUB-03, PKG-MULTI-SUB-05 | +| MULTI-SUB-LIFE-01 | open / 源码/产物事实 | Pending downloads and final object URL have no destroy owner | PKG-MULTI-SUB-02, PKG-MULTI-SUB-03, PKG-MULTI-SUB-05 | +| MULTI-SUB-EXPORT-01 | open / 已复现 | Older CommonJS default objects conflict with export-assignment declarations; latest exports a direct factory | PKG-MULTI-SUB-04, PKG-MULTI-SUB-06 | diff --git a/refactor/risks.json b/refactor/risks.json index 9777fd311..f891a89fc 100644 --- a/refactor/risks.json +++ b/refactor/risks.json @@ -511,8 +511,8 @@ { "id": "VENDOR-03", "title": "webvtt-parser 来源、版本与许可闭环", - "confirmation": "unverified", - "status": "open", + "confirmation": "reproduced", + "status": "resolved", "owners": [ "PKG-MULTI-SUB-01" ], @@ -521,7 +521,16 @@ "packages/artplayer-plugin-multiple-subtitles/src/parser.js" ], "compatibleResolution": "Keep separate from owned TS migration. Verify source/version/diff and license notices before replacement; preserve API/CSS/worker URLs and run owning package tests.", - "closureCriteria": "固定上游版本/内容差异、完整组件许可与分发 notices,兼容测试通过;仅当前上游许可证名称不足以关闭。" + "closureCriteria": "固定上游版本/内容差异、完整组件许可与分发 notices,兼容测试通过;仅当前上游许可证名称不足以关闭。", + "resolutionEvidence": [ + "refactor/changes/2026-09-13-PKG-MULTI-SUB-01-contract.md", + "refactor/baselines/multiple-subtitles-contract-validation.json", + "refactor/baselines/multiple-subtitles-vendor/sources.json", + "refactor/scripts/multiple-subtitles-vendor.mjs", + "test/multiple-subtitles-vendor.test.js", + "packages/artplayer-plugin-multiple-subtitles/THIRD_PARTY_NOTICES" + ], + "resolutionRationale": "Pinned parser/license/manifest revision and exact normalized executable adaptation verified, including old shipped IIFE sources. Full CC0 dedication is present in actual packed package and all standalone bundle headers. Parser/serializer parity and plugin normal contracts pass. Historical acquisition commit remains unknown; pinned revision is the comparison reference. Device coverage remains in package tasks 05/06." }, { "id": "VENDOR-04", @@ -4234,6 +4243,79 @@ ], "compatibleResolution": "Validate historical import forms and control integrations before selecting compatibility adapters.", "closureCriteria": "Actual package consumers and old/new cores prove supported forms; unresolved differences stay explicit." + }, + { + "id": "MULTI-SUB-TYPE-01", + "title": "Declarations omit async registration, tracks/reset and make the subtitles array required", + "confirmation": "reproduced", + "status": "open", + "owners": [ + "PKG-MULTI-SUB-04" + ], + "evidence": [ + "refactor/baselines/multiple-subtitles-release.json", + "refactor/baselines/multiple-subtitles-contract.md", + "test/multiple-subtitles.test.js", + "refactor/scripts/multiple-subtitles-contract.test.mjs" + ], + "compatibleResolution": "Preserve valid old consumers while exposing accurate methods and async types; review onParser variance separately.", + "closureCriteria": "Strict old/new consumers and installed type views cover parameters, result methods and factory replacement." + }, + { + "id": "MULTI-SUB-MERGE-01", + "title": "1.0.0 merges cues by index while later versions concatenate independently timed track cues", + "confirmation": "reproduced", + "status": "open", + "owners": [ + "PKG-MULTI-SUB-02", + "PKG-MULTI-SUB-03", + "PKG-MULTI-SUB-05" + ], + "evidence": [ + "refactor/baselines/multiple-subtitles-release.json", + "refactor/baselines/multiple-subtitles-contract.md", + "test/multiple-subtitles.test.js", + "refactor/scripts/multiple-subtitles-contract.test.mjs" + ], + "compatibleResolution": "Keep historical merge profiles explicit and test real overlap/timing before choosing compatibility behavior.", + "closureCriteria": "Unaligned lengths, overlap, sorting, names and real subtitle display across supported cores are verified." + }, + { + "id": "MULTI-SUB-LIFE-01", + "title": "Pending downloads and final object URL have no destroy owner", + "confirmation": "source-observed", + "status": "open", + "owners": [ + "PKG-MULTI-SUB-02", + "PKG-MULTI-SUB-03", + "PKG-MULTI-SUB-05" + ], + "evidence": [ + "refactor/baselines/multiple-subtitles-release.json", + "refactor/baselines/multiple-subtitles-contract.md", + "test/multiple-subtitles.test.js", + "refactor/scripts/multiple-subtitles-contract.test.mjs" + ], + "compatibleResolution": "Reproduce stale completion and own requests and URLs without changing public selection methods.", + "closureCriteria": "Cancellation, failures, source changes, repeated selection and destroy are verified with native core coverage." + }, + { + "id": "MULTI-SUB-EXPORT-01", + "title": "Older CommonJS default objects conflict with export-assignment declarations; latest exports a direct factory", + "confirmation": "reproduced", + "status": "open", + "owners": [ + "PKG-MULTI-SUB-04", + "PKG-MULTI-SUB-06" + ], + "evidence": [ + "refactor/baselines/multiple-subtitles-release.json", + "refactor/baselines/multiple-subtitles-contract.md", + "test/multiple-subtitles.test.js", + "refactor/scripts/multiple-subtitles-contract.test.mjs" + ], + "compatibleResolution": "Preserve valid historical runtime import forms and explicitly assess type-only extraction conflicts.", + "closureCriteria": "Actual installed CJS/ESM/global/legacy consumers and their declarations are verified." } ] } diff --git a/refactor/scripts/contracts.test.mjs b/refactor/scripts/contracts.test.mjs index 01160e145..2f16f8ff2 100644 --- a/refactor/scripts/contracts.test.mjs +++ b/refactor/scripts/contracts.test.mjs @@ -44,7 +44,8 @@ function fixture(t) { test('Actual contract model assigns all 264 family rows and separates exact published versions from workspace snapshots', () => { assert.equal(actual.policy.packages.length, 22) assert.equal(actual.families.length, 12) - assert.equal(actual.policy.versions.filter(version => version.kind === 'published-baseline').length, 25) + assert.equal(actual.policy.versions.filter(version => version.kind === 'published-baseline').length, 28) + assert.deepEqual(actual.policy.versions.filter(version => version.kind === 'published-baseline' && version.package === 'artplayer-plugin-multiple-subtitles').map(version => version.version).sort(), ['1.0.0', '1.1.0', '1.2.0']) assert.deepEqual(actual.policy.versions.filter(version => version.kind === 'published-baseline' && version.package === 'artplayer-plugin-vtt-thumbnail').map(version => version.version).sort(), ['1.0.0', '1.0.1', '1.0.2', '1.0.3', '1.1.0']) assert.deepEqual(actual.policy.versions.filter(version => version.kind === 'published-baseline' && version.package === 'artplayer-plugin-auto-thumbnail').map(version => version.version).sort(), ['1.0.0', '1.0.1', '1.1.0']) assert.deepEqual(actual.policy.versions.filter(version => version.kind === 'published-baseline' && version.package === 'artplayer-proxy-mediabunny').map(version => version.version).sort(), ['1.0.0', '1.2.0']) diff --git a/refactor/scripts/multiple-subtitles-contract.mjs b/refactor/scripts/multiple-subtitles-contract.mjs new file mode 100644 index 000000000..ed45ea73b --- /dev/null +++ b/refactor/scripts/multiple-subtitles-contract.mjs @@ -0,0 +1,38 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' +import process from 'node:process' +import { fileURLToPath } from 'node:url' +import { archiveFiles, ensureArchive, hash, readMember, refactorDir } from './releases.mjs' + +export async function verifyMultipleSubtitlesContract() { + const baseline = JSON.parse(fs.readFileSync(path.join(refactorDir, 'baselines/multiple-subtitles-release.json'), 'utf8')) + const archives = new Map() + for (const release of [baseline.release, ...baseline.previous]) { + const archive = await ensureArchive(release) + assert.deepEqual(archiveFiles(archive), Object.keys(release.files).sort()) + for (const [file, expected] of Object.entries(release.files)) + assert.equal(hash(readMember(archive, file)), expected, `${release.version}/${file}`) + assert.deepEqual(JSON.parse(readMember(archive, 'package/package.json')), release.manifest) + const missing = Object.fromEntries(['main', 'module', 'types', 'legacy'].filter(field => release.manifest[field] && !Object.hasOwn(release.files, `package/${release.manifest[field].replace(/^\.\//, '')}`)).map(field => [field, release.manifest[field]])) + assert.deepEqual(missing, release.missingEntrypoints) + const core = release.historicalCore + const source = execFileSync('git', ['show', `${core.commit}:${core.file}`], { encoding: 'utf8' }).replaceAll('\r\n', '\n') + assert.equal(hash(source), core.sha256LF) + assert.equal(JSON.parse(source).version, core.version) + archives.set(release.version, archive) + } + const sources = new Map() + for (const [file, expected] of Object.entries(baseline.source)) { + const source = execFileSync('git', ['show', `${baseline.sourceCommit}:${file}`], { encoding: 'utf8' }).replaceAll('\r\n', '\n') + assert.equal(hash(source), expected, `Multiple-subtitles frozen source: ${file}`) + sources.set(file, source) + } + return { baseline, archives, sources } +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const { baseline } = await verifyMultipleSubtitlesContract() + console.log(`Multiple-subtitles verified: 3 actual npm archives, ${[baseline.release, ...baseline.previous].reduce((sum, item) => sum + Object.keys(item.files).length, 0)} members, ${Object.keys(baseline.source).length} frozen inputs`) +} diff --git a/refactor/scripts/multiple-subtitles-contract.test.mjs b/refactor/scripts/multiple-subtitles-contract.test.mjs new file mode 100644 index 000000000..af3484767 --- /dev/null +++ b/refactor/scripts/multiple-subtitles-contract.test.mjs @@ -0,0 +1,93 @@ +import assert from 'node:assert/strict' +import { Buffer } from 'node:buffer' +import fs from 'node:fs' +// eslint-disable-next-line test/no-import-node-test -- Published package contract runner. +import test from 'node:test' +import { transformSync } from 'esbuild' +import { multipleSubtitlesEnvironment, multipleSubtitlesHistorical } from '../../test/helpers/multiple-subtitles.js' +import { verifyMultipleSubtitlesContract } from './multiple-subtitles-contract.mjs' +import { adaptMultipleSubtitlesParser, checkMultipleSubtitlesVendor } from './multiple-subtitles-vendor.mjs' +import { hash, readMember } from './releases.mjs' + +const contract = await verifyMultipleSubtitlesContract() +const implementations = await multipleSubtitlesHistorical() +const name = 'artplayer-plugin-multiple-subtitles' + +test('Multiple-subtitles freezes three actual npm archives and Git inputs without inventing core support', () => { + assert.deepEqual([contract.baseline.release, ...contract.baseline.previous].map(item => item.version), ['1.2.0', '1.1.0', '1.0.0']) + assert.equal([...contract.archives].length, 3) + assert.equal([contract.baseline.release, ...contract.baseline.previous].reduce((sum, item) => sum + Object.keys(item.files).length, 0), 20) + assert.equal(contract.sources.size, 9) + assert.deepEqual([contract.baseline.release, ...contract.baseline.previous].map(item => item.historicalCore.version), ['5.3.1', '5.1.7', '5.1.2']) +}) + +test('Multiple-subtitles published declarations keep required subtitles while omitting Promise and real methods', () => { + for (const release of [contract.baseline.release, ...contract.baseline.previous]) { + const source = readMember(contract.archives.get(release.version), `package/${release.manifest.types.replace(/^\.\//, '')}`).toString() + assert.match(source, /subtitles: \{/) + for (const field of ['url', 'name', 'encoding']) + assert.match(source, new RegExp(`${field}\\?: string`)) + assert.match(source, /type\?: 'vtt' \| 'srt' \| 'ass'/) + assert.match(source, /onParser\?(?::|\()/) + assert.match(source, /name: 'multipleSubtitles'/) + assert.doesNotMatch(source, /Promise<|tracks\(|reset\(/) + assert.match(source, release.version === '1.2.0' ? /export default artplayerPluginMultipleSubtitles/ : /export = artplayerPluginMultipleSubtitles/) + } +}) + +test('Multiple-subtitles historical CommonJS and globals load without fetching and preserve actual export shapes', () => { + for (const implementation of implementations.filter(item => !item.name.includes('source'))) { + const env = multipleSubtitlesEnvironment(implementation) + assert.equal(typeof env.factory, 'function') + assert.equal(typeof env.exported, ['1.0.0', '1.1.0'].includes(implementation.version) ? 'object' : 'function') + if (typeof env.exported === 'object') + assert.deepEqual(Object.keys(env.exported), ['default']) + const browser = multipleSubtitlesEnvironment(implementation, { script: true }) + assert.equal(typeof browser.factory, 'function') + assert.deepEqual(env.requests, []) + assert.deepEqual(browser.requests, []) + } +}) + +test('Multiple-subtitles latest native ESM exports only the factory and asynchronously registers named methods', async () => { + const codes = [readMember(contract.archives.get('1.2.0'), 'package/dist/artplayer-plugin-multiple-subtitles.mjs').toString(), contract.sources.get(`packages/${name}/dist/${name}.mjs`)] + for (const code of codes) { + const exported = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`) + assert.deepEqual(Object.keys(exported), ['default']) + const env = multipleSubtitlesEnvironment(implementations[0]) + try { + const pending = exported.default({ subtitles: [] })(env.art) + assert.equal(pending.name, undefined) + const result = await pending + assert.deepEqual(Object.keys(result), ['name', 'tracks', 'reset']) + assert.equal(result.tracks([]), undefined) + } + finally { + for (const option of env.initialized) + URL.revokeObjectURL(option.url) + } + } +}) + +test('Multiple-subtitles shipped source parsers match the pinned upstream adaptation', () => { + const normalized = checkMultipleSubtitlesVendor().normalizedSha256 + for (const release of contract.baseline.previous) { + const source = readMember(contract.archives.get(release.version), 'package/src/parser.js').toString() + assert(source.startsWith('// Any copyright is dedicated to the Public Domain.')) + assert.equal(hash(transformSync(adaptMultipleSubtitlesParser(source), { format: 'esm', target: 'es2020', minifyWhitespace: true, legalComments: 'none' }).code), normalized) + } +}) + +test('Multiple-subtitles README and demo retain name-based switching, reset and per-language CSS hooks', () => { + for (const release of [contract.baseline.release, ...contract.baseline.previous]) + assert.match(readMember(contract.archives.get(release.version), 'package/README.md').toString(), /example=multiple\.subtitles/) + const source = contract.sources.get('docs/assets/example/multiple.subtitles.js') + assert(source.includes('art.plugins.multipleSubtitles.tracks(')) + assert(source.includes('art.plugins.multipleSubtitles.reset()')) + for (const language of ['chinese', 'japanese']) + assert(source.includes(`.art-subtitle-${language}`)) + for (const file of ['video.mp4', 'subtitle.cn.srt', 'subtitle.jp.srt']) { + assert(source.includes(`/assets/sample/${file}`)) + assert(fs.existsSync(`docs/assets/sample/${file}`)) + } +}) diff --git a/refactor/scripts/multiple-subtitles-vendor.mjs b/refactor/scripts/multiple-subtitles-vendor.mjs new file mode 100644 index 000000000..6d6a9dc9d --- /dev/null +++ b/refactor/scripts/multiple-subtitles-vendor.mjs @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +import { transformSync } from 'esbuild' +import { hash } from './releases.mjs' + +const base = 'refactor/baselines/multiple-subtitles-vendor' +export const vendorExports = 'export { WebVTTParser, WebVTTCueTimingsAndSettingsParser, WebVTTCueTextParser, WebVTTSerializer };' + +export function adaptMultipleSubtitlesParser(upstream) { + const start = '(function () {' + const end = ' function exportify(object)' + assert.equal(upstream.split(start).length, 2) + assert.equal(upstream.split(end).length, 2) + assert(upstream.slice(0, upstream.indexOf(start)).includes('http://creativecommons.org/publicdomain/zero/1.0/')) + const footer = upstream.slice(upstream.indexOf(end)).replaceAll(/[\s;]/g, '') + assert.equal(footer, 'functionexportify(object){object.WebVTTParser=WebVTTParserobject.WebVTTCueTimingsAndSettingsParser=WebVTTCueTimingsAndSettingsParserobject.WebVTTCueTextParser=WebVTTCueTextParserobject.WebVTTSerializer=WebVTTSerializer}if(typeofwindow!==\'undefined\')exportify(window)if(typeofexports!==\'undefined\')exportify(exports)})()') + return upstream.slice(upstream.indexOf(start) + start.length, upstream.indexOf(end)) + vendorExports +} + +export function checkMultipleSubtitlesVendor() { + const provenance = JSON.parse(fs.readFileSync(`${base}/sources.json`, 'utf8')) + for (const source of provenance.sources) + assert.equal(hash(fs.readFileSync(source.file)), source.sha256, source.file) + const upstream = fs.readFileSync(`${base}/parser.txt`, 'utf8') + const local = fs.readFileSync('packages/artplayer-plugin-multiple-subtitles/src/parser.js', 'utf8') + assert(local.startsWith('// Any copyright is dedicated to the Public Domain.')) + const normalize = source => transformSync(source, { format: 'esm', target: 'es2020', minifyWhitespace: true, legalComments: 'none' }).code + const expected = normalize(adaptMultipleSubtitlesParser(upstream)) + assert.equal(normalize(local), expected, 'Unreviewed WebVTT parser adaptation') + const notices = fs.readFileSync('packages/artplayer-plugin-multiple-subtitles/THIRD_PARTY_NOTICES', 'utf8').replaceAll('\r\n', '\n') + const license = fs.readFileSync(`${base}/license.txt`, 'utf8').replaceAll('\r\n', '\n').trim() + assert(notices.includes(license), 'Complete upstream dedication must be distributed') + assert(notices.includes(provenance.revision)) + return { provenance, normalizedSha256: hash(expected), localSha256LF: hash(local.replaceAll('\r\n', '\n')), noticesSha256LF: hash(notices) } +} diff --git a/refactor/tasks.json b/refactor/tasks.json index 9f95d7128..bd6f0f79f 100644 --- a/refactor/tasks.json +++ b/refactor/tasks.json @@ -2254,11 +2254,16 @@ "dependsOn": [ "BASE-05" ], - "status": "todo", + "status": "done", "risk": "H", "deliverable": "subtitles/onParser、multipleSubtitles 名称及实际返回方法", "acceptance": "源码/声明/README/demo/发布包差异已登记;公开形状和版本范围冻结;接续 VENDOR-03,定位 WebVTT parser 来源/修订及 CC0 头,保留解析/序列化行为", - "evidence": [] + "evidence": [ + "baselines/multiple-subtitles-release.json", + "baselines/multiple-subtitles-contract.md", + "baselines/multiple-subtitles-contract-validation.json", + "changes/2026-09-13-PKG-MULTI-SUB-01-contract.md" + ] }, { "id": "PKG-MULTI-SUB-02", diff --git a/refactor/third-party.json b/refactor/third-party.json index 6708bb6f8..5c1c74332 100644 --- a/refactor/third-party.json +++ b/refactor/third-party.json @@ -316,13 +316,14 @@ "owners": [ "PKG-MULTI-SUB-01" ], - "sourceStatus": "Local WebVTTParser/Serializer and CC0 header correspond to the upstream family; exact revision/diff unknown.", - "licenseStatus": "Local public-domain/CC0 dedication present; upstream repository identifies CC0-1.0.", + "sourceStatus": "Pinned 380cfcce34ba8b472d3a31474874eb72a0e5f460 comparison reference; exact normalized executable body matches local ESM and historical shipped IIFE adaptations. Historical acquisition revision remains unknown.", + "licenseStatus": "Complete pinned CC0 dedication retained in package notices and actual tarball/standalone main, legacy and ESM banners.", "upstreamSources": [ - "https://github.com/w3c/webvtt.js", - "https://raw.githubusercontent.com/w3c/webvtt.js/master/parser.js" + "https://raw.githubusercontent.com/w3c/webvtt.js/380cfcce34ba8b472d3a31474874eb72a0e5f460/parser.js", + "https://raw.githubusercontent.com/w3c/webvtt.js/380cfcce34ba8b472d3a31474874eb72a0e5f460/LICENSE.md", + "https://raw.githubusercontent.com/w3c/webvtt.js/380cfcce34ba8b472d3a31474874eb72a0e5f460/package.json" ], - "upstreamReviewedAt": "2026-09-10", + "upstreamReviewedAt": "2026-09-13", "updatePolicy": "Keep separate from owned TS migration. Verify source/version/diff and license notices before replacement; preserve API/CSS/worker URLs and run owning package tests.", "fingerprints": [ { @@ -330,6 +331,14 @@ "algorithm": "sha256-lf", "sha256": "ba582074d57fa2d72880e6e4253fe14646787916b2b68e2a1e748e685cf96ab1" } + ], + "verificationEvidence": [ + "refactor/changes/2026-09-13-PKG-MULTI-SUB-01-contract.md", + "refactor/baselines/multiple-subtitles-contract-validation.json", + "refactor/baselines/multiple-subtitles-vendor/sources.json", + "refactor/scripts/multiple-subtitles-vendor.mjs", + "test/multiple-subtitles-vendor.test.js", + "packages/artplayer-plugin-multiple-subtitles/THIRD_PARTY_NOTICES" ] }, { diff --git a/test/helpers/multiple-subtitles.js b/test/helpers/multiple-subtitles.js new file mode 100644 index 000000000..fcb247b7f --- /dev/null +++ b/test/helpers/multiple-subtitles.js @@ -0,0 +1,83 @@ +import fs from 'node:fs' +import process from 'node:process' +import vm from 'node:vm' +import { transform } from 'esbuild' +import { verifyMultipleSubtitlesContract } from '../../refactor/scripts/multiple-subtitles-contract.mjs' +import { readMember } from '../../refactor/scripts/releases.mjs' +import { compilePackage } from './load.js' + +export const subtitleVtt = text => `WEBVTT\n\n00:00.000 --> 00:02.000\n${text}\n` + +export async function multipleSubtitlesCandidate() { + return { name: 'candidate', version: 'candidate', code: process.env.ARTPLAYER_MULTIPLE_SUBTITLES_ARTIFACT ? fs.readFileSync(process.env.ARTPLAYER_MULTIPLE_SUBTITLES_ARTIFACT, 'utf8') : await compilePackage('artplayer-plugin-multiple-subtitles', 'umd') } +} + +export async function multipleSubtitlesHistorical() { + const { baseline, archives, sources } = await verifyMultipleSubtitlesContract() + const name = 'artplayer-plugin-multiple-subtitles' + const implementations = [] + for (const release of [baseline.release, ...baseline.previous]) { + for (const field of ['main', 'legacy']) + implementations.push({ name: `published-${release.version}-${field}`, version: release.version, code: readMember(archives.get(release.version), `package/${release.manifest[field].replace(/^\.\//, '')}`).toString() }) + } + const source = sources.get(`packages/${name}/src/parser.js`) + + sources.get(`packages/${name}/src/index.js`).replace(/^import .* from ['"].\/parser['"];?\s*$/m, '') + implementations.push({ name: 'frozen-workspace-source', version: 'workspace', code: (await transform(source, { format: 'cjs', target: 'es2020' })).code }) + for (const suffix of ['js', 'legacy.js']) + implementations.push({ name: `frozen-workspace-${suffix}`, version: 'workspace', code: sources.get(`packages/${name}/dist/${name}.${suffix}`) }) + return implementations +} + +export function multipleSubtitlesEnvironment(implementation, { script = false, responses = {} } = {}) { + const requests = [] + const blobs = new Map() + const revoked = [] + const initialized = [] + const converted = [] + const module = { exports: {} } + const utils = { + getExt: url => url.split('.').pop(), + unescape: text => text.replaceAll('<', '<').replaceAll('>', '>').replaceAll('&', '&'), + srtToVtt(text) { + converted.push(['srt', text]) + return subtitleVtt('SRT') + }, + assToVtt(text) { + converted.push(['ass', text]) + return subtitleVtt('ASS') + }, + } + const art = { + constructor: { utils }, + option: { subtitle: { escape: true, style: { color: 'red' } } }, + subtitle: { init(option) { initialized.push(option) } }, + } + const context = { + Blob, + TextDecoder, + console: { log() {}, warn() {}, error() {} }, + URL: { + createObjectURL(blob) { + const url = `blob:subtitle-${blobs.size + 1}` + blobs.set(url, blob) + return url + }, + revokeObjectURL(url) { revoked.push(url) }, + }, + fetch: async (url) => { + requests.push(url) + const bytes = new TextEncoder().encode(responses[url] ?? subtitleVtt(url)) + return { ok: true, arrayBuffer: async () => bytes.buffer } + }, + } + context.window = context + if (!script) { + context.module = module + context.exports = module.exports + } + vm.runInNewContext(implementation.code, context, { timeout: 5000 }) + const exported = script ? context.artplayerPluginMultipleSubtitles : module.exports + const factory = exported?.default || exported + const latestText = async () => blobs.get(initialized.at(-1).url).text() + return { factory, exported, art, utils, requests, blobs, revoked, initialized, converted, latestText } +} diff --git a/test/multiple-subtitles-vendor.test.js b/test/multiple-subtitles-vendor.test.js new file mode 100644 index 000000000..b1be0cb44 --- /dev/null +++ b/test/multiple-subtitles-vendor.test.js @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +// eslint-disable-next-line test/no-import-node-test -- Vendor parity uses the repository Node runner. +import test from 'node:test' +import vm from 'node:vm' +import { transformSync } from 'esbuild' +import { checkMultipleSubtitlesVendor } from '../refactor/scripts/multiple-subtitles-vendor.mjs' + +test('Multiple-subtitles vendor retains pinned executable content and complete standalone distribution notices', () => { + const result = checkMultipleSubtitlesVendor() + const notices = fs.readFileSync('packages/artplayer-plugin-multiple-subtitles/THIRD_PARTY_NOTICES', 'utf8').trim() + const block = notices.split(/\r?\n/).map(line => line.trimEnd() ? ` * ${line.trimEnd()}` : ' *').join('\n') + for (const suffix of ['js', 'legacy.js', 'mjs']) { + const built = fs.readFileSync(`packages/artplayer-plugin-multiple-subtitles/dist/artplayer-plugin-multiple-subtitles.${suffix}`, 'utf8').replaceAll('\r\n', '\n') + assert(built.includes(block), `Missing complete notice in ${suffix}`) + assert(built.startsWith('/*!')) + } + assert.equal(result.provenance.revision, '380cfcce34ba8b472d3a31474874eb72a0e5f460') +}) + +test('Multiple-subtitles vendor parser and serializer match the pinned upstream on metadata and malformed inputs', () => { + const upstream = { exports: {}, Date: { now: () => 123 } } + vm.runInNewContext(fs.readFileSync('refactor/baselines/multiple-subtitles-vendor/parser.txt', 'utf8'), upstream) + const local = { exports: {}, Date: upstream.Date } + local.module = { exports: local.exports } + vm.runInNewContext(transformSync(fs.readFileSync('packages/artplayer-plugin-multiple-subtitles/src/parser.js', 'utf8'), { format: 'cjs' }).code, local) + for (const input of [ + '', + 'WEBVTT\n\n0\n00:00.000 --> 00:01.000\nhello & <world>\n', + '\uFEFFWEBVTT\r\n\r\nNOTE ignored\r\n\r\n00:01.000 --> 00:04.000 align:start\r\n日本語\r\n', + 'WEBVTT\n\nSTYLE\n::cue {color: red}\n\n00:01.000 --> 00:03.000\nB\n\n00:00.000 --> 00:04.000\nA\n', + 'WEBVTT\n\nbad --> timing\ntext\n', + ]) { + const parse = exports => new exports.WebVTTParser().parse(input, 'metadata') + const expected = parse(upstream.exports) + const actual = parse(local.module.exports) + assert.deepEqual(JSON.parse(JSON.stringify(actual)), JSON.parse(JSON.stringify(expected))) + const serialize = (exports, tree) => new exports.WebVTTSerializer().serialize(tree.cues, tree.styles) + assert.equal(serialize(local.module.exports, actual), serialize(upstream.exports, expected)) + } +}) diff --git a/test/multiple-subtitles.test.js b/test/multiple-subtitles.test.js new file mode 100644 index 000000000..a3f223e00 --- /dev/null +++ b/test/multiple-subtitles.test.js @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict' +import process from 'node:process' +// eslint-disable-next-line test/no-import-node-test -- Historical contracts use the repository Node runner. +import test from 'node:test' +import { multipleSubtitlesCandidate, multipleSubtitlesEnvironment, multipleSubtitlesHistorical, subtitleVtt } from './helpers/multiple-subtitles.js' + +const implementations = process.env.ARTPLAYER_MULTIPLE_SUBTITLES_CANDIDATE === '1' || process.env.ARTPLAYER_MULTIPLE_SUBTITLES_ARTIFACT + ? [await multipleSubtitlesCandidate()] + : await multipleSubtitlesHistorical() +const plain = value => JSON.parse(JSON.stringify(value)) + +for (const implementation of implementations) { + const create = options => multipleSubtitlesEnvironment(implementation, options) + test(`Multiple-subtitles ${implementation.name}: required factory input and async named methods remain explicit`, async () => { + const env = create() + assert.throws(() => env.factory(), { name: 'TypeError' }) + const register = env.factory({}) + assert.equal(typeof register, 'function') + const pending = register(env.art) + assert.equal(typeof pending.then, 'function') + assert.equal(pending.name, undefined) + assert.equal(env.initialized.length, 0) + const result = await pending + assert.deepEqual(Object.keys(result), ['name', 'tracks', 'reset']) + assert.equal(result.name, 'multipleSubtitles') + assert.equal(result.tracks(), undefined) + assert.equal(result.reset(), undefined) + assert.equal(await env.latestText(), 'WEBVTT\n\n') + }) + + test(`Multiple-subtitles ${implementation.name}: all tracks load concurrently and retain historical merge topology`, async () => { + const env = create({ responses: { 'en.vtt': subtitleVtt('English'), 'jp.vtt': subtitleVtt('Japanese') } }) + const pending = env.factory({ subtitles: [{ url: 'en.vtt', name: 'en' }, { url: 'jp.vtt', name: 'jp' }] })(env.art) + assert.deepEqual(env.requests, ['en.vtt', 'jp.vtt']) + await pending + const text = env.utils.unescape(await env.latestText()) + assert(text.includes('
English
')) + assert(text.includes('
Japanese
')) + assert.equal(text.match(/-->/g).length, implementation.version === '1.0.0' ? 1 : 2) + assert(text.indexOf('art-subtitle-en') < text.indexOf('art-subtitle-jp')) + }) + + test(`Multiple-subtitles ${implementation.name}: tracks select named entries, reorder, clear and reset without another fetch`, async () => { + const env = create({ responses: { 'en.vtt': subtitleVtt('English'), 'jp.vtt': subtitleVtt('Japanese') } }) + const result = await env.factory({ subtitles: [{ url: 'en.vtt', name: 'en' }, { url: 'jp.vtt', name: 'jp' }] })(env.art) + result.tracks(['jp']) + assert(!env.utils.unescape(await env.latestText()).includes('art-subtitle-en')) + result.tracks(['jp', 'en']) + const reversed = env.utils.unescape(await env.latestText()) + assert(reversed.indexOf('art-subtitle-jp') < reversed.indexOf('art-subtitle-en')) + result.tracks([]) + assert.equal(await env.latestText(), 'WEBVTT\n\n') + result.reset() + const reset = env.utils.unescape(await env.latestText()) + assert(reset.indexOf('art-subtitle-en') < reset.indexOf('art-subtitle-jp')) + assert.equal(reset.match(/
{ + const env = create() + const result = await env.factory({ subtitles: [] })(env.art) + assert.equal(env.art.option.subtitle.escape, false) + assert.equal(env.initialized[0].onVttLoad, env.utils.unescape) + assert.equal(env.initialized[0].style, env.art.option.subtitle.style) + assert.equal(env.initialized[0].type, 'vtt') + assert.deepEqual(env.revoked, ['']) + env.art.option.subtitle.encoding = 'utf-16le' + result.reset() + assert.equal(env.initialized[1].encoding, 'utf-16le') + assert.deepEqual(env.revoked, ['', 'blob:subtitle-1']) + assert.equal(env.blobs.get('blob:subtitle-2').type, 'text/vtt') + }) + + test(`Multiple-subtitles ${implementation.name}: type selection dispatches existing core converters and ignores onParser`, async () => { + let parsed = 0 + const env = create({ responses: { 'a.srt': 'source srt', 'b.ass': 'source ass', 'c.bin': subtitleVtt('Override') } }) + const onParser = () => { + parsed++ + return {} + } + await env.factory({ subtitles: [{ url: 'a.srt', name: 'srt', onParser }, { url: 'b.ass', name: 'ass' }, { url: 'c.bin', name: 'override', type: 'vtt' }] })(env.art) + assert.deepEqual(plain(env.converted), [['srt', 'source srt'], ['ass', 'source ass']]) + const text = env.utils.unescape(await env.latestText()) + for (const value of ['SRT', 'ASS', 'Override']) + assert(text.includes(value)) + assert.equal(parsed, 0) + }) +}