From 60d0111324fc8d8014784e0a2af36c0fc26f694c Mon Sep 17 00:00:00 2001
From: Damiano Galassi <damiog@gmail.com>
Date: Fri, 3 Nov 2017 07:32:09 +0100
Subject: [PATCH]  MacGui: fix a wrong usage of CFData API, CFDataCreateMutable
 creates a a CFData instance that can be filled up to the wanted capacity, but
 it doesn't set the CFData length to the capacity. Use CFDataSetLength to set
 the length. The original code doesn't work on 10.13.2 beta 1.

---
 macosx/HBCore.m | 38 +++++++++++++++++++++-----------------
 1 file changed, 21 insertions(+), 17 deletions(-)

diff --git a/macosx/HBCore.m b/macosx/HBCore.m
index acd4c187e..5e0cbb80d 100644
--- a/macosx/HBCore.m
+++ b/macosx/HBCore.m
@@ -342,9 +342,27 @@ typedef void (^HBCoreCleanupHandler)(void);
         // Create an CGImageRef and copy the libhb image into it.
         // The image data returned by hb_get_preview2 is 4 bytes per pixel, BGRA format.
         // Alpha is ignored.
-        CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaNone;
-        CFMutableDataRef imgData = CFDataCreateMutable(kCFAllocatorDefault, 3 * image->width * image->height);
+        CFMutableDataRef imgData = CFDataCreateMutable(kCFAllocatorDefault, 0);
+        CFDataSetLength(imgData, 3 * image->width * image->height);
+
+        UInt8 *src_line = image->data;
+        UInt8 *dst = CFDataGetMutableBytePtr(imgData);
+        for (int r = 0; r < image->height; r++)
+        {
+            UInt8 *src = src_line;
+            for (int c = 0; c < image->width; c++)
+            {
+                *dst++ = src[2];
+                *dst++ = src[1];
+                *dst++ = src[0];
+                src += 4;
+            }
+            src_line += image->plane[0].stride;
+        }
+
         CGDataProviderRef provider = CGDataProviderCreateWithCFData(imgData);
+
+        CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaNone;
         CGColorSpaceRef colorSpace = copyColorSpace(title.hb_title->color_prim,
                                                     title.hb_title->color_transfer,
                                                     title.hb_title->color_matrix);
@@ -360,25 +378,11 @@ typedef void (^HBCoreCleanupHandler)(void);
                             NULL,
                             NO,
                             kCGRenderingIntentDefault);
+
         CGColorSpaceRelease(colorSpace);
         CGDataProviderRelease(provider);
         CFRelease(imgData);
 
-        UInt8 *src_line = image->data;
-        UInt8 *dst = CFDataGetMutableBytePtr(imgData);
-        for (int r = 0; r < image->height; r++)
-        {
-            UInt8 *src = src_line;
-            for (int c = 0; c < image->width; c++)
-            {
-                *dst++ = src[2];
-                *dst++ = src[1];
-                *dst++ = src[0];
-                src += 4;
-            }
-            src_line += image->plane[0].stride;
-        }
-
         hb_image_close(&image);
     }
 
-- 
2.40.0