Repository navigation
Expand file tree
/
Copy pathImage.rs
More file actions
2054 lines (1955 loc) · 88.3 KB
/
Copy pathImage.rs
File metadata and controls
2054 lines (1955 loc) · 88.3 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
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
//! `Bun.Image` — Sharp-shaped image pipeline backed by the statically linked
//! libjpeg-turbo / libspng / libwebp codecs and the highway resize kernel.
//!
//! Shape: the constructor only captures the *input* (path or bytes). Chainable
//! mutators (`resize`, `rotate`, `flip`, `flop`, `jpeg`/`png`/`webp`) each
//! write one slot of `Pipeline` and return `this` — there is no op list, so
//! calling a setter twice overwrites. The actual decode → transform → encode
//! work happens off-thread when a terminal (`bytes`/`buffer`/`blob`/
//! `toBase64`/`metadata`) is awaited, via `jsc.ConcurrentPromiseTask`.
use core::cell::Cell;
use core::mem;
use crate::generated_classes::PropertyName;
use crate::webcore::Blob;
use crate::webcore::BlobExt as _;
use crate::webcore::blob::store as blob_store;
use crate::webcore::blob::{ReadBytesHandler, ReadBytesResult};
use crate::webcore::node_types::PathOrFileDescriptor;
use bun_core::ZBox;
use bun_core::base64;
use bun_core::zstr;
use bun_core::{ZStr, strings};
use bun_jsc::concurrent_promise_task::{ConcurrentPromiseTask, ConcurrentPromiseTaskContext};
use bun_jsc::{
self as jsc, ArrayBuffer, CallFrame, JSGlobalObject, JSPromise, JSValue, JsCell, JsClass as _,
JsRef, JsResult, StringJsc as _, Strong, SysErrorJsc as _,
};
use bun_sys as sys;
use super::codecs;
use super::exif;
use super::thumbhash;
/// Lowercase JS-visible name for a `codecs::Format`. Local until `Format`
/// derives `IntoStaticStr` (variant casing differs from JS).
#[inline]
fn format_name(f: codecs::Format) -> &'static str {
match f {
codecs::Format::Jpeg => "jpeg",
codecs::Format::Png => "png",
codecs::Format::Webp => "webp",
codecs::Format::Heic => "heic",
codecs::Format::Avif => "avif",
codecs::Format::Bmp => "bmp",
codecs::Format::Tiff => "tiff",
codecs::Format::Gif => "gif",
}
}
// `pub const js = jsc.Codegen.JSImage;` — `fromJS`/`fromJSDirect`/`toJS` are
// provided by `#[bun_jsc::JsClass]` codegen (see PORTING.md §JSC types). The
// `sourceJS` cached-value accessors are emitted by `generate-classes.ts` into
// `generated_classes.rs::js_Image`; re-export that module here so callers use
// `js::source_js_set_cached` / `js::source_js_get_cached`.
pub use crate::generated_classes::js_Image as js;
// R-2 (host-fn re-entrancy): every JS-exposed method takes `&self`; per-field
// interior mutability via `Cell` (Copy) / `JsCell` (non-Copy). `max_pixels`
// / `auto_orient` are read-only after construction so stay bare.
#[bun_jsc::JsClass]
pub struct Image {
source: JsCell<Source>,
pipeline: Cell<Pipeline>,
/// Decompression-bomb guard. Checked against the *header* dimensions before
/// any RGBA buffer is allocated. Mirrors Sharp's `limitInputPixels`.
max_pixels: u64,
/// Apply EXIF Orientation (JPEG) before any user ops, the way Sharp's
/// `.rotate()`-with-no-args / `autoOrient` does.
auto_orient: bool,
/// Populated after a pipeline has run once; lets `.width`/`.height` answer
/// synchronously after the first await.
last_width: Cell<i32>,
last_height: Cell<i32>,
/// Strong while at least one PipelineTask is in flight, weak otherwise. The
/// Strong→wrapper→sourceJS-slot chain is what keeps the borrowed ArrayBuffer
/// alive across the WorkPool roundtrip; switching to weak when idle lets GC
/// collect the wrapper without polling `hasPendingActivity` every cycle.
this_ref: JsCell<JsRef>,
pending_tasks: Cell<u32>,
}
impl Default for Image {
fn default() -> Self {
Self {
source: JsCell::new(Source::JsBuffer),
pipeline: Cell::new(Pipeline::default()),
max_pixels: codecs::DEFAULT_MAX_PIXELS,
auto_orient: true,
last_width: Cell::new(-1),
last_height: Cell::new(-1),
this_ref: JsCell::new(JsRef::empty()),
pending_tasks: Cell::new(0),
}
}
}
pub enum Source {
/// Input is a JS ArrayBuffer/TypedArray held in the wrapper's `sourceJS`
/// cached slot. We never cache the raw pointer here — it could be detached
/// or (for resizable, which we reject) reallocated. Each use re-fetches:
/// - `doMetadata` (sync, JS thread): `asArrayBuffer` → probe; no copy.
/// - `schedule()` (JS thread): `asArrayBuffer` → `pin()` → hand the
/// fresh slice to the worker; `then()` (JS thread) unpins. The pin
/// only lives for the task, never touches `finalize` (which runs
/// during GC sweep), and only forces `possiblySharedBuffer()`
/// materialisation when actually going off-thread — and that costs no
/// more than the dupe it replaces.
JsBuffer,
/// Owned — Blob inputs (the Blob's store may be sliced/freed independently)
/// and decoded data: URLs.
Owned(Vec<u8>),
/// Owned, NUL-terminated. Read on the worker thread.
Path(ZBox),
/// `Bun.file()`, `Bun.s3()`, an fd-backed Blob — anything whose bytes
/// don't exist until read. We hold a Strong on the JS Blob and, at
/// terminal time, just call its own `.bytes()` (whatever that means for
/// that kind of Blob — file, S3, pipe, slice) and chain the pipeline
/// task off the resulting Promise. After the first read completes the
/// source is swapped to `.owned` so subsequent terminals reuse the bytes.
Blob(Strong),
}
// `Vec<u8>`, `ZString`, and
// `Strong` all implement `Drop`, so no explicit `Drop` body is needed.
// These C++ helpers are
// Image-specific (they pin/adopt typed-array storage for the off-thread
// pipeline) and have no `bun_jsc` wrapper.
unsafe extern "C" {
fn JSC__JSValue__unpinArrayBuffer(v: JSValue);
/// 0 = detached/null, 1 = FastTypedArray (≤~1 KB, GC-movable — dupe),
/// 2 = pinned ArrayBuffer (caller must unpin). For OversizeTypedArray the
/// helper adopts the storage in-place (createAdopted — no byte copy) and
/// pins; once adopted it's detachable, so it MUST be pinned, not borrowed.
fn JSC__JSValue__borrowBytesForOffThread(
v: JSValue,
out_ptr: *mut *const u8,
out_len: *mut usize,
) -> i32;
}
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, strum::IntoStaticStr, strum::EnumString)]
pub enum Fit {
Fill,
Inside,
}
// `pub const Map = bun.ComptimeEnumMap(Fit);` → covered by `strum::EnumString`.
bun_core::comptime_string_map! {
static FIT_MAP: Fit = {
b"fill" => Fit::Fill,
b"inside" => Fit::Inside,
};
}
impl jsc::FromJsEnum for Fit {
fn from_js_value(v: JSValue, global: &JSGlobalObject, prop: &'static str) -> JsResult<Self> {
v.to_enum_from_map(global, prop, &FIT_MAP, "'fill' or 'inside'")
}
}
impl jsc::FromJsEnum for codecs::Filter {
fn from_js_value(v: JSValue, global: &JSGlobalObject, prop: &'static str) -> JsResult<Self> {
v.to_enum_from_map(
global,
prop,
&codecs::FILTER_MAP,
"'box', 'bilinear', 'linear', 'lanczos3', 'mitchell', 'nearest', 'cubic', 'lanczos2', 'mks2013' or 'mks2021'",
)
}
}
#[derive(Clone, Copy)]
pub struct Resize {
pub w: u32,
pub h: u32,
pub filter: codecs::Filter,
pub fit: Fit,
pub without_enlargement: bool,
}
impl Default for Resize {
fn default() -> Self {
Self {
w: 0,
h: 0,
filter: codecs::Filter::Lanczos3,
fit: Fit::Fill,
without_enlargement: false,
}
}
}
/// One slot per operation, not an op list — calling `.resize()` twice
/// overwrites, it doesn't resize twice. This is Sharp's semantics and means
/// the worker snapshot is a plain struct copy with a fixed execution order
/// (`run()` below), no allocation, no "too many ops" edge.
///
/// Execution order matches Sharp: (autoOrient) → rotate → flip/flop → resize
/// → modulate. Rotate precedes resize so the target box is interpreted in
/// upright space; modulate runs last so it operates on the fewest pixels.
#[derive(Clone, Copy, Default)]
pub struct Pipeline {
pub rotate: u16, // 0/90/180/270
pub flip: bool, // vertical
pub flop: bool, // horizontal
pub resize: Option<Resize>,
pub modulate: Option<Modulate>,
/// Output settings from `.jpeg()/.png()/.webp()`. `None` ⇒ re-encode in
/// source format.
pub output: Option<codecs::EncodeOptions>,
}
#[derive(Clone, Copy)]
pub struct Modulate {
/// Multiplier; 1.0 = identity.
pub brightness: f32,
/// 0 = greyscale, 1 = identity, >1 = boost.
pub saturation: f32,
}
impl Default for Modulate {
fn default() -> Self {
Self {
brightness: 1.0,
saturation: 1.0,
}
}
}
/// `@intFromFloat` is safety-checked UB on NaN/±Inf/out-of-range; every
/// number we read from JS goes through this so hostile input throws/clamps
/// instead of aborting. NaN → lo, ±Inf → the matching bound; bounds are f64
/// so the clamp stays in float space.
///
/// Rust `as` already saturates on overflow/NaN, but we keep the explicit
/// clamp so NaN maps to `lo`, not 0.
macro_rules! coerce_int {
($T:ty, $x:expr, $lo:expr, $hi:expr) => {{
let x: f64 = $x;
if x.is_nan() {
($lo) as $T
} else {
x.max($lo).min($hi) as $T
}
}};
}
/// Size cap for `.path` sources, applied at fstat time before reading
/// anything. This is the *encoded* file, not the decoded RGBA — `maxPixels`
/// covers the latter once we have a header. 256 MiB comfortably fits any
/// real-world image (a 268 MP JPEG is ~80 MB) while keeping a single
/// path-driven request from materialising gigabytes before any guard runs.
const MAX_INPUT_FILE_BYTES: u64 = 256 << 20;
// ───────────────────────────── lifecycle ────────────────────────────────────
impl Image {
// No `#[bun_jsc::host_fn]` here — `#[bun_jsc::JsClass]` on the
// struct emits the constructor C-ABI shim; the bare attribute would expand
// to a free-fn call (`constructor(__g, __f)`) that can't resolve in `impl`.
pub fn constructor(
global: &JSGlobalObject,
callframe: &CallFrame,
this_value: JSValue,
) -> JsResult<Box<Image>> {
let args = callframe.arguments();
if args.len() < 1 || args[0].is_undefined_or_null() {
return Err(global.throw_invalid_arguments(format_args!(
"Image() expects a path, ArrayBuffer, TypedArray, Blob or data: URL",
)));
}
from_input_js(
global,
args[0],
if args.len() > 1 {
args[1]
} else {
JSValue::UNDEFINED
},
this_value,
)
}
/// `Bun.file("…").image()` / `Bun.s3("…").image()` / `Blob#image()`. Same
/// allocation as `new Bun.Image(blob, opts)`. Everything that can throw runs
/// BEFORE `toJS()` — once the wrapper exists its `m_ctx` owns the *Image and
/// the generated `~JSImage` will `finalize()` on GC, so a manual `finalize()`
/// after `toJS()` is a double-free. (Contrast `from_input_js` where the
/// codegen constructor only wires `m_ctx` after the fn returns, so its
/// errdefer is safe.)
pub fn from_blob_js(
global: &JSGlobalObject,
blob_value: JSValue,
options: JSValue,
) -> JsResult<JSValue> {
let mut img = Box::<Image>::default();
// errdefer img.finalize() — `Box` drops on `?` automatically.
apply_options(&mut img, global, options)?;
// For Blob receivers `source_from_js` either dupes (in-memory blob) or
// creates a Strong (file/S3); the cached `sourceJS` slot is only used
// for the `.js_buffer` path, which a Blob never produces. The only
// reason `source_from_js` takes `this_value` at all is to set that slot
// for ArrayBuffer inputs — pass `.zero` and assert below.
img.source
.set(source_from_js(global, blob_value, JSValue::ZERO)?);
debug_assert!(!matches!(img.source.get(), Source::JsBuffer));
Ok(img.to_js(global))
}
// Codegen's `host_fn_finalize` calls this via `|b| Image::finalize(b)`
// and requires `fn finalize(self: Box<Self>)`; clippy::boxed_local is a
// false positive on that contract.
#[allow(clippy::boxed_local)]
pub fn finalize(self: Box<Self>) {
self.this_ref.with_mut(|r| r.finalize());
// `source` is dropped by Box drop.
}
pub fn estimated_size(&self) -> usize {
// Only the bytes WE own. .js_buffer is the caller's ArrayBuffer (already
// counted via the cached value slot); the worker's RGBA scratch is
// task-scoped and freed before any GC could observe it.
mem::size_of::<Image>()
+ match self.source.get() {
Source::JsBuffer | Source::Blob(_) => 0,
Source::Owned(b) => b.len(),
Source::Path(p) => p.len(),
}
}
}
fn from_input_js(
global: &JSGlobalObject,
input: JSValue,
options: JSValue,
this_value: JSValue,
) -> JsResult<Box<Image>> {
let mut img = Box::<Image>::default();
// `opt.get` can throw (Proxy/getter); without this the heap-allocated
// *Image and the duplicated source bytes leak. (Handled by `Box` Drop on `?`.)
img.source.set(source_from_js(global, input, this_value)?);
apply_options(&mut img, global, options)?;
Ok(img)
}
fn apply_options(img: &mut Image, global: &JSGlobalObject, opt: JSValue) -> JsResult<()> {
if !opt.is_object() {
return Ok(());
}
if let Some(v) = opt.get(global, "maxPixels")? {
if v.is_number() {
img.max_pixels = coerce_int!(u64, v.as_number(), 0.0, 1e15);
}
}
if let Some(v) = opt.get(global, "autoOrient")? {
img.auto_orient = v.to_boolean();
}
Ok(())
}
fn source_from_js(
global: &JSGlobalObject,
value: JSValue,
this_value: JSValue,
) -> JsResult<Source> {
// String → file path or data:/base64 URL. Everything else → bytes.
if value.is_string() {
let str = bun_core::OwnedString::new(value.to_bun_string(global)?);
let utf8 = str.to_utf8();
let s = utf8.slice();
// `data:[<mime>][;base64],<payload>` — accept any image MIME (we sniff
// anyway) and decode base64 here. Non-base64 data URLs aren't useful
// for image bytes.
if s.starts_with(b"data:") {
let Some(comma) = strings::index_of_char(s, b',') else {
return Err(global.throw_invalid_arguments(format_args!(
"Image(): malformed data: URL (no comma)"
)));
};
let meta = &s[5..comma as usize];
let payload = &s[comma as usize + 1..];
if strings::index_of(meta, b";base64").is_none() {
return Err(global.throw_invalid_arguments(format_args!(
"Image(): only base64 data: URLs are supported",
)));
}
let mut out = vec![0u8; bun_base64::decode_len(payload)];
let r = base64::decode(&mut out, payload);
if r.fail {
return Err(global.throw_invalid_arguments(format_args!(
"Image(): invalid base64 in data: URL"
)));
}
out.truncate(r.written);
return Ok(Source::Owned(out));
}
return Ok(Source::Path(ZBox::from_bytes(s)));
}
if let Some(ab) = value.as_array_buffer(global) {
// A resizable/growable buffer can shrink or reallocate underneath any
// slice we'd take; a SharedArrayBuffer can be mutated by another
// thread while the worker decodes (the codec layer parses the same
// bytes twice — header then body — so a TOCTOU swap can resize the
// implied output behind a guard that's already passed). The worker
// *borrows* the slice (see `pin_for_task`), so this rejection is
// load-bearing — `buf.slice()` is the obvious workaround.
if ab.resizable || ab.shared {
return Err(global.throw_invalid_arguments(format_args!(
"Image(): resizable / shared ArrayBuffer is not supported; pass a fixed-length view (e.g. buf.slice())",
)));
}
// Just remember the JS object — see Source::JsBuffer for why we don't
// cache the pointer or pin here.
js::source_js_set_cached(this_value, global, value);
return Ok(Source::JsBuffer);
}
if let Some(blob) = value.as_class_ref::<Blob>() {
// In-memory blob: dupe its bytes (the store may be sliced/replaced
// independently).
let view = blob.shared_view();
if !view.is_empty() {
return Ok(Source::Owned(view.to_vec()));
}
// Anything with a backing store but no in-memory view yet
// (`Bun.file()`, `Bun.s3()`, fd, …) — keep the JS object and read it
// through ITS OWN `.bytes()` at terminal time, so we inherit whatever
// that store type does (file → ReadFile, S3 → fetch, etc.) without
// knowing about it here.
if blob.store.get().is_some() {
return Ok(Source::Blob(Strong::create(value, global)));
}
}
Err(global.throw_invalid_arguments(format_args!(
"Image() input must be a path string, data: URL, ArrayBuffer, TypedArray or Blob",
)))
}
// ───────────────────────────── chainable ops ────────────────────────────────
impl Image {
/// R-2 helper: read-modify-write the `Cell<Pipeline>` in one shot so each
/// chainable setter stays a single field-write under `&self`.
#[inline]
fn update_pipeline(&self, f: impl FnOnce(&mut Pipeline)) {
let mut p = self.pipeline.get();
f(&mut p);
self.pipeline.set(p);
}
#[bun_jsc::host_fn(method)]
pub fn do_resize(&self, global: &JSGlobalObject, callframe: &CallFrame) -> JsResult<JSValue> {
let args = callframe.arguments();
if args.len() < 1 || !args[0].is_number() {
return Err(
global.throw_invalid_arguments(format_args!("resize(width, height?, options?)"))
);
}
// 0x3FFF² is the max_pixels default; capping each side at 0x3FFFF (≈262k)
// keeps every downstream u32 product in range without a per-stage check.
let mut r = Resize {
w: coerce_int!(u32, args[0].as_number(), 1.0, 0x3FFFF as f64),
// 0 height = preserve aspect ratio (resolved at execute time once the
// source dimensions are known).
h: if args.len() > 1 && args[1].is_number() {
coerce_int!(u32, args[1].as_number(), 0.0, 0x3FFFF as f64)
} else {
0
},
..Default::default()
};
if args.len() > 2 && args[2].is_object() {
let opt = args[2];
if let Some(v) = opt.get_optional_enum::<codecs::Filter>(global, "filter")? {
r.filter = v;
}
if let Some(v) = opt.get_optional_enum::<Fit>(global, "fit")? {
r.fit = v;
}
if let Some(v) = opt.get(global, "withoutEnlargement")? {
r.without_enlargement = v.to_boolean();
}
}
self.update_pipeline(|p| p.resize = Some(r));
Ok(callframe.this())
}
#[bun_jsc::host_fn(method)]
pub fn do_rotate(&self, global: &JSGlobalObject, callframe: &CallFrame) -> JsResult<JSValue> {
let args = callframe.arguments();
if args.len() < 1 || !args[0].is_number() {
return Err(global
.throw_invalid_arguments(format_args!("rotate(degrees) expects 90, 180 or 270")));
}
// coerce_int for the same NaN/Inf/huge-finite reasons as everywhere else;
// ±1e15 is plenty of headroom for "any multiple of 90 a user might pass".
let raw: i64 = coerce_int!(i64, args[0].as_number(), -1e15, 1e15);
let deg: u32 = u32::try_from(raw.rem_euclid(360)).unwrap();
if deg != 0 && deg != 90 && deg != 180 && deg != 270 {
return Err(global.throw_invalid_arguments(format_args!(
"rotate: only multiples of 90 are supported"
)));
}
self.update_pipeline(|p| p.rotate = u16::try_from(deg).expect("int cast"));
Ok(callframe.this())
}
#[bun_jsc::host_fn(method)]
pub fn do_flip(&self, _: &JSGlobalObject, callframe: &CallFrame) -> JsResult<JSValue> {
self.update_pipeline(|p| p.flip = true);
Ok(callframe.this())
}
#[bun_jsc::host_fn(method)]
pub fn do_flop(&self, _: &JSGlobalObject, callframe: &CallFrame) -> JsResult<JSValue> {
self.update_pipeline(|p| p.flop = true);
Ok(callframe.this())
}
#[bun_jsc::host_fn(method)]
pub fn do_modulate(&self, global: &JSGlobalObject, callframe: &CallFrame) -> JsResult<JSValue> {
let args = callframe.arguments();
let mut m: Modulate = self.pipeline.get().modulate.unwrap_or_default();
if args.len() > 0 && args[0].is_object() {
let opt = args[0];
// Clamp finite + bounded so Infinity doesn't reach ModulateImpl as
// f32 +Inf (0×Inf = NaN → static_cast<u8>(NaN) is UB).
if let Some(v) = opt.get(global, "brightness")? {
if v.is_number() {
let x = v.as_number();
m.brightness = if x.is_finite() {
x.clamp(0.0, 1e4) as f32
} else {
1.0
};
}
}
if let Some(v) = opt.get(global, "saturation")? {
if v.is_number() {
let x = v.as_number();
m.saturation = if x.is_finite() {
x.clamp(0.0, 1e4) as f32
} else {
1.0
};
}
}
}
self.update_pipeline(|p| p.modulate = Some(m));
Ok(callframe.this())
}
fn set_format(
&self,
global: &JSGlobalObject,
callframe: &CallFrame,
fmt: codecs::Format,
) -> JsResult<JSValue> {
let mut enc: codecs::EncodeOptions =
self.pipeline
.get()
.output
.unwrap_or_else(|| codecs::EncodeOptions {
format: fmt,
..Default::default()
});
enc.format = fmt;
let args = callframe.arguments();
if args.len() > 0 && args[0].is_object() {
let opt = args[0];
if let Some(q) = opt.get(global, "quality")? {
if q.is_number() {
enc.quality = coerce_int!(u8, q.as_number(), 1.0, 100.0);
}
}
if let Some(l) = opt.get(global, "lossless")? {
enc.lossless = l.to_boolean();
}
if let Some(c) = opt.get(global, "compressionLevel")? {
if c.is_number() {
enc.compression_level = coerce_int!(i8, c.as_number(), 0.0, 9.0);
}
}
if let Some(p) = opt.get(global, "palette")? {
enc.palette = p.to_boolean();
}
if let Some(c) = opt.get(global, "colors")? {
if c.is_number() {
enc.colors = coerce_int!(u16, c.as_number(), 2.0, 256.0);
}
}
if let Some(d) = opt.get(global, "dither")? {
enc.dither = d.to_boolean();
}
if let Some(p) = opt.get(global, "progressive")? {
enc.progressive = p.to_boolean();
}
}
self.update_pipeline(|p| p.output = Some(enc));
Ok(callframe.this())
}
#[bun_jsc::host_fn(method)]
pub fn do_format_jpeg(&self, g: &JSGlobalObject, cf: &CallFrame) -> JsResult<JSValue> {
self.set_format(g, cf, codecs::Format::Jpeg)
}
#[bun_jsc::host_fn(method)]
pub fn do_format_png(&self, g: &JSGlobalObject, cf: &CallFrame) -> JsResult<JSValue> {
self.set_format(g, cf, codecs::Format::Png)
}
#[bun_jsc::host_fn(method)]
pub fn do_format_webp(&self, g: &JSGlobalObject, cf: &CallFrame) -> JsResult<JSValue> {
self.set_format(g, cf, codecs::Format::Webp)
}
#[bun_jsc::host_fn(method)]
pub fn do_format_heic(&self, g: &JSGlobalObject, cf: &CallFrame) -> JsResult<JSValue> {
self.set_format(g, cf, codecs::Format::Heic)
}
#[bun_jsc::host_fn(method)]
pub fn do_format_avif(&self, g: &JSGlobalObject, cf: &CallFrame) -> JsResult<JSValue> {
self.set_format(g, cf, codecs::Format::Avif)
}
}
/// Stable `.code` so callers can branch without parsing the message — and so
/// tests can skip when a system-backend format is unavailable on *this
/// machine* (e.g. AVIF encode on M1/M2, or Windows without the HEIF store
/// extension) without hard-coding which configurations have what.
fn error_code(e: codecs::Error) -> &'static ZStr {
use codecs::Error as E;
match e {
E::UnknownFormat => zstr!("ERR_IMAGE_UNKNOWN_FORMAT"),
E::DecodeFailed => zstr!("ERR_IMAGE_DECODE_FAILED"),
E::EncodeFailed => zstr!("ERR_IMAGE_ENCODE_FAILED"),
E::TooManyPixels => zstr!("ERR_IMAGE_TOO_MANY_PIXELS"),
E::UnsupportedOnPlatform => zstr!("ERR_IMAGE_FORMAT_UNSUPPORTED"),
E::OutOfMemory => zstr!("ERR_OUT_OF_MEMORY"),
}
}
fn error_message(e: codecs::Error) -> &'static ZStr {
use codecs::Error as E;
match e {
E::UnknownFormat => zstr!(
"Image: unrecognised format (expected JPEG, PNG, WebP, GIF, BMP, TIFF, HEIC or AVIF)"
),
E::DecodeFailed => zstr!("Image: decode failed"),
E::EncodeFailed => zstr!("Image: encode failed"),
E::TooManyPixels => zstr!("Image: input exceeds maxPixels limit"),
E::UnsupportedOnPlatform => zstr!(
"Image: format not supported on this machine (HEIC/AVIF/TIFF require the OS codec; AVIF encode needs an AV1 encoder)"
),
E::OutOfMemory => zstr!("Image: out of memory"),
}
}
fn reject_error(global: &JSGlobalObject, e: codecs::Error) -> JSValue {
error_with_code(global, error_code(e), error_message(e))
}
fn error_with_code(global: &JSGlobalObject, code: &ZStr, msg: &ZStr) -> JSValue {
let err = global.create_error_instance(format_args!("{}", bstr::BStr::new(msg.as_bytes())));
let code_js = jsc::bun_string_jsc::create_utf8_for_js(global, code.as_bytes())
.unwrap_or(JSValue::UNDEFINED);
err.put(global, b"code", code_js);
err
}
#[derive(thiserror::Error, Debug, strum::IntoStaticStr)]
enum PinError {
#[error("detached")]
Detached,
}
impl Image {
/// Fresh slice into the input bytes for use ON THE JS THREAD ONLY (re-reads
/// the ArrayBuffer's vector each call so a detach between construction and
/// here surfaces as `None` instead of UAF). For off-thread, see `pin_for_task`.
fn js_thread_bytes(&self, this_value: JSValue, global: &JSGlobalObject) -> Option<&[u8]> {
match self.source.get() {
Source::JsBuffer => js::source_js_get_cached(this_value)
.and_then(|v: JSValue| v.as_array_buffer(global))
.map(|ab| {
// SAFETY: `ArrayBuffer` is a view struct (ptr+len); the
// bytes live in the JS heap, not in `ab` — the returned
// slice borrows the JS heap with `&self`'s lifetime, which
// is sound only on the JS thread. `this_value` keeps the
// buffer alive for this JS-thread call — see fn doc above.
unsafe { &*std::ptr::from_ref::<[u8]>(ab.byte_slice()) }
}),
Source::Owned(b) => Some(b.as_slice()),
Source::Path(_) | Source::Blob(_) => None,
}
}
/// Pin the source ArrayBuffer for the duration of one off-thread task and
/// return a slice that's safe for the worker to read. Unpinned in `then()`.
///
/// We deliberately DON'T copy: the encoded input can be tens of MB and
/// nobody mutates a buffer they just handed to a decoder. The contract is
/// documented and `.shared`/`.resizable` are refused at construction. The
/// codec layer is hardened so a hostile mid-decode mutation degrades to
/// `DecodeFailed`, not OOB/heap-leak — see `codec_jpeg.rs` cropping +
/// post-check, `codec_webp.rs` dim re-check. (If the attacker already runs
/// JS in-process the threat model is moot anyway; the surface that matters
/// is hostile *bytes*, which the codec validation handles.)
fn pin_for_task(
&self,
this_value: JSValue,
_global: &JSGlobalObject,
) -> Result<Input, PinError> {
match self.source.get() {
Source::JsBuffer => {
let Some(v) = js::source_js_get_cached(this_value) else {
return Err(PinError::Detached);
};
// Classify the storage mode WITHOUT promoting it. A fresh
// `new Uint8Array(N)` (the common path — `await res.bytes()`,
// `Buffer.from(file)`) is `OversizeTypedArray`: bytes in
// fastMalloc, no JSArrayBuffer wrapper, can't be detached or
// moved. Calling `possiblySharedBuffer()` on that would
// `slowDownAndWasteMemory()` → copy + allocate a wrapper for
// every input. The classifier returns the slice directly and
// tells us whether anything actually needs pinning.
let mut ptr: *const u8 = core::ptr::null();
let mut len: usize = 0;
// SAFETY: FFI call; out-params are valid pointers to locals.
match unsafe {
JSC__JSValue__borrowBytesForOffThread(v, &raw mut ptr, &raw mut len)
} {
0 => Err(PinError::Detached),
// FastTypedArray (≤ fastSizeLimit elements, GC-movable): tiny
// by definition — dupe instead of forcing JSC to copy via
// tryCreate(span()) + allocate a butterfly.
1 => {
if len == 0 {
Err(PinError::Detached)
} else {
// SAFETY: classifier guarantees `ptr[0..len]` is
// valid for the duration of this call (JS thread).
let copied = unsafe { bun_core::ffi::slice(ptr, len) }.to_vec();
Ok(Input {
copied: Some(copied),
..Default::default()
})
}
}
// Oversize/Wasteful/DataView/JSArrayBuffer: pinned by the
// helper. For Oversize, possiblySharedBuffer() adopts the
// existing fastMalloc storage in-place (zero byte copy);
// pinning then keeps it alive even if JS does `.buffer` →
// `transfer()` while the worker reads.
2 => {
if len == 0 {
// SAFETY: helper pinned `v`; unpin before erroring.
unsafe { JSC__JSValue__unpinArrayBuffer(v) };
Err(PinError::Detached)
} else {
// SAFETY: pinned for the lifetime of the task;
// unpinned in `then()` via `Input::release()`.
let bytes = unsafe { bun_core::ffi::slice(ptr, len) };
Ok(Input {
bytes: bun_ptr::RawSlice::new(bytes),
pinned: v,
..Default::default()
})
}
}
_ => unreachable!(),
}
}
// SAFETY: `Owned` bytes outlive the task because `this_ref` is held
// Strong while pending_tasks > 0 (see `schedule()`).
Source::Owned(b) => Ok(Input {
bytes: bun_ptr::RawSlice::new(b.as_slice()),
..Default::default()
}),
Source::Path(p) => Ok(Input {
path: Some(std::ptr::from_ref::<ZStr>(p.as_zstr())),
..Default::default()
}),
// schedule() peels this off before pin_for_task is reached.
Source::Blob(_) => unreachable!(),
}
}
}
// ───────────────────────── static `Bun.Image.backend` ───────────────────────
//
// `#[bun_jsc::host_fn(getter|setter)]` expands to a `Self`-taking
// shim, but these are *static* class accessors (no receiver). The C-ABI shim
// is emitted by `.classes.ts` codegen (`generated_classes.rs`) and calls them
// as `Image::<fn>(…)`, so they live in an inherent `impl` with the codegen's
// exact arity — including the trailing opaque `PropertyName` it threads
// through but `get_backend` ignores.
impl Image {
pub fn get_backend(global: &JSGlobalObject, _: JSValue, _: PropertyName) -> JsResult<JSValue> {
// `BACKEND` only ever stores a valid `Backend as u8` discriminant
// (`set_backend` round-trips through `Backend`); any other value is
// corruption — trap.
let b = match codecs::BACKEND.load(core::sync::atomic::Ordering::Relaxed) {
0 => codecs::Backend::System,
1 => codecs::Backend::Bun,
n => unreachable!("invalid image Backend {n}"),
};
bun_core::String::static_(<&'static str>::from(&b)).to_js(global)
}
pub fn set_backend(
global: &JSGlobalObject,
_: JSValue,
value: JSValue,
_: PropertyName,
) -> bool {
match value.to_enum::<codecs::Backend>(global, "Bun.Image.backend") {
Ok(b) => {
codecs::BACKEND.store(b as u8, core::sync::atomic::Ordering::Relaxed);
true
}
Err(_) => false,
}
}
// ──────── static `Bun.Image.fromClipboard()` / `.hasClipboardImage()` ───
//
// JS-thread synchronous read of the system clipboard for an image
// representation, returning a fresh `Bun.Image` wrapping the raw container
// bytes. Decode/encode still go through the normal off-thread pipeline;
// only the pasteboard fetch is synchronous, and that's a memcpy of bytes
// the OS already has in-process. `null` ⇔ no image present. Linux returns
// `null` unconditionally — there's no stable native API to dlopen and
// shelling out to `wl-paste`/`xclip` from inside `Bun.Image` is the wrong
// layer.
pub fn from_clipboard(global: &JSGlobalObject, _: &CallFrame) -> JsResult<JSValue> {
// `codecs::system_backend` is a cfg-gated module re-export.
#[cfg(any(target_os = "macos", windows))]
{
use codecs::system_backend;
let bytes = match system_backend::clipboard() {
Ok(Some(b)) => b,
Ok(None) => return Ok(JSValue::NULL),
Err(system_backend::BackendError::OutOfMemory) => {
return Err(global.throw_out_of_memory());
}
// BackendUnavailable (and any other backend error) ⇔ no image present.
Err(_) => return Ok(JSValue::NULL),
};
let img = Box::new(Image {
source: JsCell::new(Source::Owned(bytes)),
..Default::default()
});
return Ok(img.to_js(global));
}
#[cfg(not(any(target_os = "macos", windows)))]
{
let _ = global;
Ok(JSValue::NULL)
}
}
pub fn has_clipboard_image(_: &JSGlobalObject, _: &CallFrame) -> JsResult<JSValue> {
#[cfg(any(target_os = "macos", windows))]
{
return Ok(JSValue::from(codecs::system_backend::has_clipboard_image()));
}
#[cfg(not(any(target_os = "macos", windows)))]
Ok(JSValue::FALSE)
}
/// Monotone counter that increments on every system-wide clipboard write
/// (NSPasteboard.changeCount / GetClipboardSequenceNumber). macOS has no
/// clipboard-change notification, so polling this and calling
/// `hasClipboardImage()` only when it moves is the cheapest hint-UI
/// pattern. `-1` on Linux.
pub fn clipboard_change_count(_: &JSGlobalObject, _: &CallFrame) -> JsResult<JSValue> {
#[cfg(any(target_os = "macos", windows))]
{
return Ok(JSValue::js_number(
codecs::system_backend::clipboard_change_count() as f64,
));
}
#[cfg(not(any(target_os = "macos", windows)))]
Ok(JSValue::js_number(-1.0))
}
}
// ───────────────────────────── getters ──────────────────────────────────────
impl Image {
#[bun_jsc::host_fn(getter)]
pub fn get_width(&self, _: &JSGlobalObject) -> JSValue {
JSValue::js_number(f64::from(self.last_width.get()))
}
#[bun_jsc::host_fn(getter)]
pub fn get_height(&self, _: &JSGlobalObject) -> JSValue {
JSValue::js_number(f64::from(self.last_height.get()))
}
}
// ───────────────────────────── async terminals ──────────────────────────────
impl Image {
#[bun_jsc::host_fn(method)]
pub fn do_metadata(&self, global: &JSGlobalObject, callframe: &CallFrame) -> JsResult<JSValue> {
// Header-only probe is a few dozen byte reads — when the bytes are already
// in memory it's cheaper to do it inline than to bounce off the WorkPool
// (~0.4 ms roundtrip). Path-backed sources still go async for the file I/O.
if let Some(buf) = self.js_thread_bytes(callframe.this(), global) {
match codecs::probe(buf, self.max_pixels) {
Ok(p) => {
let mut w = p.width;
let mut h = p.height;
if self.auto_orient && p.format == codecs::Format::Jpeg {
let t = exif::read_jpeg(buf).transform();
if t.rotate == 90 || t.rotate == 270 {
mem::swap(&mut w, &mut h);
}
}
self.last_width.set(i32::try_from(w).expect("int cast"));
self.last_height.set(i32::try_from(h).expect("int cast"));
let obj = JSValue::create_empty_object(global, 3);
obj.put(global, b"width", JSValue::js_number(f64::from(w)));
obj.put(global, b"height", JSValue::js_number(f64::from(h)));
obj.put(
global,
b"format",
jsc::bun_string_jsc::create_utf8_for_js(
global,
format_name(p.format).as_bytes(),
)?,
);
return Ok(JSPromise::resolved_promise_value(global, obj));
}
// HEIC/AVIF need the system backend → fall through to async.
Err(codecs::Error::UnsupportedOnPlatform) => {}
Err(e) => {
return Ok(JSPromise::rejected_promise(global, reject_error(global, e))
.as_value(global));
}
}
}
self.schedule(
global,
callframe.this(),
Kind::Metadata,
Deliver::Uint8Array,
)
}
#[bun_jsc::host_fn(method)]
pub fn do_bytes(&self, global: &JSGlobalObject, cf: &CallFrame) -> JsResult<JSValue> {
self.schedule(
global,
cf.this(),
Kind::Encode(self.pipeline.get().output),
Deliver::Uint8Array,
)
}
#[bun_jsc::host_fn(method)]
pub fn do_buffer(&self, global: &JSGlobalObject, cf: &CallFrame) -> JsResult<JSValue> {
self.schedule(
global,
cf.this(),
Kind::Encode(self.pipeline.get().output),
Deliver::Buffer,
)
}
#[bun_jsc::host_fn(method)]
pub fn do_blob(&self, global: &JSGlobalObject, cf: &CallFrame) -> JsResult<JSValue> {
self.schedule(
global,
cf.this(),
Kind::Encode(self.pipeline.get().output),
Deliver::Blob,
)
}
#[bun_jsc::host_fn(method)]
pub fn do_to_base64(&self, global: &JSGlobalObject, cf: &CallFrame) -> JsResult<JSValue> {
self.schedule(
global,
cf.this(),
Kind::Encode(self.pipeline.get().output),
Deliver::Base64,
)
}
/// `data:image/{format};base64,{…}`. Same encode as `.toBase64()` plus the
/// MIME prefix, so it drops straight into `<img src>`.
#[bun_jsc::host_fn(method)]
pub fn do_data_url(&self, global: &JSGlobalObject, cf: &CallFrame) -> JsResult<JSValue> {
self.schedule(
global,
cf.this(),
Kind::Encode(self.pipeline.get().output),
Deliver::DataUrl,