generateImages_browserless.mjs 19 KB

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