-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScreenCapture.cs
More file actions
834 lines (715 loc) · 31.4 KB
/
ScreenCapture.cs
File metadata and controls
834 lines (715 loc) · 31.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using AmpUp.Core.Models;
namespace AmpUp;
/// <summary>
/// GDI-based screen capture with zone-based color sampling.
/// Captures a monitor region via StretchBlt (HALFTONE) into a cached downsampled bitmap
/// and samples dominant colors per zone. Runs on a background thread at up to 30fps.
/// DXGI Desktop Duplication can replace this layer later for frame-synced capture.
/// </summary>
public class ScreenCapture : IDisposable
{
private bool _disposed;
// Pixel stride for downsampled sampling (every Nth pixel — good balance of speed vs accuracy)
private const int SampleStride = 4;
// StretchBlt downsample factor — capture at 1/Nth of source resolution via GPU HALFTONE filter.
// HALFTONE box-filters on the way down, so sampling the result is more accurate than
// stride-sampling the full-res source. 2x is a safe default (~4x less CPU & memory).
private const int CaptureDownsample = 2;
// Cached downsampled bitmap reused across frames to eliminate per-frame allocations.
// Single-threaded instance (DreamSyncController owns a single capture instance).
private Bitmap? _cachedBmp;
private int _cachedSrcW, _cachedSrcH;
// Pixels darker than this (R+G+B sum) are ignored to prevent dark UI from washing out colors.
// Set high enough to filter gray/near-black pixels that dilute saturated colors (e.g. red → pink).
private const int DarkThreshold = 80; // ~27 per channel
// Black bar detection: a column/row is "black" if fewer than this % of pixels are non-dark
private const float BlackBarContentThreshold = 0.02f; // 2% — a mostly-black column
// Cache detected content bounds (recalculate every N frames since aspect ratio rarely changes)
private Rectangle _cachedContentBounds;
private int _contentBoundsFrameCounter;
private const int ContentBoundsRecalcInterval = 30; // ~1s at 30fps
// ── Public API ───────────────────────────────────────────────────────────
/// <summary>
/// Sample all zones from the specified monitor. Returns one averaged (R,G,B) per zone.
/// ZoneCount must be 4, 8, or 16. Returns null on capture failure.
/// </summary>
public (byte R, byte G, byte B)[]? CaptureZones(int monitorIndex, int zoneCount)
=> CaptureZones(monitorIndex, zoneCount, false);
/// <summary>
/// Sample all zones from the specified monitor, optionally cropping black bars.
/// When cropBlackBars is true, detects pillarbox/letterbox and only samples the content area.
/// </summary>
public (byte R, byte G, byte B)[]? CaptureZones(int monitorIndex, int zoneCount, bool cropBlackBars)
{
if (_disposed) return null;
var bounds = GetMonitorBounds(monitorIndex);
if (bounds.Width == 0 || bounds.Height == 0) return null;
try
{
var bmp = CaptureScreen(bounds);
if (bmp == null) return null;
if (cropBlackBars)
{
// Recalculate content bounds periodically (aspect ratio doesn't change often)
_contentBoundsFrameCounter++;
if (_contentBoundsFrameCounter >= ContentBoundsRecalcInterval ||
_cachedContentBounds.Width == 0 || _cachedContentBounds.Height == 0)
{
_cachedContentBounds = DetectContentBounds(bmp);
_contentBoundsFrameCounter = 0;
}
// Only use crop if it's meaningfully smaller than the full frame
// (at least 3% cropped from one side to avoid false positives on dark scenes)
int minCropPixels = bmp.Width / 30; // ~3% of width
bool hasMeaningfulCrop =
_cachedContentBounds.Left > minCropPixels ||
(bmp.Width - _cachedContentBounds.Right) > minCropPixels ||
_cachedContentBounds.Top > minCropPixels ||
(bmp.Height - _cachedContentBounds.Bottom) > minCropPixels;
if (hasMeaningfulCrop)
return SampleZones(bmp, zoneCount, _cachedContentBounds);
}
return SampleZones(bmp, zoneCount);
}
catch (Exception ex)
{
Logger.Log($"ScreenCapture.CaptureZones failed: {ex.Message}");
return null;
}
}
/// <summary>
/// Capture a 2D zone grid [row, col] from the screen.
/// Rows = vertical slices (e.g. 3 = top/mid/bottom), cols = horizontal zones (4/8/16).
/// ContentBounds defines the crop area; null = full screen.
/// </summary>
public (byte R, byte G, byte B)[,]? CaptureZoneGrid(int monitorIndex, int cols, int rows, ContentBounds? crop)
{
if (_disposed) return null;
var bounds = GetMonitorBounds(monitorIndex);
if (bounds.Width == 0 || bounds.Height == 0) return null;
try
{
var bmp = CaptureScreen(bounds);
if (bmp == null) return null;
// Determine crop rectangle
Rectangle cropRect;
if (crop != null && crop.AutoDetect)
{
// Auto-detect content bounds
_contentBoundsFrameCounter++;
if (_contentBoundsFrameCounter >= ContentBoundsRecalcInterval ||
_cachedContentBounds.Width == 0)
{
_cachedContentBounds = DetectContentBounds(bmp);
_contentBoundsFrameCounter = 0;
// Update the ContentBounds percentages from detected pixels
if (_cachedContentBounds.Width > 0 && _cachedContentBounds.Height > 0)
{
crop.LeftPct = (double)_cachedContentBounds.Left / bmp.Width;
crop.RightPct = 1.0 - (double)_cachedContentBounds.Right / bmp.Width;
crop.TopPct = (double)_cachedContentBounds.Top / bmp.Height;
crop.BottomPct = 1.0 - (double)_cachedContentBounds.Bottom / bmp.Height;
}
}
cropRect = _cachedContentBounds.Width > 0 ? _cachedContentBounds
: new Rectangle(0, 0, bmp.Width, bmp.Height);
}
else if (crop != null && (crop.LeftPct > 0 || crop.RightPct > 0 || crop.TopPct > 0 || crop.BottomPct > 0))
{
// Manual crop from percentages
int left = (int)(crop.LeftPct * bmp.Width);
int right = (int)((1.0 - crop.RightPct) * bmp.Width);
int top = (int)(crop.TopPct * bmp.Height);
int bottom = (int)((1.0 - crop.BottomPct) * bmp.Height);
cropRect = new Rectangle(left, top, Math.Max(right - left, 1), Math.Max(bottom - top, 1));
}
else
{
cropRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
}
return SampleZoneGrid(bmp, cols, rows, cropRect);
}
catch (Exception ex)
{
Logger.Log($"ScreenCapture.CaptureZoneGrid failed: {ex.Message}");
return null;
}
}
/// <summary>
/// Compute an expanded content bounds for Ambient crop mode (+5% each side, clamped).
/// </summary>
public static ContentBounds ExpandForAmbient(ContentBounds source)
{
return new ContentBounds
{
LeftPct = Math.Max(0, source.LeftPct - 0.05),
RightPct = Math.Max(0, source.RightPct - 0.05),
TopPct = Math.Max(0, source.TopPct - 0.05),
BottomPct = Math.Max(0, source.BottomPct - 0.05),
AutoDetect = false,
};
}
/// <summary>
/// Flatten a 2D zone grid to a 1D horizontal array by averaging rows.
/// Used for backward compatibility with OnZoneColors event.
/// </summary>
public static (byte R, byte G, byte B)[] FlattenToHorizontal((byte R, byte G, byte B)[,] grid, int cols, int rows)
{
var result = new (byte R, byte G, byte B)[cols];
for (int c = 0; c < cols; c++)
{
int r = 0, g = 0, b = 0;
for (int row = 0; row < rows; row++)
{
r += grid[row, c].R;
g += grid[row, c].G;
b += grid[row, c].B;
}
result[c] = ((byte)(r / rows), (byte)(g / rows), (byte)(b / rows));
}
return result;
}
/// <summary>
/// Get the averaged color of a named side/zone from the specified monitor.
/// Used by DreamSyncController for per-device zone mapping.
/// </summary>
public (byte R, byte G, byte B)? CaptureSide(int monitorIndex, ZoneSide side, int zoneCount)
{
if (_disposed) return null;
var bounds = GetMonitorBounds(monitorIndex);
if (bounds.Width == 0 || bounds.Height == 0) return null;
try
{
var bmp = CaptureScreen(bounds);
if (bmp == null) return null;
var region = GetSideRegion(bmp.Width, bmp.Height, side);
return SampleRegion(bmp, region);
}
catch (Exception ex)
{
Logger.Log($"ScreenCapture.CaptureSide failed: {ex.Message}");
return null;
}
}
// ── Monitor bounds ───────────────────────────────────────────────────────
public static Rectangle GetMonitorBounds(int monitorIndex)
{
var screens = System.Windows.Forms.Screen.AllScreens;
if (monitorIndex < 0 || monitorIndex >= screens.Length)
monitorIndex = 0;
return screens[monitorIndex].Bounds;
}
public static int MonitorCount => System.Windows.Forms.Screen.AllScreens.Length;
public static Bitmap? CapturePreviewFrame(int monitorIndex, int targetWidth, int targetHeight)
{
var bounds = GetMonitorBounds(monitorIndex);
if (bounds.Width <= 0 || bounds.Height <= 0 || targetWidth <= 0 || targetHeight <= 0)
return null;
var bitmap = new Bitmap(targetWidth, targetHeight, PixelFormat.Format32bppRgb);
try
{
using var g = Graphics.FromImage(bitmap);
var destHdc = g.GetHdc();
IntPtr srcHdc = IntPtr.Zero;
try
{
srcHdc = GetDC(IntPtr.Zero);
if (srcHdc == IntPtr.Zero)
{
bitmap.Dispose();
return null;
}
SetStretchBltMode(destHdc, HALFTONE);
SetBrushOrgEx(destHdc, 0, 0, IntPtr.Zero);
bool ok = StretchBlt(
destHdc, 0, 0, targetWidth, targetHeight,
srcHdc, bounds.X, bounds.Y, bounds.Width, bounds.Height,
SRCCOPY);
if (!ok)
{
bitmap.Dispose();
return null;
}
}
finally
{
if (srcHdc != IntPtr.Zero) ReleaseDC(IntPtr.Zero, srcHdc);
g.ReleaseHdc(destHdc);
}
return bitmap;
}
catch
{
bitmap.Dispose();
return null;
}
}
// ── GDI screen capture ───────────────────────────────────────────────────
// StretchBlt interop — GPU-accelerated downsample via HALFTONE filter.
// Captures ~4x faster at 4K than full-res BitBlt and produces a smaller
// bitmap for the CPU sampling loops to read.
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll")]
private static extern bool StretchBlt(
IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest,
IntPtr hdcSrc, int xSrc, int ySrc, int wSrc, int hSrc,
uint rop);
[DllImport("gdi32.dll")]
private static extern int SetStretchBltMode(IntPtr hdc, int mode);
[DllImport("gdi32.dll")]
private static extern bool SetBrushOrgEx(IntPtr hdc, int x, int y, IntPtr pt);
private const int HALFTONE = 4;
private const uint SRCCOPY = 0x00CC0020;
private Bitmap? CaptureScreen(Rectangle bounds)
{
// Downsampled target size — floored, minimum 1px per dim.
int dw = Math.Max(1, bounds.Width / CaptureDownsample);
int dh = Math.Max(1, bounds.Height / CaptureDownsample);
// Allocate (or reallocate) the cached bitmap only when source resolution changes.
if (_cachedBmp == null || _cachedSrcW != bounds.Width || _cachedSrcH != bounds.Height)
{
_cachedBmp?.Dispose();
_cachedBmp = new Bitmap(dw, dh, PixelFormat.Format32bppRgb);
_cachedSrcW = bounds.Width;
_cachedSrcH = bounds.Height;
}
try
{
using var g = Graphics.FromImage(_cachedBmp);
var destHdc = g.GetHdc();
IntPtr srcHdc = IntPtr.Zero;
try
{
srcHdc = GetDC(IntPtr.Zero);
if (srcHdc == IntPtr.Zero) return null;
// HALFTONE requires SetBrushOrgEx after SetStretchBltMode per MSDN.
SetStretchBltMode(destHdc, HALFTONE);
SetBrushOrgEx(destHdc, 0, 0, IntPtr.Zero);
bool ok = StretchBlt(
destHdc, 0, 0, dw, dh,
srcHdc, bounds.X, bounds.Y, bounds.Width, bounds.Height,
SRCCOPY);
if (!ok) return null;
}
finally
{
if (srcHdc != IntPtr.Zero) ReleaseDC(IntPtr.Zero, srcHdc);
g.ReleaseHdc(destHdc);
}
return _cachedBmp;
}
catch
{
return null;
}
}
// ── 2D Zone Grid sampling ─────────────────────────────────────────────
/// <summary>
/// Sample a 2D grid of zones [row, col] within the given crop rectangle.
/// Uses gamma-correct averaging and dark pixel filtering.
/// </summary>
private static (byte R, byte G, byte B)[,] SampleZoneGrid(Bitmap bmp, int cols, int rows, Rectangle crop)
{
crop.Intersect(new Rectangle(0, 0, bmp.Width, bmp.Height));
if (crop.Width == 0 || crop.Height == 0)
return new (byte R, byte G, byte B)[rows, cols];
var data = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppRgb);
var results = new (byte R, byte G, byte B)[rows, cols];
try
{
int stride = data.Stride;
int colWidth = Math.Max(1, crop.Width / cols);
int rowHeight = Math.Max(1, crop.Height / rows);
unsafe
{
byte* ptr = (byte*)data.Scan0;
for (int row = 0; row < rows; row++)
{
int yStart = crop.Top + row * rowHeight;
int yEnd = (row == rows - 1) ? crop.Bottom : yStart + rowHeight;
for (int col = 0; col < cols; col++)
{
int xStart = crop.Left + col * colWidth;
int xEnd = (col == cols - 1) ? crop.Right : xStart + colWidth;
double rLin = 0, gLin = 0, bLin = 0;
long count = 0;
for (int y = yStart; y < yEnd; y += SampleStride)
{
byte* rowPtr = ptr + y * stride;
for (int x = xStart; x < xEnd; x += SampleStride)
{
int offset = x * 4;
byte pb = rowPtr[offset];
byte pg = rowPtr[offset + 1];
byte pr = rowPtr[offset + 2];
if (pr + pg + pb < DarkThreshold)
continue;
double rl = pr / 255.0; rl *= rl;
double gl = pg / 255.0; gl *= gl;
double bl = pb / 255.0; bl *= bl;
rLin += rl;
gLin += gl;
bLin += bl;
count++;
}
}
if (count > 0)
{
results[row, col] = (
(byte)Math.Clamp(Math.Sqrt(rLin / count) * 255, 0, 255),
(byte)Math.Clamp(Math.Sqrt(gLin / count) * 255, 0, 255),
(byte)Math.Clamp(Math.Sqrt(bLin / count) * 255, 0, 255));
}
}
}
}
}
finally
{
bmp.UnlockBits(data);
}
return results;
}
// ── Content bounds detection (black bar cropping) ──────────────────────
/// <summary>
/// Detect the bounding rectangle of actual content within the frame,
/// excluding pillarbox (side black bars) and letterbox (top/bottom black bars).
/// Scans columns from edges inward to find where non-dark content starts.
/// Uses coarse sampling (every SampleStride rows/cols) for speed.
/// </summary>
private static Rectangle DetectContentBounds(Bitmap bmp)
{
var data = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppRgb);
int width = bmp.Width;
int height = bmp.Height;
int stride = data.Stride;
int left = 0, right = width, top = 0, bottom = height;
// Minimum non-dark pixels for a column/row to count as "content"
int colSamples = height / SampleStride;
int rowSamples = width / SampleStride;
int colThreshold = Math.Max(1, (int)(colSamples * BlackBarContentThreshold));
int rowThreshold = Math.Max(1, (int)(rowSamples * BlackBarContentThreshold));
try
{
unsafe
{
byte* ptr = (byte*)data.Scan0;
// Scan columns from left
for (int x = 0; x < width / 2; x += SampleStride)
{
int nonDark = 0;
for (int y = 0; y < height; y += SampleStride)
{
int offset = y * stride + x * 4;
if (ptr[offset] + ptr[offset + 1] + ptr[offset + 2] >= DarkThreshold)
nonDark++;
}
if (nonDark >= colThreshold) { left = x; break; }
}
// Scan columns from right
for (int x = width - 1; x >= width / 2; x -= SampleStride)
{
int nonDark = 0;
for (int y = 0; y < height; y += SampleStride)
{
int offset = y * stride + x * 4;
if (ptr[offset] + ptr[offset + 1] + ptr[offset + 2] >= DarkThreshold)
nonDark++;
}
if (nonDark >= colThreshold) { right = x + 1; break; }
}
// Scan rows from top
for (int y = 0; y < height / 2; y += SampleStride)
{
int nonDark = 0;
byte* row = ptr + y * stride;
for (int x = left; x < right; x += SampleStride)
{
int offset = x * 4;
if (row[offset] + row[offset + 1] + row[offset + 2] >= DarkThreshold)
nonDark++;
}
if (nonDark >= rowThreshold) { top = y; break; }
}
// Scan rows from bottom
for (int y = height - 1; y >= height / 2; y -= SampleStride)
{
int nonDark = 0;
byte* row = ptr + y * stride;
for (int x = left; x < right; x += SampleStride)
{
int offset = x * 4;
if (row[offset] + row[offset + 1] + row[offset + 2] >= DarkThreshold)
nonDark++;
}
if (nonDark >= rowThreshold) { bottom = y + 1; break; }
}
}
}
finally
{
bmp.UnlockBits(data);
}
// Sanity: ensure we have a reasonable content area (at least 25% of frame)
int contentW = right - left;
int contentH = bottom - top;
if (contentW < width / 4 || contentH < height / 4)
return new Rectangle(0, 0, width, height); // fall back to full frame
return new Rectangle(left, top, contentW, contentH);
}
// ── Zone sampling ────────────────────────────────────────────────────────
/// <summary>
/// Divide the bitmap into `zoneCount` horizontal slices within the given content bounds.
/// </summary>
private static (byte R, byte G, byte B)[] SampleZones(Bitmap bmp, int zoneCount, Rectangle contentBounds)
{
var data = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppRgb);
var results = new (byte R, byte G, byte B)[zoneCount];
try
{
int stride = data.Stride;
int zoneWidth = Math.Max(1, contentBounds.Width / zoneCount);
unsafe
{
byte* ptr = (byte*)data.Scan0;
for (int z = 0; z < zoneCount; z++)
{
int xStart = contentBounds.Left + z * zoneWidth;
int xEnd = (z == zoneCount - 1) ? contentBounds.Right : xStart + zoneWidth;
double rLin = 0, gLin = 0, bLin = 0;
long count = 0;
for (int y = contentBounds.Top; y < contentBounds.Bottom; y += SampleStride)
{
byte* row = ptr + y * stride;
for (int x = xStart; x < xEnd; x += SampleStride)
{
int offset = x * 4;
byte pb = row[offset];
byte pg = row[offset + 1];
byte pr = row[offset + 2];
if (pr + pg + pb < DarkThreshold)
continue;
double rl = pr / 255.0; rl *= rl;
double gl = pg / 255.0; gl *= gl;
double bl = pb / 255.0; bl *= bl;
rLin += rl;
gLin += gl;
bLin += bl;
count++;
}
}
if (count > 0)
{
results[z] = (
(byte)Math.Clamp(Math.Sqrt(rLin / count) * 255, 0, 255),
(byte)Math.Clamp(Math.Sqrt(gLin / count) * 255, 0, 255),
(byte)Math.Clamp(Math.Sqrt(bLin / count) * 255, 0, 255));
}
}
}
}
finally
{
bmp.UnlockBits(data);
}
return results;
}
/// <summary>
/// Divide the bitmap into `zoneCount` horizontal slices and average each zone's pixels.
/// Uses gamma-correct (linear space) averaging and filters dark pixels for accurate colors.
/// Returns an array of (R,G,B) per zone, left→right.
/// </summary>
private static (byte R, byte G, byte B)[] SampleZones(Bitmap bmp, int zoneCount)
{
var data = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppRgb);
var results = new (byte R, byte G, byte B)[zoneCount];
try
{
int bytesPerPixel = 4; // Format32bppRgb is still 4 bytes per pixel (B,G,R,unused)
int stride = data.Stride;
int width = bmp.Width;
int height = bmp.Height;
int zoneWidth = Math.Max(1, width / zoneCount);
unsafe
{
byte* ptr = (byte*)data.Scan0;
for (int z = 0; z < zoneCount; z++)
{
int xStart = z * zoneWidth;
int xEnd = (z == zoneCount - 1) ? width : xStart + zoneWidth;
// Accumulate in linear space for gamma-correct averaging
double rLin = 0, gLin = 0, bLin = 0;
long count = 0;
for (int y = 0; y < height; y += SampleStride)
{
byte* row = ptr + y * stride;
for (int x = xStart; x < xEnd; x += SampleStride)
{
int offset = x * bytesPerPixel;
byte pb = row[offset];
byte pg = row[offset + 1];
byte pr = row[offset + 2];
// Skip very dark pixels — prevents dark UI from washing out colors
if (pr + pg + pb < DarkThreshold)
continue;
// sRGB → linear (approximate gamma 2.2)
double rl = pr / 255.0; rl *= rl;
double gl = pg / 255.0; gl *= gl;
double bl = pb / 255.0; bl *= bl;
rLin += rl;
gLin += gl;
bLin += bl;
count++;
}
}
if (count > 0)
{
// Linear → sRGB (sqrt for gamma 2.2 approx)
results[z] = (
(byte)Math.Clamp(Math.Sqrt(rLin / count) * 255, 0, 255),
(byte)Math.Clamp(Math.Sqrt(gLin / count) * 255, 0, 255),
(byte)Math.Clamp(Math.Sqrt(bLin / count) * 255, 0, 255));
}
}
}
}
finally
{
bmp.UnlockBits(data);
}
return results;
}
/// <summary>
/// Average pixels in a specific rectangle region of the bitmap.
/// Uses gamma-correct averaging and dark pixel filtering.
/// </summary>
private static (byte R, byte G, byte B) SampleRegion(Bitmap bmp, Rectangle region)
{
region.Intersect(new Rectangle(0, 0, bmp.Width, bmp.Height));
if (region.Width == 0 || region.Height == 0) return (0, 0, 0);
var data = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppRgb);
double rLin = 0, gLin = 0, bLin = 0;
long count = 0;
try
{
int stride = data.Stride;
unsafe
{
byte* ptr = (byte*)data.Scan0;
for (int y = region.Top; y < region.Bottom; y += SampleStride)
{
byte* row = ptr + y * stride;
for (int x = region.Left; x < region.Right; x += SampleStride)
{
int offset = x * 4;
byte pb = row[offset];
byte pg = row[offset + 1];
byte pr = row[offset + 2];
if (pr + pg + pb < DarkThreshold)
continue;
double rl = pr / 255.0; rl *= rl;
double gl = pg / 255.0; gl *= gl;
double bl = pb / 255.0; bl *= bl;
rLin += rl; gLin += gl; bLin += bl;
count++;
}
}
}
}
finally
{
bmp.UnlockBits(data);
}
if (count == 0) return (0, 0, 0);
return (
(byte)Math.Clamp(Math.Sqrt(rLin / count) * 255, 0, 255),
(byte)Math.Clamp(Math.Sqrt(gLin / count) * 255, 0, 255),
(byte)Math.Clamp(Math.Sqrt(bLin / count) * 255, 0, 255));
}
/// <summary>
/// Map a ZoneSide to the pixel region it covers within the bitmap.
/// </summary>
private static Rectangle GetSideRegion(int width, int height, ZoneSide side)
{
return side switch
{
ZoneSide.Left => new Rectangle(0, 0, width / 2, height),
ZoneSide.Right => new Rectangle(width / 2, 0, width / 2, height),
ZoneSide.Top => new Rectangle(0, 0, width, height / 2),
ZoneSide.Bottom => new Rectangle(0, height / 2, width, height / 2),
_ => new Rectangle(0, 0, width, height), // Full
};
}
// ── Saturation boost ─────────────────────────────────────────────────────
/// <summary>
/// Apply HSV saturation multiplier to an RGB color. Clamps to 0-255.
/// </summary>
public static (byte R, byte G, byte B) BoostSaturation(byte r, byte g, byte b, float saturation)
{
if (Math.Abs(saturation - 1.0f) < 0.01f) return (r, g, b);
// RGB → HSV
float rf = r / 255f, gf = g / 255f, bf = b / 255f;
float max = Math.Max(rf, Math.Max(gf, bf));
float min = Math.Min(rf, Math.Min(gf, bf));
float delta = max - min;
float h = 0, s = 0, v = max;
if (max > 0) s = delta / max;
if (delta > 0)
{
if (max == rf) h = (gf - bf) / delta % 6;
else if (max == gf) h = (bf - rf) / delta + 2;
else h = (rf - gf) / delta + 4;
h /= 6;
if (h < 0) h += 1;
}
// Boost saturation
s = Math.Clamp(s * saturation, 0f, 1f);
// HSV → RGB
float c = v * s;
float x = c * (1 - Math.Abs(h * 6 % 2 - 1));
float m = v - c;
float ro, go, bo;
int hi = (int)(h * 6);
switch (hi % 6)
{
case 0: ro = c; go = x; bo = 0; break;
case 1: ro = x; go = c; bo = 0; break;
case 2: ro = 0; go = c; bo = x; break;
case 3: ro = 0; go = x; bo = c; break;
case 4: ro = x; go = 0; bo = c; break;
default: ro = c; go = 0; bo = x; break;
}
return (
(byte)Math.Clamp((ro + m) * 255, 0, 255),
(byte)Math.Clamp((go + m) * 255, 0, 255),
(byte)Math.Clamp((bo + m) * 255, 0, 255)
);
}
public void Dispose()
{
_disposed = true;
_cachedBmp?.Dispose();
_cachedBmp = null;
}
}