A platform for community discussion. Free, open, simple.
DEV: System specs for image optimization in composer (#36060)
Martin Brennan2942ef375d84
diff --git a/frontend/discourse/app/services/media-optimization-worker.js b/frontend/discourse/app/services/media-optimization-worker.jsindex d1e6c8a7ba0..2e75ab942aa 100644--- a/frontend/discourse/app/services/media-optimization-worker.js+++ b/frontend/discourse/app/services/media-optimization-worker.js@@ -52,7 +52,7 @@ export default class MediaOptimizationWorkerService extends Service {.composer_media_optimization_image_bytes_optimization_threshold) {this.logIfDebug(- `The file ${file.name} was less than the image optimization bytes threshold (${this.siteSettings.composer_media_optimization_image_bytes_optimization_threshold} bytes), skipping.`,+ `The file ${file.name} was less than the image optimization bytes threshold (${this.siteSettings.composer_media_optimization_image_bytes_optimization_threshold} bytes), skipping`,file);return Promise.resolve();@@ -82,6 +82,7 @@ export default class MediaOptimizationWorkerService extends Service {fileName: file.name,width: imageData.width,height: imageData.height,+ originalFileSize: file.size,settings: {resize_threshold:this.siteSettings@@ -126,7 +127,7 @@ export default class MediaOptimizationWorkerService extends Service {this.installPromise = new Promise((resolve, reject) => {this.afterInstalled = resolve;this.failedInstall = reject;- this.logIfDebug("Installing worker.");+ this.logIfDebug("Installing worker");this.startWorker();this.registerMessageHandler();this.worker.postMessage({@@ -141,7 +142,7 @@ export default class MediaOptimizationWorkerService extends Service {// we reject the install promise and clean up.setTimeout(() => {if (!this.workerInstalled) {- this.failInstall("Worker install timed out.");+ this.failInstall("Worker install timed out!");}}, WORKER_INSTALL_TIMEOUT_MS);@@ -182,7 +183,7 @@ export default class MediaOptimizationWorkerService extends Service {this.worker.onmessage = (workerMessage) => {switch (workerMessage.data.type) {case "file":- let optimizedFile = new File(+ const optimizedFile = new File([workerMessage.data.file],workerMessage.data.fileName,{@@ -190,7 +191,7 @@ export default class MediaOptimizationWorkerService extends Service {});this.logIfDebug(- `Finished optimization of ${optimizedFile.name} new size: ${optimizedFile.size}.`+ `Finished optimization of ${optimizedFile.name}, new size is ${optimizedFile.size} bytes`);this.promiseResolvers[workerMessage.data.fileId](optimizedFile);@@ -198,14 +199,14 @@ export default class MediaOptimizationWorkerService extends Service {this.workerDoneCount++;this.workerPendingCount--;if (this.workerDoneCount > 4 && this.workerPendingCount === 0) {- this.logIfDebug("Terminating worker to release memory in WASM.");+ this.logIfDebug("Terminating worker to release memory in WASM");this.stopWorker();}break;case "error":this.logIfDebug(- `Handling error message from image optimization for ${workerMessage.data.fileName}.`+ `Handling error message from image optimization for ${workerMessage.data.fileName}`);if (this.stopWorkerOnError) {@@ -216,7 +217,7 @@ export default class MediaOptimizationWorkerService extends Service {this.workerPendingCount--;break;case "installed":- this.logIfDebug("Worker installed.");+ this.logIfDebug("Worker installed");this.workerInstalled = true;this.afterInstalled();this.cleanupInstallPromises();@@ -228,7 +229,7 @@ export default class MediaOptimizationWorkerService extends Service {);break;default:- this.logIfDebug(`Sorry, we are out of ${workerMessage}.`);+ this.logIfDebug(`Sorry, we are out of ${workerMessage}`);}};}diff --git a/frontend/discourse/app/static/media-optimization-bundle.js b/frontend/discourse/app/static/media-optimization-bundle.jsindex 5358d8656e8..a9122093bac 100644--- a/frontend/discourse/app/static/media-optimization-bundle.js+++ b/frontend/discourse/app/static/media-optimization-bundle.js@@ -40,6 +40,7 @@ globalThis.optimize = async function (fileName,width,height,+ originalFileSize,settings) {// This variable assignemnt is re-written by webpack at build time.@@ -70,7 +71,9 @@ globalThis.optimize = async function (};const initialSize = imageData.byteLength;- logIfDebug(`Worker received imageData: ${initialSize}`);+ logIfDebug(+ `Received imageData ${initialSize} bytes (raw uncompressed pixels) from original file size of ${originalFileSize} bytes (compressed) for ${fileName}`+ );let maybeResized;@@ -100,14 +103,16 @@ globalThis.optimize = async function (maybeResized = resizeResult.data;width = targetDimensions.width;height = targetDimensions.height;- logIfDebug(`Worker post resizing file: ${maybeResized.byteLength}`);+ logIfDebug(+ `Post-resizing size for ${fileName} is ${maybeResized.byteLength} bytes (raw uncompressed pixels at ${width}x${height})`+ );} catch (error) {// eslint-disable-next-line no-console- console.error(`Resize failed`, error);+ console.error("Resize failed", error);maybeResized = imageData;}} else {- logIfDebug(`Skipped resize: ${width} < ${settings.resize_threshold}`);+ logIfDebug(`Skipped resize, ${width} < ${settings.resize_threshold}`);maybeResized = imageData;}@@ -118,8 +123,14 @@ globalThis.optimize = async function ();const finalSize = result.byteLength;- logIfDebug(`Worker post reencode file: ${finalSize}`);- logIfDebug(`Reduction: ${(initialSize / finalSize).toFixed(1)}x speedup`);+ logIfDebug(+ `Post-reencode size for ${fileName} is ${finalSize} bytes (compressed JPEG), original was ${originalFileSize} bytes`+ );+ const compressionFromOriginal = (originalFileSize / finalSize).toFixed(1);+ const compressionFromRaw = (initialSize / finalSize).toFixed(1);+ logIfDebug(+ `Compressed ${compressionFromOriginal}x vs original file, ${compressionFromRaw}x vs raw pixels for ${fileName}`+ );if (finalSize < 20000) {throw "Final size suspiciously small, discarding optimizations";diff --git a/public/javascripts/media-optimization-worker.js b/public/javascripts/media-optimization-worker.jsindex f4fc159106b..a4ed743ef55 100644--- a/public/javascripts/media-optimization-worker.js+++ b/public/javascripts/media-optimization-worker.js@@ -9,6 +9,7 @@ onmessage = async function (e) {e.data.fileName,e.data.width,e.data.height,+ e.data.originalFileSize,e.data.settings);postMessage(diff --git a/spec/system/composer_image_optimization_spec.rb b/spec/system/composer_image_optimization_spec.rbnew file mode 100644index 00000000000..66b82d0d9cd--- /dev/null+++ b/spec/system/composer_image_optimization_spec.rb@@ -0,0 +1,119 @@+# frozen_string_literal: true++describe "Composer image optimization for uploads using media-optimization-worker" do+ fab!(:current_user) { Fabricate(:user, refresh_auto_groups: true) }++ let(:composer) { PageObjects::Components::Composer.new }+ let(:topic) { PageObjects::Pages::Topic.new }++ before do+ sign_in(current_user)+ SiteSetting.composer_media_optimization_debug_mode = true+ SiteSetting.enable_upload_debug_mode = true++ # 1 byte to ensure all images are optimized in tests+ SiteSetting.composer_media_optimization_image_bytes_optimization_threshold = 1++ # Disable server-side optimizations+ SiteSetting.png_to_jpg_quality = 100+ end++ describe "jpeg images" do+ it "optimizes an uploaded jpeg image in the composer" do+ visit "/new-topic"+ expect(composer).to be_opened++ file = file_from_fixtures("huge.jpg", "images")+ attach_file("file-uploader", [file.path], make_visible: true)++ expect(composer).to have_no_in_progress_uploads+ expect(composer.preview).to have_css(".image-wrapper", count: 1)++ upload = Upload.find_by(original_filename: File.basename(file.path))++ # Original huge.jpg is 466_479 bytes+ expect(upload.filesize).to eq(22_302)+ end++ it "skips resizing the image if its width is < composer_media_optimization_image_resize_dimensions_threshold" do+ SiteSetting.composer_media_optimization_image_resize_dimensions_threshold = 100++ visit "/new-topic"+ expect(composer).to be_opened++ file = file_from_fixtures("logo.jpg", "images")+ attach_file("file-uploader", [file.path], make_visible: true)++ expect(composer).to have_no_in_progress_uploads+ expect(composer.preview).to have_css(".image-wrapper", count: 1)++ upload = Upload.find_by(original_filename: File.basename(file.path))++ # Original logo.jpg is 29_327 bytes, weirdly resizing this one causes it to increase in size+ expect(upload.filesize).to eq(143_862)++ # Re-upload without resizing+ SiteSetting.composer_media_optimization_image_resize_dimensions_threshold = 20_000++ visit "/new-topic"+ expect(composer).to be_opened++ file = file_from_fixtures("logo.jpg", "images")+ attach_file("file-uploader", [file.path], make_visible: true)++ expect(composer).to have_no_in_progress_uploads+ expect(composer.preview).to have_css(".image-wrapper", count: 1)++ upload = Upload.find_by(original_filename: File.basename(file.path))++ # Original logo.jpg is 29_327 bytes+ expect(upload.filesize).to eq(26_182)+ end+ end++ describe "png images" do+ it "optimizes an uploaded png image in the composer" do+ visit "/new-topic"+ expect(composer).to be_opened++ file = file_from_fixtures("large_and_unoptimized.png", "images")+ converted_file_path = file.path.gsub("unoptimized", "notransparent")++ # We do a conversion here to simulate a PNG with no transparency,+ # the fixture has transparency, and PNGs with transparency are not optimized.+ Discourse::Utils.execute_command(+ *["convert", file.path, "-background", "white", "-alpha", "remove", converted_file_path],+ timeout: 3,+ )++ attach_file("file-uploader", [converted_file_path], make_visible: true)++ expect(composer).to have_no_in_progress_uploads+ expect(composer.preview).to have_css(".image-wrapper", count: 1)++ upload =+ Upload.find_by(original_filename: File.basename(converted_file_path).gsub("png", "jpg"))++ # Original large_and_unoptimized PNG with no transparency is 312_889 bytes+ expect(upload.filesize).to eq(285_809)+ ensure+ FileUtils.rm(converted_file_path)+ end++ it "does not optimize a png with transparent pixels in the composer" do+ visit "/new-topic"+ expect(composer).to be_opened++ file = file_from_fixtures("large_and_unoptimized.png", "images")+ attach_file("file-uploader", [file.path], make_visible: true)++ expect(composer).to have_no_in_progress_uploads+ expect(composer.preview).to have_css(".image-wrapper", count: 1)++ upload = Upload.find_by(original_filename: File.basename(file.path))++ # Original large_and_unoptimized.png is 421_730 bytes+ expect(upload.filesize).to eq(421_730)+ end+ end+end