generateImages_browserless.mjs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import Blob from "cross-blob";
  2. import FS from "fs";
  3. import jsdom from "jsdom";
  4. //import headless_gl from "gl"; // this is now imported dynamically in a try catch, in case gl install fails, see #1160
  5. import OSMD from "../../build/opensheetmusicdisplay.min.js"; // window needs to be available before we can require OSMD
  6. /*
  7. Render each OSMD sample, grab the generated images, and
  8. dump them into a local directory as PNG or SVG files.
  9. inspired by Vexflow's generate_png_images and vexflow-tests.js
  10. This can be used to generate PNGs or SVGs from OSMD without a browser.
  11. It's also used with the visual regression test system (using PNGs) in
  12. `tools/visual_regression.sh`
  13. (see package.json, used with npm run generate:blessed and generate:current, then test:visual).
  14. Note: this script needs to "fake" quite a few browser elements, like window, document,
  15. and a Canvas HTMLElement (for PNG) or the DOM (for SVG) ,
  16. which otherwise are missing in pure nodejs, causing errors in OSMD.
  17. For PNG it needs the canvas package installed.
  18. There are also some hacks needed to set the container size (offsetWidth) correctly.
  19. Otherwise you'd need to run a headless browser, which is way slower,
  20. see the semi-obsolete generateDiffImagesPuppeteerLocalhost.js
  21. */
  22. function sleep (ms) {
  23. return new Promise((resolve) => {
  24. setTimeout(resolve, ms);
  25. });
  26. }
  27. // global variables
  28. // (without these being global, we'd have to pass many of these values to the generateSampleImage function)
  29. // eslint-disable-next-line prefer-const
  30. let [osmdBuildDir, sampleDir, imageDir, imageFormat, pageWidth, pageHeight, filterRegex, mode, debugSleepTimeString, skyBottomLinePreference] = process.argv.slice(2, 12);
  31. if (!osmdBuildDir || !sampleDir || !imageDir || (imageFormat !== "png" && imageFormat !== "svg")) {
  32. console.log("usage: " +
  33. // eslint-disable-next-line max-len
  34. "node test/Util/generateImages_browserless.mjs osmdBuildDir sampleDirectory imageDirectory svg|png [width|0] [height|0] [filterRegex|all|allSmall] [--debug|--osmdtesting] [debugSleepTime]");
  35. console.log(" (use pageWidth and pageHeight 0 to not divide the rendering into pages (endless page))");
  36. console.log(' (use "all" to skip filterRegex parameter. "allSmall" with --osmdtesting skips two huge OSMD samples that take forever to render)');
  37. console.log("example: node test/Util/generateImages_browserless.mjs ../../build ./test/data/ ./export png 210 297 allSmall --debug 5000");
  38. console.log("Error: need osmdBuildDir, sampleDir, imageDir and svg|png arguments. Exiting.");
  39. process.exit(1);
  40. }
  41. let pageFormat;
  42. if (!mode) {
  43. mode = "";
  44. }
  45. if (imageFormat !== "svg") {
  46. imageFormat = "png";
  47. }
  48. // let OSMD; // can only be required once window was simulated
  49. // eslint-disable-next-line @typescript-eslint/no-var-requires
  50. async function init () {
  51. console.log("[OSMD.generateImages] init");
  52. const osmdTestingMode = mode.includes("osmdtesting"); // can also be --debugosmdtesting
  53. const osmdTestingSingleMode = mode.includes("osmdtestingsingle");
  54. const DEBUG = mode.startsWith("--debug");
  55. // const debugSleepTime = Number.parseInt(process.env.GENERATE_DEBUG_SLEEP_TIME) || 0; // 5000 works for me [sschmidTU]
  56. if (DEBUG) {
  57. // console.log(' (note that --debug slows down the script by about 0.3s per file, through logging)')
  58. const debugSleepTimeMs = Number.parseInt(debugSleepTimeString, 10);
  59. if (debugSleepTimeMs > 0) {
  60. console.log("debug sleep time: " + debugSleepTimeString);
  61. await sleep(Number.parseInt(debugSleepTimeMs, 10));
  62. // [VSCode] apparently this is necessary for the debugger to attach itself in time before the program closes.
  63. // sometimes this is not enough, so you may have to try multiple times or increase the sleep timer. Unfortunately debugging nodejs isn't easy.
  64. }
  65. }
  66. debug("sampleDir: " + sampleDir, DEBUG);
  67. debug("imageDir: " + imageDir, DEBUG);
  68. debug("imageFormat: " + imageFormat, DEBUG);
  69. pageFormat = "Endless";
  70. pageWidth = Number.parseInt(pageWidth, 10);
  71. pageHeight = Number.parseInt(pageHeight, 10);
  72. const endlessPage = !(pageHeight > 0 && pageWidth > 0);
  73. if (!endlessPage) {
  74. pageFormat = `${pageWidth}x${pageHeight}`;
  75. }
  76. // ---- hacks to fake Browser elements OSMD and Vexflow need, like window, document, and a canvas HTMLElement ----
  77. // eslint-disable-next-line @typescript-eslint/no-var-requires
  78. const dom = new jsdom.JSDOM("<!DOCTYPE html></html>");
  79. // eslint-disable-next-line no-global-assign
  80. // window = dom.window;
  81. // eslint-disable-next-line no-global-assign
  82. // document = dom.window.document;
  83. // eslint-disable-next-line no-global-assign
  84. global.window = dom.window;
  85. // eslint-disable-next-line no-global-assign
  86. global.document = window.document;
  87. //window.console = console; // probably does nothing
  88. global.HTMLElement = window.HTMLElement;
  89. global.HTMLAnchorElement = window.HTMLAnchorElement;
  90. global.XMLHttpRequest = window.XMLHttpRequest;
  91. global.DOMParser = window.DOMParser;
  92. global.Node = window.Node;
  93. if (imageFormat === "png") {
  94. global.Canvas = window.Canvas;
  95. }
  96. // For WebGLSkyBottomLineCalculatorBackend: Try to import gl dynamically
  97. // this is so that the script doesn't fail if gl could not be installed,
  98. // which can happen in some linux setups where gcc-11 is installed, see #1160
  99. try {
  100. const { default: headless_gl } = await import("gl");
  101. const oldCreateElement = document.createElement.bind(document);
  102. document.createElement = function (tagName, options) {
  103. if (tagName.toLowerCase() === "canvas") {
  104. const canvas = oldCreateElement(tagName, options);
  105. const oldGetContext = canvas.getContext.bind(canvas);
  106. canvas.getContext = function (contextType, contextAttributes) {
  107. if (contextType.toLowerCase() === "webgl" || contextType.toLowerCase() === "experimental-webgl") {
  108. const gl = headless_gl(canvas.width, canvas.height, contextAttributes);
  109. gl.canvas = canvas;
  110. return gl;
  111. } else {
  112. return oldGetContext(contextType, contextAttributes);
  113. }
  114. };
  115. return canvas;
  116. } else {
  117. return oldCreateElement(tagName, options);
  118. }
  119. };
  120. } catch {
  121. if (skyBottomLinePreference === "--webgl") {
  122. console.log("WebGL image generation was requested but gl is not installed; using non-WebGL generation.");
  123. }
  124. }
  125. // fix Blob not found (to support external modules like is-blob)
  126. global.Blob = Blob;
  127. const div = document.createElement("div");
  128. div.id = "browserlessDiv";
  129. document.body.appendChild(div);
  130. // const canvas = document.createElement('canvas')
  131. // div.canvas = document.createElement('canvas')
  132. const zoom = 1.0;
  133. // width of the div / PNG generated
  134. let width = pageWidth * zoom;
  135. // TODO sometimes the width is way too small for the score, may need to adjust zoom.
  136. if (endlessPage) {
  137. width = 1440;
  138. }
  139. let height = pageHeight;
  140. if (endlessPage) {
  141. height = 32767;
  142. }
  143. div.width = width;
  144. div.height = height;
  145. // div.offsetWidth = width; // doesn't work, offsetWidth is always 0 from this. see below
  146. // div.clientWidth = width;
  147. // div.clientHeight = height;
  148. // div.scrollHeight = height;
  149. // div.scrollWidth = width;
  150. div.setAttribute("width", width);
  151. div.setAttribute("height", height);
  152. div.setAttribute("offsetWidth", width);
  153. // debug('div.offsetWidth: ' + div.offsetWidth, DEBUG) // 0 here, set correctly later
  154. // debug('div.height: ' + div.height, DEBUG)
  155. // hack: set offsetWidth reliably
  156. Object.defineProperties(window.HTMLElement.prototype, {
  157. offsetLeft: {
  158. get: function () { return parseFloat(window.getComputedStyle(this).marginTop) || 0; }
  159. },
  160. offsetTop: {
  161. get: function () { return parseFloat(window.getComputedStyle(this).marginTop) || 0; }
  162. },
  163. offsetHeight: {
  164. get: function () { return height; }
  165. },
  166. offsetWidth: {
  167. get: function () { return width; }
  168. }
  169. });
  170. debug("div.offsetWidth: " + div.offsetWidth, DEBUG);
  171. debug("div.height: " + div.height, DEBUG);
  172. // ---- end browser hacks (hopefully) ----
  173. // load globally
  174. // Create the image directory if it doesn't exist.
  175. FS.mkdirSync(imageDir, { recursive: true });
  176. const sampleDirFilenames = FS.readdirSync(sampleDir);
  177. let samplesToProcess = []; // samples we want to process/generate pngs of, excluding the filtered out files/filenames
  178. for (const sampleFilename of sampleDirFilenames) {
  179. if (osmdTestingMode && filterRegex === "allSmall") {
  180. if (sampleFilename.match("^(Actor)|(Gounod)")) { // TODO maybe filter by file size instead
  181. debug("filtering big file: " + sampleFilename, DEBUG);
  182. continue;
  183. }
  184. }
  185. // eslint-disable-next-line no-useless-escape
  186. if (sampleFilename.match("^.*(\.xml)|(\.musicxml)|(\.mxl)$")) {
  187. // console.log('found musicxml/mxl: ' + sampleFilename)
  188. samplesToProcess.push(sampleFilename);
  189. } else {
  190. debug("discarded file/directory: " + sampleFilename, DEBUG);
  191. }
  192. }
  193. // filter samples to process by regex if given
  194. if (filterRegex && filterRegex !== "" && filterRegex !== "all" && !(osmdTestingMode && filterRegex === "allSmall")) {
  195. debug("filtering samples for regex: " + filterRegex, DEBUG);
  196. samplesToProcess = samplesToProcess.filter((filename) => filename.match(filterRegex));
  197. debug(`found ${samplesToProcess.length} matches: `, DEBUG);
  198. for (let i = 0; i < samplesToProcess.length; i++) {
  199. debug(samplesToProcess[i], DEBUG);
  200. }
  201. }
  202. const backend = imageFormat === "png" ? "canvas" : "svg";
  203. const osmdInstance = new OSMD.OpenSheetMusicDisplay(div, {
  204. autoResize: false,
  205. backend: backend,
  206. pageBackgroundColor: "#FFFFFF",
  207. pageFormat: pageFormat
  208. // defaultFontFamily: 'Arial',
  209. // drawTitle: false
  210. });
  211. // for more options check OSMDOptions.ts
  212. // you can set finer-grained rendering/engraving settings in EngravingRules:
  213. // osmdInstance.EngravingRules.TitleTopDistance = 5.0 // 5.0 is default
  214. // (unless in osmdTestingMode, these will be reset with drawingParameters default)
  215. // osmdInstance.EngravingRules.PageTopMargin = 5.0 // 5 is default
  216. // osmdInstance.EngravingRules.PageBottomMargin = 5.0 // 5 is default. <5 can cut off scores that extend in the last staffline
  217. // note that for now the png and canvas will still have the height given in the script argument,
  218. // so even with a margin of 0 the image will be filled to the full height.
  219. // osmdInstance.EngravingRules.PageLeftMargin = 5.0 // 5 is default
  220. // osmdInstance.EngravingRules.PageRightMargin = 5.0 // 5 is default
  221. // osmdInstance.EngravingRules.MetronomeMarkXShift = -8; // -6 is default
  222. // osmdInstance.EngravingRules.DistanceBetweenVerticalSystemLines = 0.15; // 0.35 is default
  223. // for more options check EngravingRules.ts (though not all of these are meant and fully supported to be changed at will)
  224. if (DEBUG) {
  225. osmdInstance.setLogLevel("debug");
  226. // console.log(`osmd PageFormat: ${osmdInstance.EngravingRules.PageFormat.width}x${osmdInstance.EngravingRules.PageFormat.height}`)
  227. console.log(`osmd PageFormat idString: ${osmdInstance.EngravingRules.PageFormat.idString}`);
  228. console.log("PageHeight: " + osmdInstance.EngravingRules.PageHeight);
  229. } else {
  230. osmdInstance.setLogLevel("info"); // doesn't seem to work, log.debug still logs
  231. }
  232. debug("[OSMD.generateImages] starting loop over samples, saving images to " + imageDir, DEBUG);
  233. for (let i = 0; i < samplesToProcess.length; i++) {
  234. const sampleFilename = samplesToProcess[i];
  235. debug("sampleFilename: " + sampleFilename, DEBUG);
  236. await generateSampleImage(sampleFilename, sampleDir, osmdInstance, osmdTestingMode, {}, DEBUG);
  237. if (osmdTestingMode && !osmdTestingSingleMode && sampleFilename.startsWith("Beethoven") && sampleFilename.includes("Geliebte")) {
  238. // generate one more testing image with skyline and bottomline. (startsWith 'Beethoven' don't catch the function test)
  239. await generateSampleImage(sampleFilename, sampleDir, osmdInstance, osmdTestingMode, {skyBottomLine: true}, DEBUG);
  240. // generate one more testing image with GraphicalNote positions
  241. await generateSampleImage(sampleFilename, sampleDir, osmdInstance, osmdTestingMode, {boundingBoxes: "VexFlowGraphicalNote"}, DEBUG);
  242. }
  243. }
  244. console.log("[OSMD.generateImages] done, exiting.");
  245. }
  246. // eslint-disable-next-line
  247. // let maxRss = 0, maxRssFilename = '' // to log memory usage (debug)
  248. async function generateSampleImage (sampleFilename, directory, osmdInstance, osmdTestingMode,
  249. options = {}, DEBUG = false) {
  250. function makeSkyBottomLineOptions() {
  251. const preference = skyBottomLinePreference ?? "";
  252. if (preference === "--batch") {
  253. return {
  254. preferredSkyBottomLineBatchCalculatorBackend: 0, // plain
  255. skyBottomLineBatchCriteria: 0, // use batch algorithm only
  256. };
  257. } else if (preference === "--webgl") {
  258. return {
  259. preferredSkyBottomLineBatchCalculatorBackend: 1, // webgl
  260. skyBottomLineBatchCriteria: 0, // use batch algorithm only
  261. };
  262. } else {
  263. return {
  264. preferredSkyBottomLineBatchCalculatorBackend: 0, // plain
  265. skyBottomLineBatchCriteria: Infinity, // use non-batch algorithm only
  266. };
  267. }
  268. }
  269. const samplePath = directory + "/" + sampleFilename;
  270. let loadParameter = FS.readFileSync(samplePath);
  271. if (sampleFilename.endsWith(".mxl")) {
  272. loadParameter = await OSMD.MXLHelper.MXLtoXMLstring(loadParameter);
  273. } else {
  274. loadParameter = loadParameter.toString();
  275. }
  276. // console.log('loadParameter: ' + loadParameter)
  277. // console.log('typeof loadParameter: ' + typeof loadParameter)
  278. // set sample-specific options for OSMD visual regression testing
  279. let includeSkyBottomLine = false;
  280. let drawBoundingBoxString;
  281. if (osmdTestingMode) {
  282. const isFunctionTestAutobeam = sampleFilename.startsWith("OSMD_function_test_autobeam");
  283. const isFunctionTestAutoColoring = sampleFilename.startsWith("OSMD_function_test_auto-custom-coloring");
  284. const isFunctionTestSystemAndPageBreaks = sampleFilename.startsWith("OSMD_Function_Test_System_and_Page_Breaks");
  285. const isFunctionTestDrawingRange = sampleFilename.startsWith("OSMD_function_test_measuresToDraw_");
  286. const defaultOrCompactTightMode = sampleFilename.startsWith("OSMD_Function_Test_Container_height") ? "compacttight" : "default";
  287. const isTestFlatBeams = sampleFilename.startsWith("test_drum_tuplet_beams");
  288. const isTestEndClefStaffEntryBboxes = sampleFilename.startsWith("test_end_measure_clefs_staffentry_bbox");
  289. if (isTestEndClefStaffEntryBboxes) {
  290. drawBoundingBoxString = "VexFlowStaffEntry";
  291. } else {
  292. drawBoundingBoxString = options.boundingBoxes; // undefined is also a valid value: no bboxes
  293. }
  294. osmdInstance.setOptions({
  295. autoBeam: isFunctionTestAutobeam, // only set to true for function test autobeam
  296. coloringMode: isFunctionTestAutoColoring ? 2 : 0,
  297. // eslint-disable-next-line max-len
  298. coloringSetCustom: isFunctionTestAutoColoring ? ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"] : undefined,
  299. colorStemsLikeNoteheads: isFunctionTestAutoColoring,
  300. drawingParameters: defaultOrCompactTightMode, // note: default resets all EngravingRules. could be solved differently
  301. drawFromMeasureNumber: isFunctionTestDrawingRange ? 9 : 1,
  302. drawUpToMeasureNumber: isFunctionTestDrawingRange ? 12 : Number.MAX_SAFE_INTEGER,
  303. newSystemFromXML: isFunctionTestSystemAndPageBreaks,
  304. newPageFromXML: isFunctionTestSystemAndPageBreaks,
  305. pageBackgroundColor: "#FFFFFF", // reset by drawingparameters default
  306. pageFormat: pageFormat, // reset by drawingparameters default,
  307. ...makeSkyBottomLineOptions()
  308. });
  309. osmdInstance.EngravingRules.AlwaysSetPreferredSkyBottomLineBackendAutomatically = false; // this would override the command line options (--plain etc)
  310. includeSkyBottomLine = options.skyBottomLine ? options.skyBottomLine : false; // apparently es6 doesn't have ?? operator
  311. osmdInstance.drawSkyLine = includeSkyBottomLine; // if includeSkyBottomLine, draw skyline and bottomline, else not
  312. osmdInstance.drawBottomLine = includeSkyBottomLine;
  313. osmdInstance.setDrawBoundingBox(drawBoundingBoxString, false); // false: don't render (now). also (re-)set if undefined!
  314. if (isTestFlatBeams) {
  315. osmdInstance.EngravingRules.FlatBeams = true;
  316. // osmdInstance.EngravingRules.FlatBeamOffset = 30;
  317. osmdInstance.EngravingRules.FlatBeamOffset = 10;
  318. osmdInstance.EngravingRules.FlatBeamOffsetPerBeam = 10;
  319. } else {
  320. osmdInstance.EngravingRules.FlatBeams = false;
  321. }
  322. }
  323. try {
  324. await osmdInstance.load(loadParameter); // if using load.then() without await, memory will not be freed up between renders
  325. } catch (ex) {
  326. console.log("couldn't load sample " + sampleFilename + ", skipping. Error: \n" + ex);
  327. return;
  328. }
  329. debug("xml loaded", DEBUG);
  330. try {
  331. osmdInstance.render();
  332. // there were reports that await could help here, but render isn't a synchronous function, and it seems to work. see #932
  333. } catch (ex) {
  334. console.log("renderError: " + ex);
  335. }
  336. debug("rendered", DEBUG);
  337. const markupStrings = []; // svg
  338. const dataUrls = []; // png
  339. let canvasImage;
  340. for (let pageNumber = 1; pageNumber < Number.POSITIVE_INFINITY; pageNumber++) {
  341. if (imageFormat === "png") {
  342. canvasImage = document.getElementById("osmdCanvasVexFlowBackendCanvas" + pageNumber);
  343. if (!canvasImage) {
  344. break;
  345. }
  346. if (!canvasImage.toDataURL) {
  347. console.log(`error: could not get canvas image for page ${pageNumber} for file: ${sampleFilename}`);
  348. break;
  349. }
  350. dataUrls.push(canvasImage.toDataURL());
  351. } else if (imageFormat === "svg") {
  352. const svgElement = document.getElementById("osmdSvgPage" + pageNumber);
  353. if (!svgElement) {
  354. break;
  355. }
  356. // The important xmlns attribute is not serialized unless we set it here
  357. svgElement.setAttribute("xmlns", "http://www.w3.org/2000/svg");
  358. markupStrings.push(svgElement.outerHTML);
  359. }
  360. }
  361. for (let pageIndex = 0; pageIndex < Math.max(dataUrls.length, markupStrings.length); pageIndex++) {
  362. const pageNumberingString = `${pageIndex + 1}`;
  363. const skybottomlineString = includeSkyBottomLine ? "skybottomline_" : "";
  364. const graphicalNoteBboxesString = drawBoundingBoxString ? "bbox" + drawBoundingBoxString + "_" : "";
  365. // pageNumberingString = dataUrls.length > 0 ? pageNumberingString : '' // don't put '_1' at the end if only one page. though that may cause more work
  366. const pageFilename = `${imageDir}/${sampleFilename}_${skybottomlineString}${graphicalNoteBboxesString}${pageNumberingString}.${imageFormat}`;
  367. if (imageFormat === "png") {
  368. const dataUrl = dataUrls[pageIndex];
  369. if (!dataUrl || !dataUrl.split) {
  370. console.log(`error: could not get dataUrl (imageData) for page ${pageIndex + 1} of sample: ${sampleFilename}`);
  371. continue;
  372. }
  373. const imageData = dataUrl.split(";base64,").pop();
  374. const imageBuffer = Buffer.from(imageData, "base64");
  375. debug("got image data, saving to: " + pageFilename, DEBUG);
  376. FS.writeFileSync(pageFilename, imageBuffer, { encoding: "base64" });
  377. } else if (imageFormat === "svg") {
  378. const markup = markupStrings[pageIndex];
  379. if (!markup) {
  380. console.log(`error: could not get markup (SVG data) for page ${pageIndex + 1} of sample: ${sampleFilename}`);
  381. continue;
  382. }
  383. debug("got svg markup data, saving to: " + pageFilename, DEBUG);
  384. FS.writeFileSync(pageFilename, markup, { encoding: "utf-8" });
  385. }
  386. // debug: log memory usage
  387. // const usage = process.memoryUsage()
  388. // for (const entry of Object.entries(usage)) {
  389. // if (entry[0] === 'rss') {
  390. // if (entry[1] > maxRss) {
  391. // maxRss = entry[1]
  392. // maxRssFilename = pageFilename
  393. // }
  394. // }
  395. // console.log(entry[0] + ': ' + entry[1] / (1024 * 1024) + 'mb')
  396. // }
  397. // console.log('maxRss: ' + (maxRss / 1024 / 1024) + 'mb' + ' for ' + maxRssFilename)
  398. }
  399. // console.log('maxRss total: ' + (maxRss / 1024 / 1024) + 'mb' + ' for ' + maxRssFilename)
  400. // await sleep(5000)
  401. // }) // end read file
  402. }
  403. function debug (msg, debugEnabled) {
  404. if (debugEnabled) {
  405. console.log(msg);
  406. }
  407. }
  408. init();