Skip to content

fix(bbb-web): Improve SVG Dimension Calculation Speed - #24106

Merged
antobinary merged 10 commits into
bigbluebutton:v3.0.x-releasefrom
paultrudel:improve-img-dim-calc
Oct 21, 2025
Merged

antobinary merged 10 commits into
bigbluebutton:v3.0.x-releasefrom
paultrudel:improve-img-dim-calc

Conversation

@paultrudel

Copy link
Copy Markdown
Collaborator

What does this PR do?

Implements a new method for determining SVG dimensions by probing the content of the SVG for dimension properties. This approach avoids the OOM issue caused by the previous method from reading the entire SVG content into memory and is faster than the current method of initializing an external service to determine the dimensions of SVGs. The external service implementation for determining SVG dimensions has been kept as a fallback in cases where the probe cannot determine the SVG dimensions.

Motivation

A new approach to determining SVG dimensions was implemented to avoid OOM issues causes by the previous implementation. The downside of this approach is that it can be quite slow which has led to a degradation of user experience for loading cached presentations. The approach introduced in this PR should avoid both of these issues.

How to test

  1. Create a meeting.
  2. Upload and cache a large presentation.
  3. Create a new meeting and load the previous presentation from the cache.

Do this before the changes in this PR and then after and track the time it takes for the presentation to load.

@paultrudel paultrudel changed the title Improve svg dim calc speed fix(bbb-web): Improve SVG Dimensions Calculation Speed Oct 16, 2025
@paultrudel paultrudel changed the title fix(bbb-web): Improve SVG Dimensions Calculation Speed fix(bbb-web): Improve SVG Dimension Calculation Speed Oct 16, 2025
@coderabbitai

coderabbitai Bot commented Oct 16, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes add safe SVG-dimension probing to MsgBuilder: introduces SvgDimensions, readSvgDims(...) (XML stream parsing with external-entity protections and a bounded input stream), parseCssLengthPx(...), roundPx, and helpers to extract/parse width/height from SVG files. generatePresentationPage now first tries readSvgDims(pageAbsoluteSvgPath) and, if dims are missing or zero, falls back to imageResolutionService.identifyImageResolution(...). Logging and IO/XML imports were added. Separately, ImageSlidesGenerationService.generateSlides no longer calls the per-page notifier.sendConversionUpdateMessage(...) or the post-processing notifier.sendConversionCompletedMessage(...). No public APIs were changed.

Sequence Diagram(s)

sequenceDiagram
    participant GP as generatePresentationPage
    participant FS as Filesystem
    participant SVG as readSvgDims (XML parser)
    participant IRS as imageResolutionService

    rect rgba(135,206,250,0.12)
    GP->>FS: resolve pageAbsoluteSvgPath
    GP->>SVG: readSvgDims(path)
    note right of SVG: open bounded stream\nXMLInputFactory (no external entities)
    SVG-->>GP: SvgDimensions or none/zero
    end

    alt SvgDimensions found (non-zero)
        GP->>GP: use SvgDimensions.width/height
    else fallback or zero
        GP->>IRS: identifyImageResolution(path)
        IRS-->>GP: resolution (width,height)
        GP->>GP: use IRS width/height (if non-zero)
    end
Loading
sequenceDiagram
    participant G_old as generateSlides (old)
    participant P as PageProcessor
    participant N as notifier

    rect rgba(144,238,144,0.12)
    G_old->>P: process each page
    P->>N: sendConversionUpdateMessage(page, pres, page)
    end
    rect rgba(255,228,225,0.12)
    G_old->>N: sendConversionCompletedMessage(pres)
    end
Loading
sequenceDiagram
    participant G_new as generateSlides (new)
    participant P as PageProcessor

    rect rgba(224,255,255,0.12)
    G_new->>P: process each page
    end
    note right of G_new: per-page and completion notifier calls removed
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "fix(bbb-web): Improve SVG Dimension Calculation Speed" is directly related to the main changes in this pull request. The raw_summary confirms that the primary modification is to MsgBuilder.scala, which implements SVG dimension probing as a faster alternative to the existing approach, with the external service as a fallback. The PR objectives explicitly state this is about improving SVG dimension calculation speed to enhance user experience when loading cached presentations. The title is concise, specific, and accurately reflects the core intent of the changeset without being vague or misleading.
Description Check ✅ Passed The pull request description is clearly related to the changeset. It explains that a new probe-based method for SVG dimension extraction has been implemented to avoid out-of-memory issues and improve performance, with the external service retained as a fallback—which matches exactly with the changes documented in the raw_summary showing the two-step approach in MsgBuilder.scala. The description provides meaningful context about what the change does, why it was necessary, and how to test it. The content is specific and directly addresses the implementation rather than being generic or off-topic.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@antobinary antobinary added this to the Release 3.0 milestone Oct 16, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (2)

110-114: Remove commented-out code.

The commented-out code should be removed before merging to production. Version control preserves the history if needed.

