[simple-scan] Improve algorithm that picks JPEG or zlib compression for PDF files.



commit e147dfe4092f92480774c485f210351848f41d92
Author: Robert Ancell <robert ancell canonical com>
Date:   Thu Apr 27 22:59:31 2017 +1200

    Improve algorithm that picks JPEG or zlib compression for PDF files.
    
    Compress with JPEG first - it is more likely to be used.
    Limit zlib compression to the size of the JPEG, this means we don't spend time
    doing zlib work to throw it away when it's too big anyway.

 src/book.vala |   38 ++++++++++++++++----------------------
 1 files changed, 16 insertions(+), 22 deletions(-)
---
diff --git a/src/book.vala b/src/book.vala
index a843981..db7acc9 100644
--- a/src/book.vala
+++ b/src/book.vala
@@ -165,10 +165,10 @@ public class Book
         }
     }
 
-    private uint8[]? compress_zlib (uint8[] data)
+    private uint8[]? compress_zlib (uint8[] data, uint max_size)
     {
         var stream = ZLib.DeflateStream (ZLib.Level.BEST_COMPRESSION);
-        var out_data = new uint8[data.length];
+        var out_data = new uint8[max_size];
 
         stream.next_in = data;
         stream.next_out = out_data;
@@ -181,7 +181,7 @@ public class Book
         if (stream.avail_in > 0)
             return null;
 
-        var n_written = data.length - stream.avail_out;
+        var n_written = out_data.length - stream.avail_out;
         out_data.resize ((int) n_written);
 
         return out_data;
@@ -439,26 +439,20 @@ public class Book
                 }
             }
 
-            /* Compress data */
-            var compressed_data = compress_zlib (data);
-            if (compressed_data != null)
+            /* Compress data and use zlib compression if it is smaller than JPEG.
+             * zlib compression is slower in the worst case, so do JPEG first
+             * and stop zlib if it exceeds the JPEG size */
+            var jpeg_data = compress_jpeg (image, quality, page.dpi);
+            var zlib_data = compress_zlib (data, jpeg_data.length);
+            if (zlib_data != null)
             {
-                /* Try if JPEG compression is better */
-                if (depth > 1)
-                {
-                    var jpeg_data = compress_jpeg (image, quality, page.dpi);
-                    if (jpeg_data.length < compressed_data.length)
-                    {
-                        filter = "DCTDecode";
-                        data = jpeg_data;
-                    }
-                }
-
-                if (filter == null)
-                {
-                    filter = "FlateDecode";
-                    data = compressed_data;
-                }
+                filter = "FlateDecode";
+                data = zlib_data;
+            }
+            else
+            {
+                filter = "DCTDecode";
+                data = jpeg_data;
             }
 
             /* Page */


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]