generateImages_browserless.js 18 KB

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