Apply this diff:

-    //    val imageResolution = imageResolutionService.identifyImageResolution(pageAbsoluteSvgPath)
-    //    if (imageResolution.getWidth != 0 && imageResolution.getHeight != 0) {
-    //      width = imageResolution.getWidth
-    //      height = imageResolution.getHeight
-    //    }
-
     val dims = readSvgDims(pageAbsoluteSvgPath)

512-532: LGTM with optional simplification.

The BoundedInputStream implementation correctly enforces byte read limits, providing essential protection against malicious large files that could cause OOM.

Optional refinement: Line 526's calculation could be simplified for clarity:

     override def read(b: Array[Byte], off: Int, len: Int): Int = {
       if (remaining <= 0) -1
       else {
-        val want = Math.min(len.toLong, Math.max(0L, Math.min(Int.MaxValue.toLong, remaining))).toInt
+        val want = Math.min(len, Math.min(Int.MaxValue, remaining.toInt))
         val r = super.read(b, off, want)
         if (r > 0) remaining -= r
         r
       }
     }

Note: The current implementation is correct; this simplification works when remaining fits in an Int, which should always be true given typical file sizes.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cd8cecf and f3b125e.

📒 Files selected for processing (1)
  • bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (4 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (1)
bigbluebutton-html5/imports/ui/components/whiteboard/container.jsx (1)
  • width (455-455)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-package (bbb-web)
🔇 Additional comments (4)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (4)

116-127: LGTM! Solid fallback strategy.

The two-tier approach (probe-based dimension extraction with fallback to external service) is well-implemented and aligns with the PR objectives to improve performance while maintaining reliability.


450-450: LGTM!

The private case class appropriately encapsulates SVG dimensions.


458-463: Excellent XXE protections!

The XML factory configuration properly disables DTD processing and external entities, preventing XML External Entity (XXE) injection attacks. This is a critical security safeguard when parsing untrusted SVG content.


489-510: LGTM! CSS unit conversions are correct.

The method properly handles CSS length units with correct conversion factors for 96 DPI standard:

  • Absolute units (px, pt, pc, in, cm, mm, q) are correctly converted
  • Invalid inputs (null, empty, percentages, unknown units) are safely rejected
  • Regex pattern correctly parses numeric values with optional signs and decimals

@paultrudel
paultrudel marked this pull request as draft October 16, 2025 19:37
@paultrudel
paultrudel marked this pull request as ready for review October 17, 2025 22:26

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (1)

458-461: Consider logging failures of optional XML properties.

While using Try() to set optional XML properties is acceptable, consider logging any failures to aid debugging of XML parsing issues.

       val f = XMLInputFactory.newFactory()
       f.setProperty(XMLInputFactory.SUPPORT_DTD, java.lang.Boolean.FALSE)
-      Try(f.setProperty("javax.xml.stream.isSupportingExternalEntities", java.lang.Boolean.FALSE))
-      Try(f.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.FALSE))
-      Try(f.setProperty("javax.xml.stream.isNamespaceAware", java.lang.Boolean.TRUE))
-      Try(f.setXMLResolver((_, _, _, _) => null))
+      Try(f.setProperty("javax.xml.stream.isSupportingExternalEntities", java.lang.Boolean.FALSE))
+        .failed.foreach(e => logger.warn("Could not set XML property isSupportingExternalEntities: {}", e.getMessage))
+      Try(f.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.FALSE))
+        .failed.foreach(e => logger.warn("Could not set XML property isCoalescing: {}", e.getMessage))
+      Try(f.setProperty("javax.xml.stream.isNamespaceAware", java.lang.Boolean.TRUE))
+        .failed.foreach(e => logger.warn("Could not set XML property isNamespaceAware: {}", e.getMessage))
+      Try(f.setXMLResolver((_, _, _, _) => null))
+        .failed.foreach(e => logger.warn("Could not set XML resolver: {}", e.getMessage))
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f3b125e and 264ff33.

📒 Files selected for processing (2)
  • bbb-common-web/src/main/java/org/bigbluebutton/presentation/imp/ImageSlidesGenerationService.java (0 hunks)
  • bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (3 hunks)
💤 Files with no reviewable changes (1)
  • bbb-common-web/src/main/java/org/bigbluebutton/presentation/imp/ImageSlidesGenerationService.java
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-package (bbb-web)
🔇 Additional comments (6)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (6)

11-20: LGTM!

The new imports are necessary for the SVG dimension extraction functionality, and the logger initialization is appropriate.

Also applies to: 24-24


116-117: Verify rounding precision aligns with requirements.

As noted in a previous review, these values should be rounded to avoid excessive precision. The current implementation rounds to integers (scale=0) inside readSvgDims. Confirm whether integer precision is sufficient or if fractional pixels should be preserved.

Based on past review comments.


448-448: LGTM!

The SvgDimensions case class appropriately encapsulates width and height values.


450-491: Well-structured resource management with Using.Manager.

