forked from NiLuJe/FBInk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fbink.c
12038 lines (11140 loc) · 431 KB
/
fbink.c
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
FBInk: FrameBuffer eInker, a library to print text & images to an eInk Linux framebuffer
Copyright (C) 2018-2024 NiLuJe <[email protected]>
SPDX-License-Identifier: GPL-3.0-or-later
----
Some (the 8/16/24/32bpp put_pixel_* variants) Linux framebuffer writing routines based on: fbtestfnt.c & fbtest6.c, from
https://raspberrycompote.blogspot.com/2014/04/low-level-graphics-on-raspberry-pi-text.html &
https://raspberrycompote.blogspot.com/2013/03/low-level-graphics-on-raspberry-pi-part_8.html
Original works by J-P Rosti (a.k.a -rst- and 'Raspberry Compote'),
Licensed under the Creative Commons Attribution 3.0 Unported License
(http://creativecommons.org/licenses/by/3.0/deed.en_US)
Ordered dithering routine (dither_o8x8) completely based on ImageMagick's implementation,
(OrderedDitherImage @ https://github.com/ImageMagick/ImageMagick/blob/master/MagickCore/threshold.c),
Copyright 1999-2019 ImageMagick Studio LLC,
Licensed under the ImageMagick License,
(https://imagemagick.org/script/license.php)
----
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "fbink.h"
#include "fbink_internal.h"
#ifdef FBINK_WITH_IMAGE
# define STB_IMAGE_IMPLEMENTATION
// Make it private, we don't need it anywhere else
# define STB_IMAGE_STATIC
// Disable HDR, as well as the linear light API, to avoid pulling in libm
# define STBI_NO_HDR
# define STBI_NO_LINEAR
// We want SIMD for JPEG decoding (... if we can actually use it)!
// It's not the end of the world if we can't, the speed gains are minimal (~5%).
# ifdef __ARM_NEON
# define STBI_NEON
# endif
// We don't care about those formats (PhotoShop, AutoDesk)
# define STBI_NO_PSD
# define STBI_NO_PIC
// We can't use stbi_failure_reason as it's not thread-safe, so ditch the strings
# define STBI_NO_FAILURE_STRINGS
// Prevent attempting to decode ginormous images
# define STBI_MAX_DIMENSIONS (1 << 13)
// Disable a bunch of very verbose but mostly harmless warnings
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wunknown-warning-option"
# pragma GCC diagnostic ignored "-Wcast-qual"
# pragma GCC diagnostic ignored "-Wcast-align"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wsign-conversion"
# pragma GCC diagnostic ignored "-Wduplicated-branches"
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wsign-compare"
# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=pure"
# include "stb/stb_image.h"
# pragma GCC diagnostic pop
#endif
#ifdef FBINK_WITH_OPENTYPE
# define STB_TRUETYPE_IMPLEMENTATION
// Make it private, we don't need it anywhere else
# define STBTT_STATIC
// stb_truetype is.... noisy
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wunknown-warning-option"
# pragma GCC diagnostic ignored "-Wcast-qual"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wsign-conversion"
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=pure"
# include "stb/stb_truetype.h"
# pragma GCC diagnostic pop
#endif
// Return the library version as devised at library compile-time
const char*
fbink_version(void)
{
return FBINK_VERSION;
}
// Return the target platform of the current library build
FBINK_TARGET_T
fbink_target(void)
{
#if defined(FBINK_FOR_LINUX)
return FBINK_TARGET_LINUX;
#elif defined(FBINK_FOR_KOBO)
return FBINK_TARGET_KOBO;
#elif defined(FBINK_FOR_KINDLE)
return FBINK_TARGET_KINDLE;
#elif defined(FBINK_FOR_LEGACY)
return FBINK_TARGET_KINDLE_LEGACY;
#elif defined(FBINK_FOR_CERVANTES)
return FBINK_TARGET_CERVANTES;
#elif defined(FBINK_FOR_REMARKABLE)
return FBINK_TARGET_REMARKABLE;
#elif defined(FBINK_FOR_POCKETBOOK)
return FBINK_TARGET_POCKETBOOK;
#else
// Unreachable
return FBINK_TARGET_MAX;
#endif
}
// Return the feature set of the current library build
uint32_t
fbink_features(void)
{
#ifndef FBINK_MINIMAL
uint32_t features = FBINK_FEATURE_FULL;
#else
uint32_t features = FBINK_FEATURE_MINIMAL;
# ifdef FBINK_WITH_DRAW
features |= FBINK_FEATURE_DRAW;
# endif
# ifdef FBINK_WITH_BITMAP
features |= FBINK_FEATURE_BITMAP;
# endif
# ifdef FBINK_WITH_FONTS
features |= FBINK_FEATURE_FONTS;
# endif
# ifdef FBINK_WITH_UNIFONT
features |= FBINK_FEATURE_UNIFONT;
# endif
# ifdef FBINK_WITH_OPENTYPE
features |= FBINK_FEATURE_OPENTYPE;
# endif
# ifdef FBINK_WITH_IMAGE
features |= FBINK_FEATURE_IMAGE;
# endif
# ifdef FBINK_WITH_BUTTON_SCAN
features |= FBINK_FEATURE_BUTTON_SCAN;
# endif
#endif // !FBINK_MINIMAL
return features;
}
#ifdef FBINK_WITH_DRAW
// #RGB -> RGB565
static inline __attribute__((always_inline, hot)) uint16_t
pack_rgb565(uint8_t r, uint8_t g, uint8_t b)
{
// ((r / 8) * 2048) + ((g / 4) * 32) + (b / 8);
return (uint16_t) (((r >> 3U) << 11U) | ((g >> 2U) << 5U) | (b >> 3U));
}
// Helper functions to 'plot' a specific pixel in a given color to the framebuffer
static inline __attribute__((always_inline, hot)) void
put_pixel_Gray4(const FBInkCoordinates* restrict coords, const FBInkPixel* restrict px)
{
// calculate the pixel's byte offset inside the buffer
// note: x / 2 as every byte holds 2 pixels
const size_t pix_offset = (coords->x >> 1U) + (coords->y * fInfo.line_length);
// NOTE: Squash 8bpp to 4bpp:
// (v >> 4)
// or: v * 16 / 256
// First, we'll need the current full byte to make sure we never clobber a nibble...
const uint8_t b = *((unsigned char*) (fbPtr + pix_offset));
// We can't address nibbles directly, so this takes some shenanigans...
if ((coords->x & 0x01u) == 0U) {
// Even pixel: high nibble
// ORed to avoid clobbering our odd pixel
*((unsigned char*) (fbPtr + pix_offset)) = (unsigned char) ((b & 0x0Fu) | (px->gray8 & 0xF0u));
// Squash to 4bpp, and write to the top/left nibble
// or: ((v >> 4) << 4)
} else {
// Odd pixel: low nibble
// ORed to avoid clobbering our even pixel
*((unsigned char*) (fbPtr + pix_offset)) = (unsigned char) ((b & 0xF0u) | (px->gray8 >> 4U));
}
}
static inline __attribute__((always_inline, hot)) void
put_pixel_Gray8(const FBInkCoordinates* restrict coords, const FBInkPixel* restrict px)
{
// calculate the pixel's byte offset inside the buffer
const size_t pix_offset = coords->x + (coords->y * fInfo.line_length);
// now this is about the same as 'fbp[pix_offset] = value'
*((unsigned char*) (fbPtr + pix_offset)) = px->gray8;
}
static inline __attribute__((always_inline)) void
put_pixel_RGB24(const FBInkCoordinates* restrict coords, const FBInkPixel* restrict px)
{
// calculate the pixel's byte offset inside the buffer
// note: x * 3 as every pixel is 3 consecutive bytes
const size_t pix_offset = (coords->x * 3U) + (coords->y * fInfo.line_length);
// now this is about the same as 'fbp[pix_offset] = value'
// NOTE: Technically legitimate warning. In practice, we always pass RGB32 pixels in 24bpp codepaths.
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wunknown-warning-option"
# pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
*((unsigned char*) (fbPtr + pix_offset)) = px->bgra.color.b;
*((unsigned char*) (fbPtr + pix_offset + 1U)) = px->bgra.color.g;
*((unsigned char*) (fbPtr + pix_offset + 2U)) = px->bgra.color.r;
# pragma GCC diagnostic pop
}
static inline __attribute__((always_inline, hot)) void
put_pixel_RGB32(const FBInkCoordinates* restrict coords, const FBInkPixel* restrict px)
{
// calculate the scanline's byte offset inside the buffer
const size_t scanline_offset = (size_t) coords->y * fInfo.line_length;
// write the four bytes at once
// NOTE: We rely on pointer arithmetic rules to handle the pixel offset inside the scanline,
// i.e., if we add x *after* the cast, that's an addition of x uint32_t elements, meaning x times 4 bytes,
// which is exactly what we want ;).
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-align"
*((uint32_t*) (fbPtr + scanline_offset) + coords->x) = px->bgra.p;
# pragma GCC diagnostic pop
}
static inline __attribute__((always_inline, hot)) void
put_pixel_RGB565(const FBInkCoordinates* restrict coords, const FBInkPixel* restrict px)
{
// calculate the scanline's byte offset inside the buffer
const size_t scanline_offset = (size_t) coords->y * fInfo.line_length;
// write the two bytes at once, much to GCC's dismay...
// NOTE: Input pixel *has* to be properly packed to RGB565 first (via pack_rgb565, c.f., put_pixel)!
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-align"
*((uint16_t*) (fbPtr + scanline_offset) + coords->x) = px->rgb565;
# pragma GCC diagnostic pop
}
#endif // FBINK_WITH_DRAW
#if defined(FBINK_FOR_KOBO) || defined(FBINK_FOR_CERVANTES) || defined(FBINK_FOR_POCKETBOOK)
// Handle rotation quirks...
static void
rotate_coordinates_pickel(FBInkCoordinates* restrict coords)
{
// Rotate the coordinates to account for pickel's rotation...
const unsigned short int rx = coords->y;
const unsigned short int ry = (unsigned short int) (screenWidth - coords->x - 1);
// NOTE: This codepath is not production ready, it was just an experiment to wrap my head around framebuffer rotation...
// In particular, only CW has been actually confirmed to behave properly (to handle the isNTX16bLandscape quirk),
// and region rotation is NOT handled properly/at all.
// TL;DR: This is for documentation purposes only, never build w/ MATHS defined ;).
# ifdef FBINK_WITH_MATHS_ROTA
uint8_t rotation = FB_ROTATE_CW;
// i.e., θ (c.f., https://en.wikipedia.org/wiki/Cartesian_coordinate_system#Rotation)
double rangle = ((rotation * 90) * M_PI / 180.0);
double fxp = coords->x * cos(rangle) - coords->y * sin(rangle);
double fyp = coords->x * sin(rangle) + coords->y * cos(rangle);
LOG("(fxp, fyp) -> (%f, %f)", fxp, fyp);
unsigned short int xp;
unsigned short int yp;
switch (rotation) {
case FB_ROTATE_CW:
xp = (unsigned short int) lround(-fxp);
yp = (unsigned short int) lround(vInfo.yres - 1 - fyp);
break;
case FB_ROTATE_UD:
// NOTE: IIRC, this pretty much ends up with (x', y') being equal to (y, x).
xp = (unsigned short int) lround(-fyp);
yp = (unsigned short int) lround(-fxp);
break;
case FB_ROTATE_CCW:
xp = (unsigned short int) lround(vInfo.xres - 1 - fxp);
yp = (unsigned short int) lround(-fyp);
break;
default:
xp = (unsigned short int) lround(fxp);
yp = (unsigned short int) lround(fyp);
break;
}
LOG("(x, y) -> (%hu, %hu) vs. (rx, ry) -> (%hu, %hu) vs. (x', y') -> (%hu, %hu)",
coords->x,
coords->y,
rx,
ry,
xp,
yp);
coords->x = xp;
coords->y = yp;
# else
coords->x = rx;
coords->y = ry;
# endif
}
#endif // FBINK_FOR_KOBO || FBINK_FOR_CERVANTES || FBINK_FOR_POCKETBOOK
#if defined(FBINK_FOR_KOBO) || defined(FBINK_FOR_CERVANTES)
static void
rotate_coordinates_boot(FBInkCoordinates* restrict coords)
{
// Rotate the coordinates to account for the native boot rotation...
// NOTE: See the note is fbink_init, this is based on a replicated boot modeset,
// which apparently doesn't exactly match the *real* boot modeset... -_-".
const unsigned short int rx = (unsigned short int) (screenHeight - coords->y - 1);
const unsigned short int ry = coords->x;
coords->x = rx;
coords->y = ry;
}
# ifdef FBINK_WITH_BUTTON_SCAN
// NOTE: Do *not* trust this to do the right thing, see utils/finger_trace.c instead!
// This is basically left as-is for archeological purposes only,
// the only caller is in button_scan, which was kind of a crazy experiment to begin with ;).
static void
rotate_touch_coordinates(FBInkCoordinates* restrict coords)
{
unsigned short int rx = coords->x;
unsigned short int ry = coords->y;
uint32_t rotation = vInfo.rotate;
// NOTE: Try to take into account the various rotation quirks, depending on the device...
// c.f., mxc_epdc_fb_check_var @ drivers/video/mxc/mxc_epdc_fb.c OR drivers/video/fbdev/mxc/mxc_epdc_v2_fb.c
if (deviceQuirks.ntxRotaQuirk == NTX_ROTA_ODD_INVERTED) {
// On the Forma, only Portrait orientations are inverted...
// When I say Portrait/Landscape, that's how the device *looks*, which doesn't match the FB_ROTATE_* constants...
// i.e., in Nickel, *visually*, UR is 3, CW is 2, UD is 1, CCW is 0,
// and when sending ioctls, UR returns 0 (match), CW returns 3 (^= 2), UD returns 2 (match), CCW returns 1 (^= 2).
if (rotation & 0x01u) {
// Rotation constant is odd (i.e., CW or CCW), invert it.
rotation ^= 2U;
}
// NOTE: Plato goes with a simple rotation = (4 - rotation) % 4; which does the exact same thing,
// I just have a harder time wrapping my head around it ;).
// Plus, I'm inclined to believe a simple branch would be faster than a modulo.
} else if (deviceQuirks.ntxRotaQuirk == NTX_ROTA_ALL_INVERTED) {
// On *some* devices with a 6.8" panel, *every* orientation is inverted...
rotation ^= 2U;
} else if (deviceQuirks.ntxRotaQuirk == NTX_ROTA_SANE) {
// TODO: This is for the Libra, double-check that it holds up...
// The reasoning being to try to match the Forma's behavior:
// UR -> 3 ^ 2 -> CW / CW -> 2 -> UD / UD -> 1 ^ 2 -> CCW / CCW -> 0 -> UR
// The format being: *effective* orientation (i.e., user-facing) -> actual fb rotate value -> input transform
// Wich means we essentially want:
// UR -> CW / CW -> UD / UD -> CCW / CCW -> UR
// Given the fact that the Libra's panel is finally Portrait, and kept @ UR (boot, pickel & nickel),
// effective orientation & fb rotate value should always match,
// that means we just need to shift by +90°, one CW rotation.
// I suspect this bit of insanity was actually mangled back in for backwards compatibility w/ NTX shenanigans...
rotation = (rotation + 1U) & 3U;
}
// NOTE: Should match *most* Kobo devices...
// c.f., https://patchwork.openembedded.org/patch/149258
// NOTE: See also create_and_get_mt_pdata @ drivers/input/touchscreen/cyttsp5_devtree.c,
// there may be method to this madness...
switch (rotation) {
case FB_ROTATE_UR:
// NOP!
break;
case FB_ROTATE_CW:
rx = coords->y;
ry = (unsigned short int) (screenWidth - coords->x - 1);
break;
case FB_ROTATE_UD:
rx = (unsigned short int) (screenWidth - coords->x - 1);
ry = (unsigned short int) (screenHeight - coords->y - 1);
break;
case FB_ROTATE_CCW:
rx = (unsigned short int) (screenHeight - coords->y - 1);
ry = coords->x;
break;
}
// NOTE: The H2O²r1 (possibly r2 as well), on the other hand, is a special snowflake...
// (It'll need a dedicated deviceQuirks).
// c.f., https://www.mobileread.com/forums/showpost.php?p=3766627&postcount=236
// & https://github.com/baskerville/plato/commit/5181eaf0b48a9e1201b6ea5751c2af108512f74f
// & https://github.com/baskerville/plato/commit/bf7af35eef9c29250d206687738b4888f40ecab1
/*
switch(rotation) {
case FB_ROTATE_UR:
rx = coords->x;
ry = (unsigned short int) (screenHeight - coords->y - 1);
break;
case FB_ROTATE_CW:
rx = (unsigned short int) (screenHeight - coords->y - 1);
ry = (unsigned short int) (screenWidth - coords->x - 1);
break;
case FB_ROTATE_UD:
rx = (unsigned short int) (screenWidth - coords->x - 1);
ry = coords->y;
break;
case FB_ROTATE_CCW:
rx = coords->y;
ry = coords->x;
break;
}
*/
coords->x = rx;
coords->y = ry;
}
# endif // FBINK_WITH_BUTTON_SCAN
#endif // FBINK_FOR_KOBO || FBINK_FOR_CERVANTES
static void
rotate_coordinates_nop(FBInkCoordinates* restrict coords __attribute__((unused)))
{
// NOP!
// May be smarter than one might think on armv7-a,
// (quoting http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.100069_0610_01_en/pge1425898111637.html
// "NOP is not necessarily a time-consuming NOP.
// The processor might remove it from the pipeline before it reaches the execution stage."),
// which might explain why this isn't worse than branching (i.e., what we did before
// https://github.com/NiLuJe/FBInk/commit/75407d4a44d7bfc7705665ad4ec9ecad0d03a368).
}
#ifdef FBINK_WITH_DRAW
// Handle a few sanity checks...
// NOTE: If you can, prefer using the right put_pixel_* function directly.
// While the bounds checking is generally rather cheap,
// (i.e., (*fxpPutPixel) is only marginally faster than put_pixel()),
// the overhead of going through the function pointers is rather large
// (i.e., put_pixel() can be twice as slow as put_pixel_*()).
// On the oldest of our target HW, it's often *slightly* faster than branching or switching, though ;).
// But on modern processors, even on our target HW, branching should eventually take the lead, though,
// and in this case (ha!) appears to behave *noticeably* better than switching...
// Which is why we now branch via an if ladder, as it should offer marginally better performance on newer devices.
static inline __attribute__((always_inline, hot)) void
put_pixel(FBInkCoordinates coords, const FBInkPixel* restrict px, bool is_rgb565)
{
// Handle rotation now, so we can properly validate if the pixel is off-screen or not ;).
// fbink_init() takes care of setting this global pointer to the right function...
// NOTE: In this case, going through the function pointer is *noticeably* faster than branching...
(*fxpRotateCoords)(&coords);
// NOTE: Discard off-screen pixels!
// For instance, when we have a halfcell offset in conjunction with a !isPerfectFit pixel offset,
// when we're padding and centering, the final whitespace of right-padding will have its last
// few pixels (the exact amount being half of the dead zone width) pushed off-screen...
// And, of course, anything using hoffset or voffset can happily push stuff OOB ;).
if (unlikely(coords.x >= vInfo.xres || coords.y >= vInfo.yres)) {
# ifdef DEBUG
// NOTE: This is only enabled in Debug builds because it can be pretty verbose,
// and does not necessarily indicate an actual issue, as we've just explained...
LOG("Put: discarding off-screen pixel @ (%hu, %hu) (out of %ux%u bounds)",
coords.x,
coords.y,
vInfo.xres,
vInfo.yres);
# endif
return;
}
// NOTE: Hmm, here, an if ladder appears to be ever so *slightly* faster than going through the function pointer...
if (vInfo.bits_per_pixel == 4U) {
put_pixel_Gray4(&coords, px);
} else if (likely(vInfo.bits_per_pixel == 8U)) {
put_pixel_Gray8(&coords, px);
} else if (vInfo.bits_per_pixel == 16U) {
// Do we need to pack the pixel, first?
if (is_rgb565) {
// Nope :)
put_pixel_RGB565(&coords, px);
} else {
// Yep :(
FBInkPixel packed_px;
// NOTE: Technically legitimate warning. In practice, we always pass RGB32 pixels in 16bpp codepaths.
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wunknown-warning-option"
# pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
packed_px.rgb565 = pack_rgb565(px->bgra.color.r, px->bgra.color.g, px->bgra.color.b);
# pragma GCC diagnostic pop
put_pixel_RGB565(&coords, &packed_px);
}
} else if (unlikely(vInfo.bits_per_pixel == 24U)) {
put_pixel_RGB24(&coords, px);
} else if (likely(vInfo.bits_per_pixel == 32U)) {
put_pixel_RGB32(&coords, px);
}
}
// Helper functions to 'get' a specific pixel's color from the framebuffer
// c.f., FBGrab convert* functions
// (http://trac.ak-team.com/trac/browser/niluje/Configs/trunk/Kindle/Misc/FBGrab/fbgrab.c#L402)
// as well as KOReader's routines
// (https://github.com/koreader/koreader-base/blob/b3e72affd0e1ba819d92194b229468452c58836f/ffi/blitbuffer.lua#L292)
static inline __attribute__((always_inline, hot)) void
get_pixel_Gray4(const FBInkCoordinates* restrict coords, FBInkPixel* restrict px)
{
// calculate the pixel's byte offset inside the buffer
// note: x / 2 as every byte holds 2 pixels
const size_t pix_offset = (coords->x >> 1U) + (coords->y * fInfo.line_length);
// NOTE: Expand 4bpp to 8bpp:
// (v * 0x11)
// Byte to nibble (c.f., https://en.wikipedia.org/wiki/Nibble)
// Hi:
// (((b) >> 4) & 0x0F)
// Lo:
// ((b) & 0x0F)
// We'll need the full byte first...
const uint8_t b = *((const unsigned char*) (fbPtr + pix_offset));
if ((coords->x & 0x01u) == 0U) {
// Even pixel: high nibble
const uint8_t v = (b & 0xF0u);
px->gray8 = (v | (v >> 4U));
// pull the top/left nibble, expanded to 8bit
// or: (uint8_t)((((b) >> 4) & 0x0F) * 0x11);
} else {
// Odd pixel: low nibble
px->gray8 = (uint8_t) ((b & 0x0Fu) * 0x11u);
// or: pull the low/right nibble, expanded to 8bit
}
// NOTE: c.f., FBInkPixel typedef in fbink_types.h for details on the union shenanigans...
// In short: gray8 -> gray4.hi -> bgra.color.b
// gray4.lo -> bgra.color.g
}
static inline __attribute__((always_inline, hot)) void
get_pixel_Gray8(const FBInkCoordinates* restrict coords, FBInkPixel* restrict px)
{
// calculate the pixel's byte offset inside the buffer
const size_t pix_offset = coords->x + (coords->y * fInfo.line_length);
px->gray8 = *((unsigned char*) (fbPtr + pix_offset));
}
static inline __attribute__((always_inline)) void
get_pixel_RGB24(const FBInkCoordinates* restrict coords, FBInkPixel* restrict px)
{
// calculate the pixel's byte offset inside the buffer
// note: x * 3 as every pixel is 3 consecutive bytes
const size_t pix_offset = (coords->x * 3U) + (coords->y * fInfo.line_length);
px->bgra.color.b = *((unsigned char*) (fbPtr + pix_offset));
px->bgra.color.g = *((unsigned char*) (fbPtr + pix_offset + 1U));
px->bgra.color.r = *((unsigned char*) (fbPtr + pix_offset + 2U));
}
static inline __attribute__((always_inline, hot)) void
get_pixel_RGB32(const FBInkCoordinates* restrict coords, FBInkPixel* restrict px)
{
// calculate the pixel's byte offset inside the buffer
const size_t scanline_offset = (size_t) coords->y * fInfo.line_length;
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-align"
px->bgra.p = *((uint32_t*) (fbPtr + scanline_offset) + coords->x);
# pragma GCC diagnostic pop
// NOTE: We generally don't care about alpha, we always assume it's opaque, as that's how it behaves.
// We *do* pickup the actual alpha value, here, though.
}
static inline __attribute__((always_inline, hot)) void
get_pixel_RGB565(const FBInkCoordinates* restrict coords, FBInkPixel* restrict px)
{
// calculate the pixel's byte offset inside the buffer
const size_t scanline_offset = (size_t) coords->y * fInfo.line_length;
// NOTE: We're honoring the fb's bitfield offsets here (B: 0, G: >> 5, R: >> 11)
// Like put_pixel_RGB565, read those two consecutive bytes at once
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-align"
const uint16_t v = *((const uint16_t*) (fbPtr + scanline_offset) + coords->x);
# pragma GCC diagnostic pop
// NOTE: Unpack to RGB32, because we have no use for RGB565, it's terrible.
// NOTE: c.f., https://stackoverflow.com/q/2442576
// I feel that this approach tracks better with what we do in put_pixel_RGB565,
// and I have an easier time following it than the previous approach ported from KOReader.
// Both do exactly the same thing, though ;).
const uint8_t r = (uint8_t) ((v & 0xF800u) >> 11U); // 11111000 00000000 = 0xF800
const uint8_t g = (v & 0x07E0u) >> 5U; // 00000111 11100000 = 0x07E0
const uint8_t b = (v & 0x001Fu); // 00000000 00011111 = 0x001F
px->bgra.color.r = (uint8_t) ((r << 3U) | (r >> 2U));
px->bgra.color.g = (uint8_t) ((g << 2U) | (g >> 4U));
px->bgra.color.b = (uint8_t) ((b << 3U) | (b >> 2U));
}
// Handle a few sanity checks...
static inline __attribute__((always_inline, hot)) void
get_pixel(FBInkCoordinates coords, FBInkPixel* restrict px)
{
// Handle rotation now, so we can properly validate if the pixel is off-screen or not ;).
// fbink_init() takes care of setting this global pointer to the right function...
(*fxpRotateCoords)(&coords);
// NOTE: Discard off-screen pixels!
// For instance, when we have a halfcell offset in conjunction with a !isPerfectFit pixel offset,
// when we're padding and centering, the final whitespace of right-padding will have its last
// few pixels (the exact amount being half of the dead zone width) pushed off-screen...
// And, of course, anything using hoffset or voffset can happily push stuff OOB ;).
if (unlikely(coords.x >= vInfo.xres || coords.y >= vInfo.yres)) {
# ifdef DEBUG
// NOTE: This is only enabled in Debug builds because it can be pretty verbose,
// and does not necessarily indicate an actual issue, as we've just explained...
LOG("Put: discarding off-screen pixel @ (%hu, %hu) (out of %ux%u bounds)",
coords.x,
coords.y,
vInfo.xres,
vInfo.yres);
# endif
return;
}
// NOTE: Hmm, here, an if ladder appears to be ever so *slightly* faster than going through the function pointer...
if (vInfo.bits_per_pixel == 4U) {
get_pixel_Gray4(&coords, px);
} else if (likely(vInfo.bits_per_pixel == 8U)) {
get_pixel_Gray8(&coords, px);
} else if (vInfo.bits_per_pixel == 16U) {
get_pixel_RGB565(&coords, px);
} else if (unlikely(vInfo.bits_per_pixel == 24U)) {
get_pixel_RGB24(&coords, px);
} else if (likely(vInfo.bits_per_pixel == 32U)) {
get_pixel_RGB32(&coords, px);
}
}
// Helper functions to draw a rectangle in a given color
static __attribute__((hot)) void
fill_rect_Gray4(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// Go with pixel plotting @ 4bpp to keep this simple...
for (unsigned short int cy = 0U; cy < h; cy++) {
for (unsigned short int cx = 0U; cx < w; cx++) {
const FBInkCoordinates coords = {
.x = (unsigned short int) (x + cx),
.y = (unsigned short int) (y + cy),
};
put_pixel_Gray4(&coords, px);
}
}
# ifdef DEBUG
LOG("Filled a #%02hhX %hux%hu rectangle @ (%hu, %hu)", px->gray8, w, h, x, y);
# endif
}
static __attribute__((hot)) void
fill_rect_Gray4_checked(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// Bounds-checking, to ensure the memset won't do stupid things...
// Do signed maths, to account for the fact that x or y might already be OOB!
if (unlikely(x + w > screenWidth)) {
w = (unsigned short int) MAX(0, (w - ((x + w) - (int) screenWidth)));
# ifdef DEBUG
LOG("Chopped rectangle width to %hu", w);
# endif
}
if (unlikely(y + h > screenHeight)) {
h = (unsigned short int) MAX(0, (h - ((y + h) - (int) screenHeight)));
# ifdef DEBUG
LOG("Chopped rectangle height to %hu", h);
# endif
}
// Abort early if that left us with an empty rectangle ;).
if (unlikely(w == 0U || h == 0U)) {
# ifdef DEBUG
LOG("Skipped empty %hux%hu rectangle @ (%hu, %hu)", w, h, x, y);
# endif
return;
}
return fill_rect_Gray4(x, y, w, h, px);
}
# ifdef FBINK_FOR_POCKETBOOK
static __attribute__((hot)) void
fill_rect_Gray8(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// NOTE: We may require fxpRotateRegion on PB :(.
struct mxcfb_rect region = {
.top = y,
.left = x,
.width = w,
.height = h,
};
(*fxpRotateRegion)(®ion);
for (size_t j = region.top; j < region.top + region.height; j++) {
uint8_t* p = fbPtr + (fInfo.line_length * j) + (region.left);
memset(p, px->gray8, region.width);
}
# ifdef DEBUG
LOG("Filled a #%02hhX %hux%hu rectangle @ (%hu, %hu)", px->gray8, w, h, x, y);
# endif
}
# else
static __attribute__((hot)) void
fill_rect_Gray8(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// NOTE: fxpRotateRegion is never set at 8bpp :).
for (size_t j = y; j < y + h; j++) {
uint8_t* p = fbPtr + (fInfo.line_length * j) + (x);
memset(p, px->gray8, w);
}
# ifdef DEBUG
LOG("Filled a #%02hhX %hux%hu rectangle @ (%hu, %hu)", px->gray8, w, h, x, y);
# endif
}
# endif
static __attribute__((hot)) void
fill_rect_Gray8_checked(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// Bounds-checking, to ensure the memset won't do stupid things...
// Do signed maths, to account for the fact that x or y might already be OOB!
if (unlikely(x + w > screenWidth)) {
w = (unsigned short int) MAX(0, (w - ((x + w) - (int) screenWidth)));
# ifdef DEBUG
LOG("Chopped rectangle width to %hu", w);
# endif
}
if (unlikely(y + h > screenHeight)) {
h = (unsigned short int) MAX(0, (h - ((y + h) - (int) screenHeight)));
# ifdef DEBUG
LOG("Chopped rectangle height to %hu", h);
# endif
}
// Abort early if that left us with an empty rectangle ;).
if (unlikely(w == 0U || h == 0U)) {
# ifdef DEBUG
LOG("Skipped empty %hux%hu rectangle @ (%hu, %hu)", w, h, x, y);
# endif
return;
}
return fill_rect_Gray8(x, y, w, h, px);
}
static __attribute__((hot)) void
fill_rect_RGB565(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// Things are a bit trickier @ 16bpp, because except for black or white, we're not sure the requested color
// will be composed of two indentical bytes when packed as RGB565... -_-".
// NOTE: Silver lining: as fill_rect was originally designed to only ever be fed eInk palette colors,
// we have a guarantee that the input pixel is already packed, so we can use px->rgb565 ;).
struct mxcfb_rect region = {
.top = y,
.left = x,
.width = w,
.height = h,
};
(*fxpRotateRegion)(®ion);
// And that's a cheap-ass manual memset16, let's hope the compiler can do something fun with that...
// That's the exact pattern used by the Linux kernel (c.f., memset16 @ lib/string.c), so, here's hoping ;).
for (size_t j = region.top; j < region.top + region.height; j++) {
const size_t scanline_offset = fInfo.line_length * j;
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-align"
uint16_t* restrict p = (uint16_t*) (fbPtr + scanline_offset) + region.left;
# pragma GCC diagnostic pop
size_t px_count = region.width;
while (px_count--) {
*p++ = px->rgb565;
}
}
# ifdef DEBUG
LOG("Filled a #%02hhX %hux%hu rectangle @ (%hu, %hu)", px->gray8, w, h, x, y);
# endif
}
static __attribute__((hot)) void
fill_rect_RGB565_checked(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// Bounds-checking, to ensure the memset won't do stupid things...
// Do signed maths, to account for the fact that x or y might already be OOB!
// NOTE: Unlike put_pixel, we check against screenWidth/screenHeight instead of xres/yres because we're doing this
// *before* fxpRotateRegion!
if (unlikely(x + w > screenWidth)) {
w = (unsigned short int) MAX(0, (w - ((x + w) - (int) screenWidth)));
# ifdef DEBUG
LOG("Chopped rectangle width to %hu", w);
# endif
}
if (unlikely(y + h > screenHeight)) {
h = (unsigned short int) MAX(0, (h - ((y + h) - (int) screenHeight)));
# ifdef DEBUG
LOG("Chopped rectangle height to %hu", h);
# endif
}
// Abort early if that left us with an empty rectangle ;).
if (unlikely(w == 0U || h == 0U)) {
# ifdef DEBUG
LOG("Skipped empty %hux%hu rectangle @ (%hu, %hu)", w, h, x, y);
# endif
return;
}
return fill_rect_RGB565(x, y, w, h, px);
}
static void
fill_rect_RGB24(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// NOTE: fxpRotateRegion is never set at 24bpp :).
for (size_t j = y; j < y + h; j++) {
uint8_t* p = fbPtr + (fInfo.line_length * j) + (x * 3U);
memset(p, px->gray8, w * 3U);
}
# ifdef DEBUG
LOG("Filled a #%02hhX %hux%hu rectangle @ (%hu, %hu)", px->gray8, w, h, x, y);
# endif
}
static void
fill_rect_RGB24_checked(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// Bounds-checking, to ensure the memset won't do stupid things...
// Do signed maths, to account for the fact that x or y might already be OOB!
if (unlikely(x + w > screenWidth)) {
w = (unsigned short int) MAX(0, (w - ((x + w) - (int) screenWidth)));
# ifdef DEBUG
LOG("Chopped rectangle width to %hu", w);
# endif
}
if (unlikely(y + h > screenHeight)) {
h = (unsigned short int) MAX(0, (h - ((y + h) - (int) screenHeight)));
# ifdef DEBUG
LOG("Chopped rectangle height to %hu", h);
# endif
}
// Abort early if that left us with an empty rectangle ;).
if (unlikely(w == 0U || h == 0U)) {
# ifdef DEBUG
LOG("Skipped empty %hux%hu rectangle @ (%hu, %hu)", w, h, x, y);
# endif
return;
}
return fill_rect_RGB24(x, y, w, h, px);
}
static __attribute__((hot)) void
fill_rect_RGB32(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// NOTE: fxpRotateRegion is never set at 32bpp :).
for (size_t j = y; j < y + h; j++) {
// NOTE: Go with a cheap memset32 in order to preserve the alpha value of our input pixel...
// The compiler should be able to turn that into something as fast as a plain memset ;).
const size_t scanline_offset = fInfo.line_length * j;
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-align"
uint32_t* p = (uint32_t*) (fbPtr + scanline_offset) + x;
# pragma GCC diagnostic pop
size_t px_count = w;
while (px_count--) {
*p++ = px->bgra.p;
}
}
# ifdef DEBUG
LOG("Filled a #%02hhX %hux%hu rectangle @ (%hu, %hu)", px->gray8, w, h, x, y);
# endif
}
static __attribute__((hot)) void
fill_rect_RGB32_checked(unsigned short int x,
unsigned short int y,
unsigned short int w,
unsigned short int h,
const FBInkPixel* restrict px)
{
// Bounds-checking, to ensure the memset won't do stupid things...
// Do signed maths, to account for the fact that x or y might already be OOB!
if (unlikely(x + w > screenWidth)) {
w = (unsigned short int) MAX(0, (w - ((x + w) - (int) screenWidth)));
# ifdef DEBUG
LOG("Chopped rectangle width to %hu", w);
# endif
}
if (unlikely(y + h > screenHeight)) {
h = (unsigned short int) MAX(0, (h - ((y + h) - (int) screenHeight)));
# ifdef DEBUG
LOG("Chopped rectangle height to %hu", h);
# endif
}
// Abort early if that left us with an empty rectangle ;).
if (unlikely(w == 0U || h == 0U)) {
# ifdef DEBUG
LOG("Skipped empty %hux%hu rectangle @ (%hu, %hu)", w, h, x, y);
# endif
return;
}
return fill_rect_RGB32(x, y, w, h, px);
}
// Helper function to clear the screen - fill whole screen with given color
static void
clear_screen(int fbfd UNUSED_BY_NOTKINDLE, uint8_t v, bool is_flashing UNUSED_BY_NOTKINDLE)
{
# ifdef FBINK_FOR_KINDLE
// NOTE: einkfb has a dedicated ioctl, so, use that, when it's not doing more harm than good...
if (deviceQuirks.isKindleLegacy) {
// NOTE: The ioctl only does white, though, and it has a tendency to enforce a flash,
// which would cause a double refresh if we were to print a rectangle in another color right after...
// So, basically, only use the ioctl when we request a FLASHING clear to WHITE...
// This still enforces an explicit flash that's lengthier than what we usually get,
// not that that's a great comparison, since we hardly ever manage to coax a *real* full flash
// out of einkfb... This appears to do it (i.e., ~800ms)!
// NOTE: We're on inverted palette devices, hence the use of the "wrong" LUT...
// NOTE: We're calling clear_screen to handle is_cleared,
// which means we're probably refreshing twice in these cases...
// Oh, well...
if (is_flashing && v == eInkFGCMap[BG_WHITE]) {
if (ioctl(fbfd, FBIO_EINK_CLEAR_SCREEN, EINK_CLEAR_SCREEN) < 0) {
PFWARN("FBIO_EINK_CLEAR_SCREEN: %m");
// Just warn, this is non-fatal ;).
}
LOG("Requested a flashing WHITE clear, only doing an FBIO_EINK_CLEAR_SCREEN to save some time!");
return;
}
// NOTE: And because we can't have nice things, the einkfb driver has a stupid "optimization",
// where it discards redundant FBIO_EINK_UPDATE_DISPLAY* calls if the buffer content hasn't changed...
// If we memset the full smem_len, that trips this check, because we probably overwrite both buffers...
// Do a slightly more targeted memset instead (line_length * yres_virtual),
// which should cover the active & visible buffer only...
memset(fbPtr, v, fInfo.line_length * vInfo.yres_virtual);
} else {
memset(fbPtr, v, fInfo.smem_len);