The use of Using.Manager properly addresses the resource leak concerns from previous reviews. The XML security settings appropriately disable DTD processing and external entities. The early returns are correctly handled by the .toOption.flatten pattern.

Based on past review comments.


516-522: LGTM!

The roundPx method correctly handles rounding with appropriate edge case handling for NaN, Infinity, and negative zero.


524-544: LGTM!

The BoundedInputStream implementation correctly limits the number of bytes read from the underlying stream, preventing excessive memory consumption.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (2)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (2)

503-503: Fix incorrect point-to-pixel conversion.

The conversion factor for points (pt) is incorrect and will cause miscalculations for SVG files using point units. One point equals 1/72 inch, so at 96 DPI, the conversion should be 96/72 ≈ 1.333 pixels per point.

Apply this diff:

         val px = unit0.toLowerCase match {
           case "" | "px" => 1.0
-          case "pt"      => 1.0
+          case "pt"      => 96.0 / 72.0
           case "pc"      => 16.0
           case "in"      => 96.0

508-508: Fix incorrect quarter-millimeter (q) conversion.

The conversion factor for quarter-millimeters (q) is incorrect. One q equals 0.25mm (or 1/4 mm), so the divisor should be 4.0, not 40.0. This will cause dimension miscalculations for SVG files using q units.

Apply this diff:

           case "cm"      => 96.0 / 2.54
           case "mm"      => 96.0 / 25.4
-          case "q"       => 96.0 / 25.4 / 40.0
+          case "q"       => 96.0 / 25.4 / 4.0
           case _         => Double.NaN
🧹 Nitpick comments (1)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (1)

112-125: Polish log messages for production.

The dimension extraction logic correctly implements the probe-then-fallback pattern. However, the log messages contain informal asterisks that should be replaced with standard professional logging.

Apply this diff:

     dims match {
       case Some(d) =>
-        logger.info("***** Dimensions found from probe *****")
+        logger.info("SVG dimensions extracted from probe: {}x{} for page {}", d.width, d.height, page)
         width = d.width
         height = d.height
       case None =>
-        logger.info("***** Falling back to image resolution service *****")
+        logger.info("Falling back to image resolution service for page {} at path: {}", page, pageAbsoluteSvgPath)
         val imageResolution = imageResolutionService.identifyImageResolution(pageAbsoluteSvgPath)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 264ff33 and 860ff52.

📒 Files selected for processing (1)
  • bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-package (bbb-web)
🔇 Additional comments (4)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (4)

11-24: LGTM!

The new imports and logger initialization are appropriate for the SVG dimension extraction functionality.


450-491: LGTM!

The resource management using Using.Manager is correct and addresses the previous concern about resource leaks. The security settings appropriately protect against XXE attacks, and the bounded input stream prevents OOM issues.


516-522: LGTM!

The rounding implementation correctly handles edge cases (NaN, Infinite) and uses appropriate rounding mode. The normalization of -0.0 to 0.0 is a good defensive practice.


524-544: LGTM!

The custom BoundedInputStream implementation correctly enforces byte limits on both read methods and properly tracks remaining bytes. The calculation at Line 538 appropriately handles the min/max logic to respect both buffer size and remaining byte constraints.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (5)

24-24: Prefer class-based logger name

Use the class to name the logger for consistency with SLF4J conventions and easier filtering.

-  private lazy val logger: Logger = LoggerFactory.getLogger("msg-builder")
+  private lazy val logger: Logger = LoggerFactory.getLogger(classOf[MsgBuilder.type])

127-141: Remove redundant Try around Using; keep one error boundary

The extra Try(...) wrapping Using(...).get is unnecessary; Using already returns a Try.

-    val content = Try {
-      val maxChars: Int = 1024 * 1024 // limit ~1 MB to avoid OOM
-      val pageAbsoluteTxtPath = presParentPath + "/textfiles/slide-" + page.toString + ".txt"
-      Using(Source.fromFile(pageAbsoluteTxtPath, StandardCharsets.UTF_8.name())) { source =>
-        val buffer = new StringBuilder
-        val iter = source.iter
-        var count = 0
-        while (iter.hasNext && count < maxChars) {
-          buffer.append(iter.next())
-          count += 1
-        }
-        buffer.toString()
-      }.get
-    }.getOrElse("")
+    val content = {
+      val maxChars: Int = 1024 * 1024 // limit ~1 MB to avoid OOM
+      val pageAbsoluteTxtPath = presParentPath + "/textfiles/slide-" + page.toString + ".txt"
+      Using(Source.fromFile(pageAbsoluteTxtPath, StandardCharsets.UTF_8.name())) { source =>
+        val buffer = new StringBuilder(maxChars)
+        val iter = source.iter
+        var count = 0
+        while (iter.hasNext && count < maxChars) {
+          buffer.append(iter.next())
+          count += 1
+        }
+        buffer.toString()
+      }.getOrElse("")
+    }

450-491: Avoid early return inside Using.Manager

Non-local returns work but are non-idiomatic and throw control exceptions; accumulate a result instead to ensure clean closure semantics.

-  private def readSvgDims(svgPath: String, maxBytes: Long = 10L * 1024 * 1024, scale: Int = 0): Option[SvgDimensions] = {
+  private def readSvgDims(svgPath: String, maxBytes: Long = 10L * 1024 * 1024, scale: Int = 0): Option[SvgDimensions] = {
     Using.Manager { use =>
       val in = use(Files.newInputStream(Paths.get(svgPath)))
       val bis = use(new BufferedInputStream(in))
       val bounded = use(new BoundedInputStream(bis, if (maxBytes <= 0) Long.MaxValue else maxBytes))
@@
-      while (reader.hasNext) {
-        reader.next() match {
-          case XMLStreamConstants.START_ELEMENT if reader.getLocalName.equalsIgnoreCase("svg") =>
-            val wRaw = Option(reader.getAttributeValue(null, "width"))
-            val hRaw = Option(reader.getAttributeValue(null, "height"))
-
-            val wPx = wRaw.flatMap(parseCssLengthPx)
-            val hPx = hRaw.flatMap(parseCssLengthPx)
-
-            (wPx, hPx) match {
-              case (Some(w), Some(h)) =>
-                val W = roundPx(w, scale)
-                val H = roundPx(h, scale)
-                return Some(SvgDimensions(W, H))
-              case _ =>
-                return None
-            }
-          case _ =>
-        }
-      }
-      None
+      var result: Option[SvgDimensions] = None
+      while (reader.hasNext && result.isEmpty) {
+        reader.next() match {
+          case XMLStreamConstants.START_ELEMENT if reader.getLocalName.equalsIgnoreCase("svg") =>
+            val wPx = Option(reader.getAttributeValue(null, "width")).flatMap(parseCssLengthPx)
+            val hPx = Option(reader.getAttributeValue(null, "height")).flatMap(parseCssLengthPx)
+            result = for {
+              w <- wPx
+              h <- hPx
+            } yield SvgDimensions(roundPx(w, scale), roundPx(h, scale))
+          case _ =>
+        }
+      }
+      result
     }.toOption.flatten
   }

524-544: Custom BoundedInputStream is solid; optional minor enhancements

Implementation correctly bounds reads for both overloads. Optionally override available() to reflect remaining bytes and short‑circuit some parsers; also consider overriding skip() to respect bounds.

   private final class BoundedInputStream(in: InputStream, max: Long) extends FilterInputStream(in) {
     private var remaining = max
@@
     }
+
+    override def available(): Int = {
+      val sup = super.available()
+      val rem = Math.min(remaining, Int.MaxValue.toLong).toInt
+      Math.min(sup, rem)
+    }
+
+    override def skip(n: Long): Long = {
+      if (remaining <= 0) 0L
+      else {
+        val toSkip = Math.min(n, remaining)
+        val skipped = super.skip(toSkip)
+        if (skipped > 0) remaining -= skipped
+        skipped
+      }
+    }
   }

112-125: Tune log level and add structured context (remove decorative strings)

The decorative asterisk patterns in lines 115 and 119 should be replaced with debug-level logs that include the file path and dimensions for better traceability:

     dims match {
       case Some(d) =>
-        logger.info("***** Dimensions found from probe *****")
+        logger.debug("SVG dimensions from probe for {}: {}x{}", pageAbsoluteSvgPath, java.lang.Double.valueOf(d.width), java.lang.Double.valueOf(d.height))
         width = d.width
         height = d.height
       case None =>
-        logger.info("***** Falling back to image resolution service *****")
+        logger.debug("Falling back to image resolution service for {}", pageAbsoluteSvgPath)
         val imageResolution = imageResolutionService.identifyImageResolution(pageAbsoluteSvgPath)

Note: Similar decorative logging patterns exist elsewhere in the codebase (e.g., other Scala and Java files) and may warrant a separate cleanup pass.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 860ff52 and ff51e06.

📒 Files selected for processing (1)
  • bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-package (bbb-web)
🔇 Additional comments (2)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (2)

493-514: CSS unit parsing looks correct; pt and q conversions fixed

Good coverage for px/pt/pc/in/cm/mm/q and case insensitivity; rejects percentages. LGTM.

Consider adding small unit tests for parseCssLengthPx to lock these conversions in (pt, pc, q, edge cases like ".5cm", "12."). I can draft them if helpful.


516-522: Rounding helper is robust

Handles NaN/Infinity and normalizes negative zero. LGTM.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (1)

112-125: Consider cleaning up log message formatting.

The probe-first, fallback-second approach is correct and well-structured. However, the log messages contain excessive asterisks that appear debug-like.

Consider this cleaner format:

     dims match {
       case Some(d) =>
-        logger.info("***** Dimensions found from probe *****")
+        logger.info("SVG dimensions extracted from probe for page {}: {}x{}", page, d.width, d.height)
         width = d.width
         height = d.height
       case None =>
-        logger.info("***** Falling back to image resolution service *****")
+        logger.info("Probe failed for page {}, falling back to image resolution service", page)
         val imageResolution = imageResolutionService.identifyImageResolution(pageAbsoluteSvgPath)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ff51e06 and 8e5ac95.

📒 Files selected for processing (1)
  • bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-18T20:47:01.429Z
Learnt from: gustavotrott
PR: bigbluebutton/bigbluebutton#24106
File: bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala:0-0
Timestamp: 2025-10-18T20:47:01.429Z
Learning: In bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala, the parseCssLengthPx function intentionally uses a conversion factor of 1.0 for "pt" units (instead of the CSS-standard 96.0/72.0) because pdftocairo sets units as "pt" when they actually appear to be "px". This deliberate deviation is preferred to underestimate rather than overestimate dimensions.

Applied to files:

  • bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-package (bbb-web)
🔇 Additional comments (7)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (7)

11-20: LGTM!

The new imports are appropriate for the SVG dimension probing functionality: Logger for structured logging, IO/NIO classes for stream handling, XML parsing infrastructure, and BigDecimal rounding mode for precision control.


24-24: LGTM!

Logger initialization follows best practices with lazy evaluation and a descriptive name.


448-448: LGTM!

Simple, appropriate case class for holding SVG dimensions.


450-491: Excellent resource management and security hardening.

The implementation correctly addresses previous concerns:

  • Using.Manager ensures all resources are properly closed even with early returns
  • XML security properties prevent XXE attacks (DTD disabled, external entities disabled, null resolver)
  • BoundedInputStream prevents OOM by limiting reads to 10MB
  • Stream parsing approach avoids loading entire file into memory

The XMLStreamReader wrapping pattern (lines 463-467) is unconventional but necessary to register it with Using.Manager, and it works correctly.


493-514: LGTM!

CSS length parsing correctly handles all standard units with appropriate conversions. The pt conversion factor of 1.0 is intentionally non-standard to work around pdftocairo's mislabeling of pixels as points. The q (quarter-millimeter) conversion is mathematically correct.

Based on learnings


516-522: LGTM!

Rounding implementation correctly handles edge cases (NaN, Infinite, -0.0) and uses standard HALF_UP rounding mode with configurable precision.


524-544: LGTM!

Custom BoundedInputStream implementation correctly limits byte reads to prevent OOM. Both read() methods properly enforce the limit and handle edge cases (long-to-int conversion, remaining byte tracking).

@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (3)

112-125: Tighten fallback observability; keep defaults explicit.

Log a warning when the fallback returns 0×0 so silent defaults don’t hide failures. Minimal diff:

       case None =>
         logger.info("Falling back to image resolution service")
 
         val imageResolution = imageResolutionService.identifyImageResolution(pageAbsoluteSvgPath)
         if (imageResolution.getWidth != 0 && imageResolution.getHeight != 0) {
           width = imageResolution.getWidth
           height = imageResolution.getHeight
         } else {
+          logger.warn("Image resolution service returned 0x0 for: {}", pageAbsoluteSvgPath)
         }

128-141: Simplify Using/Try nesting.

Avoid the outer Try; rely on Using’s Try directly.

-    val content = Try {
-      val maxChars: Int = 1024 * 1024 // limit ~1 MB to avoid OOM
-      val pageAbsoluteTxtPath = presParentPath + "/textfiles/slide-" + page.toString + ".txt"
-      Using(Source.fromFile(pageAbsoluteTxtPath, StandardCharsets.UTF_8.name())) { source =>
-        val buffer = new StringBuilder
-        val iter = source.iter
-        var count = 0
-        while (iter.hasNext && count < maxChars) {
-          buffer.append(iter.next())
-          count += 1
-        }
-        buffer.toString()
-      }.get
-    }.getOrElse("")
+    val content = {
+      val maxChars: Int = 1024 * 1024 // limit ~1 MB to avoid OOM
+      val pageAbsoluteTxtPath = presParentPath + "/textfiles/slide-" + page.toString + ".txt"
+      Using(Source.fromFile(pageAbsoluteTxtPath, StandardCharsets.UTF_8.name())) { source =>
+        val buffer = new StringBuilder
+        val iter = source.iter
+        var count = 0
+        while (iter.hasNext && count < maxChars) {
+          buffer.append(iter.next()); count += 1
+        }
+        buffer.toString()
+      }.getOrElse("")
+    }

451-492: Avoid early returns inside Using.Manager; let XML auto-detect encoding.

Non-local returns work but are non-idiomatic and complicate resource lifetimes. Also, forcing UTF‑8 may misread files with different XML prologs. Suggested refactor:

-      val reader = {
-        val r0 = f.createXMLStreamReader(bounded, StandardCharsets.UTF_8.name())
+      val reader = {
+        val r0 = f.createXMLStreamReader(bounded)
         use(new AutoCloseable { override def close(): Unit = r0.close() })
         r0
       }
 
-      while (reader.hasNext) {
+      var result: Option[SvgDimensions] = None
+      while (reader.hasNext && result.isEmpty) {
         reader.next() match {
           case XMLStreamConstants.START_ELEMENT if reader.getLocalName.equalsIgnoreCase("svg") =>
             val wRaw = Option(reader.getAttributeValue(null, "width"))
             val hRaw = Option(reader.getAttributeValue(null, "height"))
 
             val wPx = wRaw.flatMap(parseCssLengthPx)
             val hPx = hRaw.flatMap(parseCssLengthPx)
 
             (wPx, hPx) match {
               case (Some(w), Some(h)) =>
                 val W = roundPx(w, scale)
                 val H = roundPx(h, scale)
-                return Some(SvgDimensions(W, H))
+                result = Some(SvgDimensions(W, H))
               case _ =>
-                return None
+                result = None
             }
           case _ =>
         }
       }
-      None
+      result
     }.toOption.flatten

Optional: consider falling back to viewBox when width/height are absent to improve hit rate before calling the external service.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8e5ac95 and f39462b.

📒 Files selected for processing (1)
  • bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-18T20:47:01.429Z
Learnt from: gustavotrott
PR: bigbluebutton/bigbluebutton#24106
File: bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala:0-0
Timestamp: 2025-10-18T20:47:01.429Z
Learning: In bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala, the parseCssLengthPx function intentionally uses a conversion factor of 1.0 for "pt" units (instead of the CSS-standard 96.0/72.0) because pdftocairo sets units as "pt" when they actually appear to be "px". This deliberate deviation is preferred to underestimate rather than overestimate dimensions.

Applied to files:

  • bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-package (bbb-web)
🔇 Additional comments (4)
bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala (4)

11-20: Imports look good.

Required modules are precise; no unused or conflicting imports observed.


24-24: Logger initialization is fine.

Lazy logger with a stable name is acceptable here.


494-515: CSS length parsing is solid; keep pt→px at 1.0 here.

Regex is strict; unit handling is correct. The 1.0 factor for "pt" is intentional due to pdftocairo labeling. Looks good. Based on learnings.


517-523: Rounding helper LGTM.

Covers NaN/Inf and negative zero.

Comment on lines +525 to +545
private final class BoundedInputStream(in: InputStream, max: Long) extends FilterInputStream(in) {
private var remaining = max

override def read(): Int =
if (remaining <= 0) -1
else {
val r = super.read();
if (r >= 0) remaining -= 1;
r
}

override def read(b: Array[Byte], off: Int, len: Int): Int = {
if (remaining <= 0) -1
else {
val want = Math.min(len.toLong, Math.max(0L, Math.min(Int.MaxValue.toLong, remaining))).toInt
val r = super.read(b, off, want)
if (r > 0) remaining -= r
r
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Bound can be bypassed via InputStream.skip; override skip/available.

Without overriding skip, a consumer could skip past the limit without decrementing remaining, weakening the OOM guard. Add:

   override def read(b: Array[Byte], off: Int, len: Int): Int = {
     if (remaining <= 0) -1
     else {
       val want = Math.min(len.toLong, Math.max(0L, Math.min(Int.MaxValue.toLong, remaining))).toInt
       val r = super.read(b, off, want)
       if (r > 0) remaining -= r
       r
     }
   }
+
+  override def skip(n: Long): Long = {
+    if (remaining <= 0) 0L
+    else {
+      val want = Math.min(n, Math.max(0L, remaining))
+      val skipped = super.skip(want)
+      if (skipped > 0) remaining -= skipped
+      skipped
+    }
+  }
+
+  override def available(): Int = {
+    val a = super.available()
+    val rem = Math.min(Int.MaxValue.toLong, Math.max(0L, remaining)).toInt
+    Math.min(a, rem)
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private final class BoundedInputStream(in: InputStream, max: Long) extends FilterInputStream(in) {
private var remaining = max
override def read(): Int =
if (remaining <= 0) -1
else {
val r = super.read();
if (r >= 0) remaining -= 1;
r
}
override def read(b: Array[Byte], off: Int, len: Int): Int = {
if (remaining <= 0) -1
else {
val want = Math.min(len.toLong, Math.max(0L, Math.min(Int.MaxValue.toLong, remaining))).toInt
val r = super.read(b, off, want)
if (r > 0) remaining -= r
r
}
}
}
private final class BoundedInputStream(in: InputStream, max: Long) extends FilterInputStream(in) {
private var remaining = max
override def read(): Int =
if (remaining <= 0) -1
else {
val r = super.read();
if (r >= 0) remaining -= 1;
r
}
override def read(b: Array[Byte], off: Int, len: Int): Int = {
if (remaining <= 0) -1
else {
val want = Math.min(len.toLong, Math.max(0L, Math.min(Int.MaxValue.toLong, remaining))).toInt
val r = super.read(b, off, want)
if (r > 0) remaining -= r
r
}
}
override def skip(n: Long): Long = {
if (remaining <= 0) 0L
else {
val want = Math.min(n, Math.max(0L, remaining))
val skipped = super.skip(want)
if (skipped > 0) remaining -= skipped
skipped
}
}
override def available(): Int = {
val a = super.available()
val rem = Math.min(Int.MaxValue.toLong, Math.max(0L, remaining)).toInt
Math.min(a, rem)
}
}
🤖 Prompt for AI Agents
In bbb-common-web/src/main/scala/org/bigbluebutton/api2/MsgBuilder.scala around
lines 525 to 545, the BoundedInputStream currently allows callers to bypass the
byte limit by using InputStream.skip and does not reflect the remaining bound in
available(); override skip(long) to call super.skip(n) but cap n to remaining,
decrement remaining by the actual skipped amount, handle negative inputs and
return the skipped count, and override available() to return the lesser of
super.available() and remaining (cast to int safely) so callers cannot see or
consume more bytes than the bound.

@github-actions

Copy link
Copy Markdown

Automated tests Summary

✅ All the CI tests have passed!

@antobinary
antobinary merged commit 234e492 into bigbluebutton:v3.0.x-release Oct 21, 2025
imdt-claudiop added a commit to Tainan404/bigbluebutton that referenced this pull request Jul 16, 2026
…p identify-on-SVG fallback

bbb-web reads presentation slide dimensions from SVGs. PR bigbluebutton#24106 moved
dimension reading to an XML probe of the svg width/height attributes,
keeping ImageMagick "identify" as a fallback when the probe returned
None. That fallback is dead code: every BBB-generated slide SVG comes
from pdftocairo, which always writes concrete width/height attributes,
so the probe resolves them directly and the "identify" branch is never
reached for any real input. It only ran when the probe already failed,
and for a pdftocairo SVG the probe does not fail.

The fix makes the probe strictly more robust instead of leaning on that
unreachable branch: pdftocairo also always emits a viewBox
("min-x min-y width height"), so when width/height are absent or
unparseable we now derive dimensions from the viewBox before falling
back to the 1440x1080 defaults. This closes the real gap behind bigbluebutton#24110,
where a slide with unusable width/height would silently degrade to
defaults even though the viewBox carried the correct size.

Removing the "identify" call also drops a fragile secondary path. It is
version-sensitive (libcairo2 1.16.0 emits pt units; 1.17.8/1.18.0 makes
"identify" print errors), and in hardened deployments where the inkscape
delegate is blocked, identify-on-SVG returns exit 1. That is secondary
context, not the justification: the branch was already unreachable for
BBB's own SVGs regardless of the ImageMagick policy in effect (stock
Ubuntu ImageMagick-6 policy blocks PDF/PS/EPS/XPS coders but not SVG, so
identify does work on SVG there).

The now-unused ImageMagick service instance in MsgBuilder is removed; the
ImageResolutionService class is kept for its raster (PNG) callers. The
probe success path for real inputs is unchanged.

Adds ScalaTest coverage (MsgBuilderTest) for the probe and its helpers,
including the viewBox fallback, rejection of non-finite viewBox values,
and unresolvable inputs.

Closes bigbluebutton#24110

Co-authored-by: Tainan Felipe <[email protected]>
imdt-claudiop added a commit to Tainan404/bigbluebutton that referenced this pull request Jul 17, 2026
…p identify-on-SVG fallback

bbb-web reads presentation slide dimensions from SVGs. PR bigbluebutton#24106 moved
dimension reading to an XML probe of the svg width/height attributes,
keeping ImageMagick "identify" as a fallback when the probe returned
None. That fallback is dead code: every BBB-generated slide SVG comes
from pdftocairo, which always writes concrete width/height attributes,
so the probe resolves them directly and the "identify" branch is never
reached for any real input. It only ran when the probe already failed,
and for a pdftocairo SVG the probe does not fail.

The fix makes the probe strictly more robust instead of leaning on that
unreachable branch: pdftocairo also always emits a viewBox
("min-x min-y width height"), so when width/height are absent or
unparseable we now derive dimensions from the viewBox before falling
back to the 1440x1080 defaults. This closes the real gap behind bigbluebutton#24110,
where a slide with unusable width/height would silently degrade to
defaults even though the viewBox carried the correct size.

Removing the "identify" call also drops a fragile secondary path. It is
version-sensitive (libcairo2 1.16.0 emits pt units; 1.17.8/1.18.0 makes
"identify" print errors), and in hardened deployments where the inkscape
delegate is blocked, identify-on-SVG returns exit 1. That is secondary
context, not the justification: the branch was already unreachable for
BBB's own SVGs regardless of the ImageMagick policy in effect (stock
Ubuntu ImageMagick-6 policy blocks PDF/PS/EPS/XPS coders but not SVG, so
identify does work on SVG there).

The now-unused ImageMagick service instance in MsgBuilder is removed; the
ImageResolutionService class is kept for its raster (PNG) callers. The
probe success path for real inputs is unchanged.

Coverage is added as a Playwright e2e test (the standard BBB CI path):
a new case uploads a 16:9 (720x405) PDF and asserts the rendered slide
keeps that aspect ratio, rejecting a silent collapse to the 4:3
(1440x1080) default. Unit tests are not used because BBB CI does not run
sbt test for this module.

Closes bigbluebutton#24110

Co-authored-by: Tainan Felipe <[email protected]>
imdt-claudiop added a commit to Tainan404/bigbluebutton that referenced this pull request Jul 17, 2026
…p identify-on-SVG fallback

bbb-web reads presentation slide dimensions from SVGs. PR bigbluebutton#24106 moved
dimension reading to an XML probe of the svg width/height attributes,
keeping ImageMagick "identify" as a fallback when the probe returned
None. That fallback is dead code: every BBB-generated slide SVG comes
from pdftocairo, which always writes concrete width/height attributes,
so the probe resolves them directly and the "identify" branch is never
reached for any real input. It only ran when the probe already failed,
and for a pdftocairo SVG the probe does not fail.

The fix makes the probe strictly more robust instead of leaning on that
unreachable branch: pdftocairo also always emits a viewBox
("min-x min-y width height"), so when width/height are absent or
unparseable we now derive dimensions from the viewBox before falling
back to the 1440x1080 defaults. This closes the real gap behind bigbluebutton#24110,
where a slide with unusable width/height would silently degrade to
defaults even though the viewBox carried the correct size.

Removing the "identify" call also drops a fragile secondary path. It is
version-sensitive (libcairo2 1.16.0 emits pt units; 1.17.8/1.18.0 makes
"identify" print errors), and in hardened deployments where the inkscape
delegate is blocked, identify-on-SVG returns exit 1. That is secondary
context, not the justification: the branch was already unreachable for
BBB's own SVGs regardless of the ImageMagick policy in effect (stock
Ubuntu ImageMagick-6 policy blocks PDF/PS/EPS/XPS coders but not SVG, so
identify does work on SVG there).

The now-unused ImageMagick service instance in MsgBuilder is removed; the
ImageResolutionService class is kept for its raster (PNG) callers. The
probe success path for real inputs is unchanged.

Coverage is added as a Playwright e2e test (the standard BBB CI path):
a new case uploads a 16:9 (720x405) PDF and asserts the rendered slide
keeps that aspect ratio, rejecting a silent collapse to the 4:3
(1440x1080) default. Unit tests are not used because BBB CI does not run
sbt test for this module.

Closes bigbluebutton#24110

Co-authored-by: Tainan Felipe <[email protected]>
imdt-claudiop added a commit to Tainan404/bigbluebutton that referenced this pull request Jul 17, 2026
…p identify-on-SVG fallback

bbb-web reads presentation slide dimensions from SVGs. PR bigbluebutton#24106 moved
dimension reading to an XML probe of the svg width/height attributes,
keeping ImageMagick "identify" as a fallback when the probe returned
None. That fallback is dead code: every BBB-generated slide SVG comes
from pdftocairo, which always writes concrete width/height attributes,
so the probe resolves them directly and the "identify" branch is never
reached for any real input. It only ran when the probe already failed,
and for a pdftocairo SVG the probe does not fail.

The fix makes the probe strictly more robust instead of leaning on that
unreachable branch: pdftocairo also always emits a viewBox
("min-x min-y width height"), so when width/height are absent or
unparseable we now derive dimensions from the viewBox before falling
back to the 1440x1080 defaults. This closes the real gap behind bigbluebutton#24110,
where a slide with unusable width/height would silently degrade to
defaults even though the viewBox carried the correct size.

Removing the "identify" call also drops a fragile secondary path. It is
version-sensitive (libcairo2 1.16.0 emits pt units; 1.17.8/1.18.0 makes
"identify" print errors), and in hardened deployments where the inkscape
delegate is blocked, identify-on-SVG returns exit 1. That is secondary
context, not the justification: the branch was already unreachable for
BBB's own SVGs regardless of the ImageMagick policy in effect (stock
Ubuntu ImageMagick-6 policy blocks PDF/PS/EPS/XPS coders but not SVG, so
identify does work on SVG there).

The now-unused ImageMagick service instance in MsgBuilder is removed; the
ImageResolutionService class is kept for its raster (PNG) callers. The
probe success path for real inputs is unchanged.

Coverage is added as a Playwright e2e test (the standard BBB CI path):
a new case uploads a 16:9 (720x405) PDF and asserts the rendered slide
keeps that aspect ratio, rejecting a silent collapse to the 4:3
(1440x1080) default. Unit tests are not used because BBB CI does not run
sbt test for this module.

Closes bigbluebutton#24110

Co-authored-by: Tainan Felipe <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants