@windowkit/appkit 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -1
- package/binding.gyp +4 -1
- package/package.json +2 -2
- package/prebuilds/darwin-arm64/calayers.node +0 -0
- package/prebuilds/darwin-x64/calayers.node +0 -0
- package/src/addon.mm +4 -0
- package/src/backend.mm +235 -22
- package/src/video.mm +709 -0
package/README.md
CHANGED
|
@@ -125,7 +125,7 @@ waits on the UI thread (`test/threaded-verbs.js` covers each row):
|
|
|
125
125
|
|
|
126
126
|
| from a worker | verbs |
|
|
127
127
|
| --- | --- |
|
|
128
|
-
| unchanged, on the calling thread | surfaces, every `ctx*` (`ctxDrawSymbol` included), layouts and fonts, `symbolSize`, `pasteboardTypeForMIME`, `pasteboardTypeInfo`, `contentTypeFor`, `colorSpace` |
|
|
128
|
+
| unchanged, on the calling thread | surfaces and video surfaces, every `ctx*` (`ctxDrawSymbol` included), layouts and fonts, `symbolSize`, `pasteboardTypeForMIME`, `pasteboardTypeInfo`, `contentTypeFor`, `colorSpace` |
|
|
129
129
|
| a command, answering nothing | `initApp`, `setActivationPolicy`, `setAppName`, `activateApp`, `showWindow`, `hideWindow`, `setWindowFrame`, `setWindowTitle`, `setWindowMinMax`, `setWindowIgnoresMouseEvents`, `invalidateWindowShadow`, `destroyWindow2`, `setCursor`, `setMainMenu`, `setDockMenu`, `setDockBadge`, `cancelUserAttention`, `setStatusItem`, `setStatusItemMenu`, `removeStatusItem`, `registerDropTypes`, `setDropResponse`, `pasteboardWriteText`, `pasteboardClear`, `cancelPanel`, `cancelPopUpMenu`; the test posts `postMouseEvent`, `postKeyEvent`, `postAppleEvent`, `postAccessibilityDisplayChange` |
|
|
130
130
|
| a handle at the call | `createWindow2`, followed by `window-created { handle, windowNumber }`; every event about the window, input included, carries `handle`, so `ev.handle === win` |
|
|
131
131
|
| | `windowRootLayer`, allocated with the window |
|
|
@@ -558,6 +558,87 @@ native.ctxSetGlobalAlpha(win, 0.6);
|
|
|
558
558
|
native.ctxDrawSurfaceFaded(win, card, 0, 0, 556, 300, 100, 100, 556, 300, 0.6);
|
|
559
559
|
```
|
|
560
560
|
|
|
561
|
+
## Video surfaces
|
|
562
|
+
|
|
563
|
+
A frame a decoder hands over as bytes — ffmpeg over a pipe, a WASM decoder, an addon —
|
|
564
|
+
goes on the screen the way VideoToolbox's own output does: as a YCbCr IOSurface a plain
|
|
565
|
+
layer shows, converted and scaled by the render server. The CPU's share is the copy in.
|
|
566
|
+
|
|
567
|
+
- **`native.createVideoSurface(widthPx, heightPx, options?)`** → `{ handle, iosurfaceId }`.
|
|
568
|
+
`format` is `'NV12'` (the default: two planes, `420v`, or `420f` with `range: 'full'`)
|
|
569
|
+
or `'BGRA'`. `colorSpace` — `'bt709'` (the default), `'bt601'` or `'bt2020'` (SDR) — and
|
|
570
|
+
`range` — `'video'` (the default) or `'full'` — say what an NV12 surface's numbers mean,
|
|
571
|
+
and go on it as the attachments CoreVideo gives a decoded frame: the YCbCr matrix, the
|
|
572
|
+
primaries and the transfer function, which Core Animation reads. Shown through
|
|
573
|
+
`setLayerContentsIOSurface(layer, iosurfaceId)`, which keeps a colour a surface names
|
|
574
|
+
(or derives from CoreVideo's tags: see below). A new surface is black.
|
|
575
|
+
- **`native.writeVideoSurface(target, format, planes, options?)`** — one frame, `planes`
|
|
576
|
+
an array of Buffers or typed arrays: `'NV12'` (Y, then CbCr pairs), `'I420'` (Y, Cb, Cr)
|
|
577
|
+
or `'BGRA'`, each plane `options.strides[i]` bytes a row (packed by default) and checked
|
|
578
|
+
to hold every row; a 4:2:0 chroma plane is `ceil(width / 2)` by `ceil(height / 2)`. An
|
|
579
|
+
NV12 surface takes NV12, and I420 with its chroma interleaved on the way in; a BGRA
|
|
580
|
+
surface takes BGRA, and YCbCr converted. `target` may also be a **2D surface**
|
|
581
|
+
(`createSurface`, `createSurfaceIOSurface`), for a renderer that draws the frame in its
|
|
582
|
+
own paint order — something is drawn over the video — rather than lifting it onto a
|
|
583
|
+
layer: the frame lands at the surface's top-left, `options.width`/`height` of it (the
|
|
584
|
+
surface's size by default), converted with `options.colorSpace` and `range`. A frame's
|
|
585
|
+
fourth byte is ignored: a frame is opaque.
|
|
586
|
+
- **`native.videoSurfaceIsInUse(handle)`** — whether anything still reads the surface; a
|
|
587
|
+
renderer keeping a ring writes only into one this answers `false` for, and in threaded
|
|
588
|
+
mode `surface-released { id }` names the surface a frame took off a layer.
|
|
589
|
+
- **`native.releaseVideoSurface(handle)`** — free it now; idempotent; a layer showing it
|
|
590
|
+
keeps it until it lets go. Every other verb on a released handle throws.
|
|
591
|
+
- **`native.videoFormats()`** → `{ surfaces: ['NV12', 'BGRA'], frames: ['NV12', 'I420',
|
|
592
|
+
'BGRA'] }`, for a renderer to ask rather than assume.
|
|
593
|
+
|
|
594
|
+
Two things the verbs exist to get right, both measured on screen (`test/video-surface.js`):
|
|
595
|
+
|
|
596
|
+
- **Three planes draw nothing.** A layer shows `420v`, `420f` and `2vuy` surfaces and shows
|
|
597
|
+
`y420`/`f420` as transparent, so an I420 frame is interleaved into NV12, in the copy
|
|
598
|
+
the write makes anyway — 0.27ms at 1080p on an M1 Pro, against 0.07ms for NV12 as it is.
|
|
599
|
+
- **The same colours on a layer, in a bitmap and under `AVPlayerLayer`.** An NV12 surface
|
|
600
|
+
is named the colour space CoreVideo makes of its tags, and `setLayerContentsIOSurface`
|
|
601
|
+
names one the same way for a tagged surface it is handed by id. Shown with the tags
|
|
602
|
+
alone, Core Animation linearises a frame tagged BT.709 throughout with the exact 709
|
|
603
|
+
curve, where `AVPlayerLayer` — the platform's player — VideoToolbox's pixel transfer
|
|
604
|
+
and Core Image all use Apple's 1.961 gamma: a video-range grey of Y′=50 was sRGB 55 on
|
|
605
|
+
such a layer and 44 everywhere else. Named, a frame on a layer, the same frame
|
|
606
|
+
converted into a bitmap by VideoToolbox (about 1ms at 1080p) and the player showing it
|
|
607
|
+
agree to within a level or two. What cannot match is gamut: a layer keeps a 2020
|
|
608
|
+
colour outside sRGB on a wide-gamut panel, and an sRGB bitmap clips it.
|
|
609
|
+
|
|
610
|
+
## Text: at a display's scale
|
|
611
|
+
|
|
612
|
+
A text verb's size is the caller's pixels, and a renderer that draws in device pixels hands
|
|
613
|
+
over device pixels: a 13px label on a 2x display is 26. CoreText reads some of a face's data
|
|
614
|
+
by point size, though — the optical size and tracking San Francisco is set at, the tracking
|
|
615
|
+
Apple Color Emoji's `trak` table adds below 29pt — so a font made at 26 is San Francisco as
|
|
616
|
+
it is set at 26pt, 8% narrower than AppKit sets the 13pt label, and a 19px emoji is 1em wide
|
|
617
|
+
where it is 23pt at 19pt. Faces with no such data (Helvetica, Menlo) measure the same either
|
|
618
|
+
way.
|
|
619
|
+
|
|
620
|
+
- **`scale`** — the display's backing scale, as a `matchFont` option and a third argument
|
|
621
|
+
to `cgFontWithSize(cg, size, scale)` and `fontByPostScriptName(name, size, scale)`. The
|
|
622
|
+
font is made at `size / scale` points under a matrix that scales it by `scale`, so CoreText
|
|
623
|
+
reads the face at its point size, and every verb answers in the caller's pixels as before:
|
|
624
|
+
metrics, advances, `fontShapeText`'s runs, a layout's lines, runs, carets and hit testing,
|
|
625
|
+
and `drawLayout`, `ctxDrawGlyphs`, `drawLayoutGradient` and `layoutCoverage` draw it there.
|
|
626
|
+
`fontMetrics(font).size` is the size asked for. A copy — `fontWithSize`, variations,
|
|
627
|
+
features, a `fontFallbackFor` face, a face a layout substitutes — keeps the scale. Absent
|
|
628
|
+
or 1, nothing changes.
|
|
629
|
+
|
|
630
|
+
Two answers are the scaled face's own rather than the point-size face's times the scale. An
|
|
631
|
+
emoji's advance: CoreText rounds a bitmap glyph's to a whole pixel of the font it is set in,
|
|
632
|
+
a whole point at 1x and half of one at 2x, so a 19px emoji is 45 pixels at 2x where the
|
|
633
|
+
point-size face's 23 points are 46. And the system face's `postScriptName` is
|
|
634
|
+
`.SFNS-Regular`, CoreText's name for it, where NSFont calls the unscaled one by its alias,
|
|
635
|
+
`.AppleSystemUIFont`.
|
|
636
|
+
|
|
637
|
+
```js
|
|
638
|
+
// 13px at 2x: San Francisco as AppKit sets 13pt, measured in device pixels
|
|
639
|
+
const label = native.matchFont({ families: ['system-ui'], size: 26, scale: 2 });
|
|
640
|
+
```
|
|
641
|
+
|
|
561
642
|
## Text: letter spacing and OpenType features
|
|
562
643
|
|
|
563
644
|
The text verbs a renderer lays paragraphs out and shapes glyph runs with —
|
package/binding.gyp
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
"src/notifications.mm",
|
|
10
10
|
"src/calendars.mm",
|
|
11
11
|
"src/screencolor.mm",
|
|
12
|
-
"src/threaded.mm"
|
|
12
|
+
"src/threaded.mm",
|
|
13
|
+
"src/video.mm"
|
|
13
14
|
],
|
|
14
15
|
"include_dirs": [
|
|
15
16
|
"<!@(node -p \"require('node-addon-api').include\")"
|
|
@@ -28,6 +29,8 @@
|
|
|
28
29
|
"-framework CoreGraphics",
|
|
29
30
|
"-framework ImageIO",
|
|
30
31
|
"-framework IOSurface",
|
|
32
|
+
"-framework CoreVideo",
|
|
33
|
+
"-framework VideoToolbox",
|
|
31
34
|
"-framework UniformTypeIdentifiers",
|
|
32
35
|
"-framework AVFoundation",
|
|
33
36
|
"-framework CoreLocation",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@windowkit/appkit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.0",
|
|
4
4
|
"description": "Retained-mode AppKit backend for Node.js: Core Animation (CALayer) layer trees, CoreText layout and drawing, IOSurface presentation, NSMenu, and native control bezels — the macOS half of react-x11.",
|
|
5
5
|
"author": "Andrey Sidorov <andrey.sidorov@gmail.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"install": "node scripts/install.js",
|
|
44
44
|
"build": "node-gyp rebuild",
|
|
45
45
|
"demo": "node demo/demo.js",
|
|
46
|
-
"test": "node test/app-lifecycle.js && node test/animation.js && node test/layer-transform.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/popup-menu.js && node test/surface-blit.js && node test/surface-faded.js && node test/surface-colorspace.js && node test/round-rect-xy.js && node test/control-bezels.js && node test/text-features.js && node test/font-from-data.js && node test/text-coverage.js && node test/text-typesetter.js && node test/text-line-height.js && node test/text-line-width.js && node test/symbols.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.js && node test/notifications.js && node test/threaded.js && node test/threaded-verbs.js && node test/threaded-frames.js && node test/threaded-resize.js && node test/ending-worker.js && node test/live-resize.js && node test/activation-policy.js"
|
|
46
|
+
"test": "node test/app-lifecycle.js && node test/animation.js && node test/layer-transform.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/popup-menu.js && node test/surface-blit.js && node test/surface-faded.js && node test/surface-colorspace.js && node test/video-surface.js && node test/round-rect-xy.js && node test/control-bezels.js && node test/text-features.js && node test/font-from-data.js && node test/text-coverage.js && node test/text-typesetter.js && node test/text-line-height.js && node test/text-line-width.js && node test/text-scale.js && node test/symbols.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.js && node test/notifications.js && node test/threaded.js && node test/threaded-verbs.js && node test/threaded-frames.js && node test/threaded-resize.js && node test/ending-worker.js && node test/live-resize.js && node test/activation-policy.js"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"node-addon-api": "^8.3.0"
|
|
Binary file
|
|
Binary file
|
package/src/addon.mm
CHANGED
|
@@ -1718,6 +1718,9 @@ void InitScreenColor(Napi::Env env, Napi::Object exports);
|
|
|
1718
1718
|
// src/threaded.mm — threaded mode: runMain parks the main thread in
|
|
1719
1719
|
// [NSApp run], commands in through the main run loop, events out in batches.
|
|
1720
1720
|
void InitThreaded(Napi::Env env, Napi::Object exports);
|
|
1721
|
+
// src/video.mm — video surfaces: a YCbCr or BGRA IOSurface a layer shows
|
|
1722
|
+
// as it is, frames written into it, and frames converted into a surface.
|
|
1723
|
+
void InitVideo(Napi::Env env, Napi::Object exports);
|
|
1721
1724
|
|
|
1722
1725
|
static Napi::Object Init(Napi::Env env, Napi::Object exports) {
|
|
1723
1726
|
#define FN(js, fn) exports.Set(js, Napi::Function::New(env, fn))
|
|
@@ -1764,6 +1767,7 @@ static Napi::Object Init(Napi::Env env, Napi::Object exports) {
|
|
|
1764
1767
|
InitCalendars(env, exports);
|
|
1765
1768
|
InitScreenColor(env, exports);
|
|
1766
1769
|
InitThreaded(env, exports);
|
|
1770
|
+
InitVideo(env, exports);
|
|
1767
1771
|
return exports;
|
|
1768
1772
|
}
|
|
1769
1773
|
|
package/src/backend.mm
CHANGED
|
@@ -1604,6 +1604,22 @@ static CALSurface* SurfaceFrom(Napi::Value v) {
|
|
|
1604
1604
|
return s;
|
|
1605
1605
|
}
|
|
1606
1606
|
|
|
1607
|
+
// A 2D surface's bitmap, for video.mm's writeVideoSurface: false, with a
|
|
1608
|
+
// JS error pending, when `v` is not a live surface handle.
|
|
1609
|
+
struct CALSurfaceBits {
|
|
1610
|
+
uint8_t* data;
|
|
1611
|
+
size_t width, height, bytesPerRow;
|
|
1612
|
+
};
|
|
1613
|
+
bool CALSurfaceBitmap(Napi::Value v, CALSurfaceBits* out) {
|
|
1614
|
+
CALSurface* s = SurfaceFrom(v);
|
|
1615
|
+
if (!s) return false;
|
|
1616
|
+
out->data = (uint8_t*)CGBitmapContextGetData(s->ctx);
|
|
1617
|
+
out->width = s->width;
|
|
1618
|
+
out->height = s->height;
|
|
1619
|
+
out->bytesPerRow = CGBitmapContextGetBytesPerRow(s->ctx);
|
|
1620
|
+
return true;
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1607
1623
|
// For the fire-and-forget drawing verbs: the context to draw into, or a
|
|
1608
1624
|
// scratch bitmap when the surface is released (the error is already
|
|
1609
1625
|
// pending; the stroke lands nowhere anyone looks).
|
|
@@ -1661,8 +1677,12 @@ static Napi::Value CreateSurface(const Napi::CallbackInfo& info) {
|
|
|
1661
1677
|
// A surface this bridge draws into is named sRGB whatever it said before
|
|
1662
1678
|
// (`keep` false): what is in it is what an sRGB context wrote. One it is
|
|
1663
1679
|
// only handed to show (setLayerContentsIOSurface — a GL target, another
|
|
1664
|
-
// process's buffer) keeps a space its producer named, and is
|
|
1665
|
-
// sRGB, like everything else here, when it names none.
|
|
1680
|
+
// process's buffer, a video frame) keeps a space its producer named, and is
|
|
1681
|
+
// taken to be sRGB, like everything else here, when it names none. A video
|
|
1682
|
+
// frame says what it is the way CoreVideo writes a decoded buffer's
|
|
1683
|
+
// attachments onto its IOSurface — matrix, primaries, transfer function —
|
|
1684
|
+
// and is named the colour space those make (video.mm says why).
|
|
1685
|
+
bool CALNameVideoColorSpace(IOSurfaceRef ios);
|
|
1666
1686
|
void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep) {
|
|
1667
1687
|
static const CFPropertyListRef srgb = [] {
|
|
1668
1688
|
CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
|
|
@@ -1678,6 +1698,8 @@ void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep) {
|
|
|
1678
1698
|
CFRelease(named);
|
|
1679
1699
|
return;
|
|
1680
1700
|
}
|
|
1701
|
+
// a video frame's tags, named as the colour space they make (video.mm)
|
|
1702
|
+
if (CALNameVideoColorSpace(ios)) return;
|
|
1681
1703
|
}
|
|
1682
1704
|
IOSurfaceSetValue(ios, kIOSurfaceColorSpace, srgb);
|
|
1683
1705
|
}
|
|
@@ -4649,7 +4671,60 @@ static NSFontWeight FontWeightFromCss(double weight) {
|
|
|
4649
4671
|
return NSFontWeightBlack;
|
|
4650
4672
|
}
|
|
4651
4673
|
|
|
4652
|
-
//
|
|
4674
|
+
// --- a font at a display's scale ---------------------------------------------
|
|
4675
|
+
//
|
|
4676
|
+
// A size here is in the caller's pixels, and on a Retina display those are
|
|
4677
|
+
// device pixels: a 13px label is 26. A font made at 26 is a 26pt font to
|
|
4678
|
+
// CoreText, which reads some of a face's data by point size — the optical
|
|
4679
|
+
// size and tracking San Francisco is set at, the tracking Apple Color Emoji's
|
|
4680
|
+
// trak table adds below 29pt — so the label was set as SF is at 26pt, 8%
|
|
4681
|
+
// narrower than AppKit sets it at 13, and a 19px emoji was 1em wide where it
|
|
4682
|
+
// is 23pt at 19pt. Faces with no such data measure the same either way.
|
|
4683
|
+
//
|
|
4684
|
+
// So a font may be made at a `scale`: at size / scale points, under a matrix
|
|
4685
|
+
// that scales it by `scale`. CoreText reads the face at its point size and
|
|
4686
|
+
// answers in the caller's pixels — metrics, advances, bounds, a line's width,
|
|
4687
|
+
// a caret's offset — through the matrix. Two things it does not take through
|
|
4688
|
+
// it, and every reader of them here goes through the helpers below: a run's
|
|
4689
|
+
// glyph origins, which are in text space, before the font matrix
|
|
4690
|
+
// (BRunPositions); and a bitmap glyph, which CoreText draws at the font's
|
|
4691
|
+
// point size whatever its matrix (BDrawGlyphsAtScale). A copy of a scaled
|
|
4692
|
+
// font — another size, variations, features, a fallback face — keeps the
|
|
4693
|
+
// scale. A font made without one has the identity matrix, and nothing here
|
|
4694
|
+
// changes for it.
|
|
4695
|
+
|
|
4696
|
+
/** The scale a font was made at: its matrix's, or 1. */
|
|
4697
|
+
static double BFontScale(CTFontRef font) {
|
|
4698
|
+
if (!font) return 1;
|
|
4699
|
+
const CGAffineTransform m = CTFontGetMatrix(font);
|
|
4700
|
+
return m.a > 0 && m.a == m.d && m.b == 0 && m.c == 0 && m.tx == 0 &&
|
|
4701
|
+
m.ty == 0
|
|
4702
|
+
? m.a
|
|
4703
|
+
: 1;
|
|
4704
|
+
}
|
|
4705
|
+
|
|
4706
|
+
/** A scale argument: a finite number above 0, else 1. */
|
|
4707
|
+
static double BScaleOf(Napi::Value v) {
|
|
4708
|
+
if (!v.IsNumber()) return 1;
|
|
4709
|
+
const double scale = v.As<Napi::Number>().DoubleValue();
|
|
4710
|
+
return scale > 0 && std::isfinite(scale) ? scale : 1;
|
|
4711
|
+
}
|
|
4712
|
+
|
|
4713
|
+
/** `font` (owned, released) as the same face under the matrix of `scale`,
|
|
4714
|
+
* at the point size it already has. */
|
|
4715
|
+
static CTFontRef BAtScale(CTFontRef font, double scale) {
|
|
4716
|
+
if (!font || scale == 1) return font;
|
|
4717
|
+
const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
|
|
4718
|
+
CTFontRef scaled = CTFontCreateCopyWithAttributes(font, 0, &m, NULL);
|
|
4719
|
+
if (!scaled) return font;
|
|
4720
|
+
CFRelease(font);
|
|
4721
|
+
return scaled;
|
|
4722
|
+
}
|
|
4723
|
+
|
|
4724
|
+
// matchFont({ families: [..], size, weight (100-900), italic, scale? })
|
|
4725
|
+
// -> font handle
|
|
4726
|
+
// `size` is in the caller's pixels; `scale`, the display's, makes the font
|
|
4727
|
+
// at size / scale points under a matrix of `scale` (see above).
|
|
4653
4728
|
static NSFont* ResolveFamily(NSString* family, double size, double weight,
|
|
4654
4729
|
bool italic) {
|
|
4655
4730
|
NSFontWeight w = FontWeightFromCss(weight);
|
|
@@ -4711,7 +4786,8 @@ static NSFont* ResolveFamily(NSString* family, double size, double weight,
|
|
|
4711
4786
|
static Napi::Value MatchFont(const Napi::CallbackInfo& info) {
|
|
4712
4787
|
Napi::Env env = info.Env();
|
|
4713
4788
|
Napi::Object o = info[0].As<Napi::Object>();
|
|
4714
|
-
double
|
|
4789
|
+
const double scale = BScaleOf(o.Get("scale"));
|
|
4790
|
+
double size = BNumOr(o, "size", 14) / scale;
|
|
4715
4791
|
double weight = BNumOr(o, "weight", 400);
|
|
4716
4792
|
bool italic = BBoolOr(o, "italic", false);
|
|
4717
4793
|
NSFont* font = nil;
|
|
@@ -4726,9 +4802,18 @@ static Napi::Value MatchFont(const Napi::CallbackInfo& info) {
|
|
|
4726
4802
|
NSFontWeight w = weight >= 550 ? NSFontWeightSemibold : NSFontWeightRegular;
|
|
4727
4803
|
font = [NSFont systemFontOfSize:size weight:w];
|
|
4728
4804
|
}
|
|
4805
|
+
if (scale != 1 && font) {
|
|
4806
|
+
CTFontRef scaled =
|
|
4807
|
+
BAtScale((CTFontRef)CFBridgingRetain(font), scale);
|
|
4808
|
+
font = (__bridge_transfer NSFont*)scaled;
|
|
4809
|
+
}
|
|
4729
4810
|
return BWrapRetained(env, font);
|
|
4730
4811
|
}
|
|
4731
4812
|
|
|
4813
|
+
// fontMetrics(font) -> { ascent, descent, leading, capHeight, xHeight, size,
|
|
4814
|
+
// familyName, postScriptName }
|
|
4815
|
+
// In the caller's pixels, a scaled font's included: `size` is the one the
|
|
4816
|
+
// font was asked for.
|
|
4732
4817
|
static Napi::Value FontMetrics(const Napi::CallbackInfo& info) {
|
|
4733
4818
|
Napi::Env env = info.Env();
|
|
4734
4819
|
NSFont* font = BDeref<NSFont*>(info[0]);
|
|
@@ -4739,7 +4824,7 @@ static Napi::Value FontMetrics(const Napi::CallbackInfo& info) {
|
|
|
4739
4824
|
r.Set("leading", CTFontGetLeading(ct));
|
|
4740
4825
|
r.Set("capHeight", CTFontGetCapHeight(ct));
|
|
4741
4826
|
r.Set("xHeight", CTFontGetXHeight(ct));
|
|
4742
|
-
r.Set("size", CTFontGetSize(ct));
|
|
4827
|
+
r.Set("size", CTFontGetSize(ct) * BFontScale(ct));
|
|
4743
4828
|
r.Set("familyName", font.familyName ? font.familyName.UTF8String : "");
|
|
4744
4829
|
r.Set("postScriptName", font.fontName.UTF8String);
|
|
4745
4830
|
return r;
|
|
@@ -4783,6 +4868,71 @@ static bool BCheckFontArg(const Napi::CallbackInfo& info, const char* fn) {
|
|
|
4783
4868
|
return false;
|
|
4784
4869
|
}
|
|
4785
4870
|
|
|
4871
|
+
static CTFontRef BRunFont(CTRunRef run) {
|
|
4872
|
+
return (CTFontRef)CFDictionaryGetValue(CTRunGetAttributes(run),
|
|
4873
|
+
kCTFontAttributeName);
|
|
4874
|
+
}
|
|
4875
|
+
|
|
4876
|
+
// A run's glyph origins from its line's origin, y up, in the caller's pixels.
|
|
4877
|
+
// CTRunGetPositions answers in text space, before the font matrix, where
|
|
4878
|
+
// everything else CoreText measures of a scaled font has the matrix applied;
|
|
4879
|
+
// so a scaled run's origins are multiplied by its scale here. A line set in
|
|
4880
|
+
// faces of one scale, which is every line a caller makes, is in one space.
|
|
4881
|
+
static void BRunPositions(CTRunRef run, std::vector<CGPoint>* out) {
|
|
4882
|
+
const CFIndex count = CTRunGetGlyphCount(run);
|
|
4883
|
+
out->resize(count > 0 ? (size_t)count : 0);
|
|
4884
|
+
if (count <= 0) return;
|
|
4885
|
+
CTRunGetPositions(run, CFRangeMake(0, 0), out->data());
|
|
4886
|
+
const double scale = BFontScale(BRunFont(run));
|
|
4887
|
+
if (scale == 1) return;
|
|
4888
|
+
for (CGPoint& p : *out) {
|
|
4889
|
+
p.x *= scale;
|
|
4890
|
+
p.y *= scale;
|
|
4891
|
+
}
|
|
4892
|
+
}
|
|
4893
|
+
|
|
4894
|
+
// A scaled font as its point-size face: the same font with the identity
|
|
4895
|
+
// matrix. Kept, because a terminal draws its runs every frame. +1.
|
|
4896
|
+
static CTFontRef BAtPointSize(CTFontRef font) {
|
|
4897
|
+
static NSCache* kept = [[NSCache alloc] init];
|
|
4898
|
+
id key = (__bridge id)font;
|
|
4899
|
+
id hit = [kept objectForKey:key];
|
|
4900
|
+
if (!hit) {
|
|
4901
|
+
const CGAffineTransform identity = CGAffineTransformIdentity;
|
|
4902
|
+
CTFontRef plain = CTFontCreateCopyWithAttributes(font, 0, &identity, NULL);
|
|
4903
|
+
if (!plain) return (CTFontRef)CFRetain(font);
|
|
4904
|
+
hit = (__bridge_transfer id)plain;
|
|
4905
|
+
[kept setObject:hit forKey:key];
|
|
4906
|
+
}
|
|
4907
|
+
return (CTFontRef)CFBridgingRetain(hit);
|
|
4908
|
+
}
|
|
4909
|
+
|
|
4910
|
+
// A scaled font's glyphs drawn the way AppKit draws text to a Retina backing
|
|
4911
|
+
// store: the face at its point size, under a CTM scaled by the scale. Drawn
|
|
4912
|
+
// through the font's matrix instead, an outline came out right and a bitmap
|
|
4913
|
+
// glyph — Apple Color Emoji's — at the font's point size, so an emoji was
|
|
4914
|
+
// half its size at 2x. `origins` are from `at`, in the caller's pixels, y up,
|
|
4915
|
+
// as BRunPositions answers them; `at` is in the context's user space, and the
|
|
4916
|
+
// text matrix is the y-flip every draw here sets.
|
|
4917
|
+
static void BDrawGlyphsAtScale(CGContextRef ctx, CTFontRef font,
|
|
4918
|
+
const CGGlyph* glyphs, const CGPoint* origins,
|
|
4919
|
+
size_t count, CGPoint at) {
|
|
4920
|
+
if (count == 0) return;
|
|
4921
|
+
const double scale = BFontScale(font);
|
|
4922
|
+
std::vector<CGPoint> points(count);
|
|
4923
|
+
for (size_t i = 0; i < count; i++) {
|
|
4924
|
+
points[i] = CGPointMake(origins[i].x / scale, origins[i].y / scale);
|
|
4925
|
+
}
|
|
4926
|
+
CTFontRef plain = BAtPointSize(font);
|
|
4927
|
+
CGContextSaveGState(ctx);
|
|
4928
|
+
CGContextTranslateCTM(ctx, at.x, at.y);
|
|
4929
|
+
CGContextScaleCTM(ctx, scale, scale);
|
|
4930
|
+
CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
|
|
4931
|
+
CTFontDrawGlyphs(plain, glyphs, points.data(), (CFIndex)count, ctx);
|
|
4932
|
+
CGContextRestoreGState(ctx);
|
|
4933
|
+
CFRelease(plain);
|
|
4934
|
+
}
|
|
4935
|
+
|
|
4786
4936
|
// One code point -> its UTF-16 form. False for a surrogate or an
|
|
4787
4937
|
// out-of-range value.
|
|
4788
4938
|
static bool BUtf16ForCodepoint(uint32_t cp, unichar out[2], CFIndex* len) {
|
|
@@ -5027,7 +5177,8 @@ static Napi::Value FontFallbackFor(const Napi::CallbackInfo& info) {
|
|
|
5027
5177
|
// substitution — fontFallbackFor's answer, a fontShapeText run's font — has
|
|
5028
5178
|
// no family to re-match by, and asking the cascade again at the new size is
|
|
5029
5179
|
// a different question with a possibly different answer. This is how such a
|
|
5030
|
-
// face answers metrics and advances at every size, as itself.
|
|
5180
|
+
// face answers metrics and advances at every size, as itself. `size` is in
|
|
5181
|
+
// the caller's pixels, and a scaled font's copy keeps its scale.
|
|
5031
5182
|
static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
|
|
5032
5183
|
Napi::Env env = info.Env();
|
|
5033
5184
|
if (!BCheckFontArg(info, "fontWithSize")) return env.Undefined();
|
|
@@ -5037,8 +5188,11 @@ static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
|
|
|
5037
5188
|
.ThrowAsJavaScriptException();
|
|
5038
5189
|
return env.Undefined();
|
|
5039
5190
|
}
|
|
5040
|
-
CTFontRef
|
|
5041
|
-
|
|
5191
|
+
CTFontRef font = BFontFrom(info[0]);
|
|
5192
|
+
const double scale = BFontScale(font);
|
|
5193
|
+
const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
|
|
5194
|
+
CTFontRef sized =
|
|
5195
|
+
CTFontCreateCopyWithAttributes(font, (CGFloat)(size / scale), &m, NULL);
|
|
5042
5196
|
if (!sized) return env.Null();
|
|
5043
5197
|
return Napi::External<void>::New(env, (void*)sized, [](Napi::Env, void* d) {
|
|
5044
5198
|
CFRelease(d);
|
|
@@ -5094,7 +5248,7 @@ static Napi::Value FontShapeText(const Napi::CallbackInfo& info) {
|
|
|
5094
5248
|
std::vector<CGPoint> positions((size_t)count);
|
|
5095
5249
|
std::vector<CGSize> advances((size_t)count);
|
|
5096
5250
|
CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
|
|
5097
|
-
|
|
5251
|
+
BRunPositions(run, &positions);
|
|
5098
5252
|
CTRunGetAdvances(run, CFRangeMake(0, 0), advances.data());
|
|
5099
5253
|
CFDictionaryRef rattrs = CTRunGetAttributes(run);
|
|
5100
5254
|
CTFontRef rfont =
|
|
@@ -5192,27 +5346,33 @@ static Napi::Value FontFromData(const Napi::CallbackInfo& info) {
|
|
|
5192
5346
|
return r;
|
|
5193
5347
|
}
|
|
5194
5348
|
|
|
5195
|
-
// cgFontWithSize(cgExternal, size) -> CTFont handle (what layouts
|
|
5349
|
+
// cgFontWithSize(cgExternal, size, scale?) -> CTFont handle (what layouts
|
|
5350
|
+
// take), at a scale as matchFont makes one
|
|
5196
5351
|
static Napi::Value CgFontWithSize(const Napi::CallbackInfo& info) {
|
|
5197
5352
|
Napi::Env env = info.Env();
|
|
5198
5353
|
CGFontRef cg = (CGFontRef)info[0].As<Napi::External<void>>().Data();
|
|
5199
5354
|
double size = info[1].As<Napi::Number>().DoubleValue();
|
|
5200
|
-
|
|
5355
|
+
const double scale = BScaleOf(info[2]);
|
|
5356
|
+
const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
|
|
5357
|
+
CTFontRef ct = CTFontCreateWithGraphicsFont(cg, size / scale,
|
|
5358
|
+
scale == 1 ? NULL : &m, NULL);
|
|
5201
5359
|
if (!ct) return env.Null();
|
|
5202
5360
|
return Napi::External<void>::New(env, (void*)ct, [](Napi::Env, void* d) {
|
|
5203
5361
|
CFRelease(d);
|
|
5204
5362
|
});
|
|
5205
5363
|
}
|
|
5206
5364
|
|
|
5207
|
-
// fontByPostScriptName(name, size) -> CTFont handle or null
|
|
5208
|
-
//
|
|
5209
|
-
// the next route.
|
|
5365
|
+
// fontByPostScriptName(name, size, scale?) -> CTFont handle or null, at a
|
|
5366
|
+
// scale as matchFont makes one. Exact: a fallback answer (a substituted
|
|
5367
|
+
// face) reads as null so the caller can try the next route.
|
|
5210
5368
|
static Napi::Value FontByPostScriptName(const Napi::CallbackInfo& info) {
|
|
5211
5369
|
Napi::Env env = info.Env();
|
|
5212
5370
|
NSString* name = BToNSString(info[0]);
|
|
5213
5371
|
double size = info[1].As<Napi::Number>().DoubleValue();
|
|
5214
|
-
|
|
5215
|
-
|
|
5372
|
+
const double scale = BScaleOf(info[2]);
|
|
5373
|
+
const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
|
|
5374
|
+
CTFontRef ct = CTFontCreateWithName((__bridge CFStringRef)name,
|
|
5375
|
+
size / scale, scale == 1 ? NULL : &m);
|
|
5216
5376
|
if (!ct) return env.Null();
|
|
5217
5377
|
CFStringRef got = CTFontCopyPostScriptName(ct);
|
|
5218
5378
|
bool exact = got && [(__bridge NSString*)got isEqualToString:name];
|
|
@@ -5404,6 +5564,9 @@ struct CALLine {
|
|
|
5404
5564
|
descent = 0;
|
|
5405
5565
|
long start = 0, end = 0; // UTF-16 units
|
|
5406
5566
|
bool hardBreak = false; // the line ends with a newline it owns
|
|
5567
|
+
// a run of bitmap glyphs in a scaled face, which drawLayout draws apart
|
|
5568
|
+
// (BDrawGlyphsAtScale)
|
|
5569
|
+
bool bitmapsAtScale = false;
|
|
5407
5570
|
std::vector<CALRun> runs;
|
|
5408
5571
|
};
|
|
5409
5572
|
|
|
@@ -5745,6 +5908,14 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
|
|
|
5745
5908
|
CTRunGetPositions(run, CFRangeMake(0, 1), &first);
|
|
5746
5909
|
rx = first.x;
|
|
5747
5910
|
}
|
|
5911
|
+
// in text space, before a scaled face's matrix (BRunPositions)
|
|
5912
|
+
CTFontRef rfont = BRunFont(run);
|
|
5913
|
+
const double rscale = BFontScale(rfont);
|
|
5914
|
+
rx *= rscale;
|
|
5915
|
+
if (rscale != 1 &&
|
|
5916
|
+
(CTFontGetSymbolicTraits(rfont) & kCTFontTraitColorGlyphs)) {
|
|
5917
|
+
L.bitmapsAtScale = true;
|
|
5918
|
+
}
|
|
5748
5919
|
}
|
|
5749
5920
|
CALRun R;
|
|
5750
5921
|
R.x = rx;
|
|
@@ -5855,9 +6026,40 @@ static Napi::Value DrawLayout(const Napi::CallbackInfo& info) {
|
|
|
5855
6026
|
// per glyph run. Standard recipe: flip the text matrix, position each
|
|
5856
6027
|
// line at its baseline in the flipped space.
|
|
5857
6028
|
CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
|
|
6029
|
+
std::vector<CGPoint> positions;
|
|
5858
6030
|
for (const CALLine& L : layout->lines) {
|
|
5859
|
-
|
|
5860
|
-
|
|
6031
|
+
if (!L.bitmapsAtScale) {
|
|
6032
|
+
CGContextSetTextPosition(ctx, x + L.x, y + L.baseline);
|
|
6033
|
+
CTLineDraw(L.line, ctx);
|
|
6034
|
+
continue;
|
|
6035
|
+
}
|
|
6036
|
+
// a line with a scaled face's bitmap glyphs in it is drawn a run at a
|
|
6037
|
+
// time, and a scaled run at its face's point size under a scaled CTM:
|
|
6038
|
+
// CTRunDraw, unlike CTLineDraw, does not draw through the font matrix
|
|
6039
|
+
// either, outlines included
|
|
6040
|
+
CFArrayRef runs = CTLineGetGlyphRuns(L.line);
|
|
6041
|
+
for (CFIndex ri = 0; ri < CFArrayGetCount(runs); ri++) {
|
|
6042
|
+
CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, ri);
|
|
6043
|
+
CTFontRef font = BRunFont(run);
|
|
6044
|
+
if (!font || BFontScale(font) == 1) {
|
|
6045
|
+
CGContextSetTextPosition(ctx, x + L.x, y + L.baseline);
|
|
6046
|
+
CTRunDraw(run, ctx, CFRangeMake(0, 0));
|
|
6047
|
+
continue;
|
|
6048
|
+
}
|
|
6049
|
+
const CFIndex count = CTRunGetGlyphCount(run);
|
|
6050
|
+
if (count <= 0) continue;
|
|
6051
|
+
std::vector<CGGlyph> glyphs((size_t)count);
|
|
6052
|
+
CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
|
|
6053
|
+
BRunPositions(run, &positions);
|
|
6054
|
+
CGContextSaveGState(ctx);
|
|
6055
|
+
CGColorRef ink = (CGColorRef)CFDictionaryGetValue(
|
|
6056
|
+
CTRunGetAttributes(run), kCTForegroundColorAttributeName);
|
|
6057
|
+
if (ink) CGContextSetFillColorWithColor(ctx, ink);
|
|
6058
|
+
BDrawGlyphsAtScale(ctx, font, glyphs.data(), positions.data(),
|
|
6059
|
+
(size_t)count,
|
|
6060
|
+
CGPointMake(x + L.x, y + L.baseline));
|
|
6061
|
+
CGContextRestoreGState(ctx);
|
|
6062
|
+
}
|
|
5861
6063
|
}
|
|
5862
6064
|
CGContextRestoreGState(ctx);
|
|
5863
6065
|
return info.Env().Undefined();
|
|
@@ -5897,8 +6099,14 @@ static Napi::Value CtxDrawGlyphs(const Napi::CallbackInfo& info) {
|
|
|
5897
6099
|
BGlyphOriginsArg(run.Get("positions"), &positionStore);
|
|
5898
6100
|
size_t count = std::min(nGlyphs, positionStore.size());
|
|
5899
6101
|
if (count == 0) continue;
|
|
5900
|
-
|
|
5901
|
-
|
|
6102
|
+
CTFontRef font = BFontFrom(fv);
|
|
6103
|
+
if (BFontScale(font) != 1) {
|
|
6104
|
+
// the origins are the caller's pixels, in text space through the flip
|
|
6105
|
+
BDrawGlyphsAtScale(ctx, font, glyphs, positionStore.data(), count,
|
|
6106
|
+
CGPointZero);
|
|
6107
|
+
continue;
|
|
6108
|
+
}
|
|
6109
|
+
CTFontDrawGlyphs(font, glyphs, positionStore.data(), (CFIndex)count, ctx);
|
|
5902
6110
|
}
|
|
5903
6111
|
CGContextRestoreGState(ctx);
|
|
5904
6112
|
return info.Env().Undefined();
|
|
@@ -6060,7 +6268,7 @@ static Napi::Value DrawLayoutGradient(const Napi::CallbackInfo& info) {
|
|
|
6060
6268
|
std::vector<CGGlyph> glyphs((size_t)count);
|
|
6061
6269
|
std::vector<CGPoint> positions((size_t)count);
|
|
6062
6270
|
CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
|
|
6063
|
-
|
|
6271
|
+
BRunPositions(run, &positions);
|
|
6064
6272
|
for (CFIndex g = 0; g < count; g++) {
|
|
6065
6273
|
CGAffineTransform t = {1, 0, 0, -1,
|
|
6066
6274
|
x + L.x + positions[(size_t)g].x,
|
|
@@ -6333,7 +6541,7 @@ static Napi::Value LayoutCoverage(const Napi::CallbackInfo& info) {
|
|
|
6333
6541
|
glyphs.resize((size_t)count);
|
|
6334
6542
|
positions.resize((size_t)count);
|
|
6335
6543
|
CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
|
|
6336
|
-
|
|
6544
|
+
BRunPositions(run, &positions);
|
|
6337
6545
|
for (size_t g = 0; g < (size_t)count; g++) {
|
|
6338
6546
|
// a glyph shaping deleted, such as a ligature's second half
|
|
6339
6547
|
if (glyphs[g] == kCGFontIndexInvalid) continue;
|
|
@@ -6378,6 +6586,11 @@ static Napi::Value LayoutCoverage(const Napi::CallbackInfo& info) {
|
|
|
6378
6586
|
CGContextSetGrayFillColor(ctx, 0, 1);
|
|
6379
6587
|
CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
|
|
6380
6588
|
for (const DrawnGlyph& d : drawn) {
|
|
6589
|
+
if (BFontScale(d.font) != 1) {
|
|
6590
|
+
const CGPoint here = CGPointZero;
|
|
6591
|
+
BDrawGlyphsAtScale(ctx, d.font, &d.glyph, &here, 1, d.origin);
|
|
6592
|
+
continue;
|
|
6593
|
+
}
|
|
6381
6594
|
// CTFontDrawGlyphs reads positions in text space, through the flip
|
|
6382
6595
|
const CGPoint at = CGPointMake(d.origin.x, -d.origin.y);
|
|
6383
6596
|
CTFontDrawGlyphs(d.font, &d.glyph, &at, 1, ctx);
|
package/src/video.mm
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
1
|
+
// @windowkit/appkit video.mm — video frames a renderer is handed as bytes,
|
|
2
|
+
// shown on a layer as they are or drawn into a surface.
|
|
3
|
+
//
|
|
4
|
+
// A decoder that is not the platform's — ffmpeg over a pipe, a WASM module,
|
|
5
|
+
// an addon — hands a renderer planes of bytes, and the cheapest way to put
|
|
6
|
+
// them on the screen is the way VideoToolbox's own output gets there: a
|
|
7
|
+
// YCbCr IOSurface as a plain layer's contents. The render server converts
|
|
8
|
+
// and scales it, in the GPU, on its own clock; the CPU's share is the copy
|
|
9
|
+
// in and a transaction. Measured for react-x11's video design record
|
|
10
|
+
// (docs/architecture/video.md §3.4): `420v`, `420f` and `2vuy` surfaces all
|
|
11
|
+
// show on screen — through the window server, not through
|
|
12
|
+
// CALayer.render(in:), which draws none of them — and the three-plane
|
|
13
|
+
// layouts (`y420`, `f420`) draw nothing. So:
|
|
14
|
+
//
|
|
15
|
+
// - createVideoSurface(width, height, { format, colorSpace, range })
|
|
16
|
+
// -> { handle, iosurfaceId }: an IOSurface-backed CVPixelBuffer, `NV12`
|
|
17
|
+
// (two planes, `420v` or `420f` by range) or `BGRA`, carrying the colour
|
|
18
|
+
// attachments CoreVideo gives a decoded frame — matrix, primaries and
|
|
19
|
+
// transfer function, which CoreVideo mirrors onto the IOSurface where Core
|
|
20
|
+
// Animation reads them. Shown through setLayerContentsIOSurface by id,
|
|
21
|
+
// like any other IOSurface; that verb keeps the colour the surface names.
|
|
22
|
+
// - writeVideoSurface(target, format, planes, options?): one frame in.
|
|
23
|
+
// `NV12` and `I420` into an NV12 surface — I420's two chroma planes
|
|
24
|
+
// interleaved on the way, the copy the write makes anyway — and `BGRA`
|
|
25
|
+
// into a BGRA one. Into a BGRA surface, or into a 2D surface
|
|
26
|
+
// (createSurface, createSurfaceIOSurface) for a renderer that draws the
|
|
27
|
+
// frame in its own paint order, a YCbCr frame is converted by
|
|
28
|
+
// VideoToolbox's pixel transfer, colour-matched to sRGB, so that the
|
|
29
|
+
// frame drawn into a bitmap and the same frame on a layer show the same
|
|
30
|
+
// colours.
|
|
31
|
+
// - videoSurfaceIsInUse(handle), releaseVideoSurface(handle) — the
|
|
32
|
+
// surface verbs' counterparts, so a renderer keeping a ring of them writes
|
|
33
|
+
// only into one the render server has let go.
|
|
34
|
+
// - videoFormats() -> { surfaces, frames }: what this bridge makes and
|
|
35
|
+
// takes, for a renderer to ask rather than assume.
|
|
36
|
+
//
|
|
37
|
+
// Every verb runs on the calling thread — a worker's, in threaded mode —
|
|
38
|
+
// and none touches a layer: the copy is IOSurface memory under its own
|
|
39
|
+
// lock, and the flip is setLayerContentsIOSurface's, which goes through the
|
|
40
|
+
// layer queue like every other layer change.
|
|
41
|
+
|
|
42
|
+
#include <napi.h>
|
|
43
|
+
#import <CoreVideo/CoreVideo.h>
|
|
44
|
+
#import <Foundation/Foundation.h>
|
|
45
|
+
#import <IOSurface/IOSurface.h>
|
|
46
|
+
#import <VideoToolbox/VideoToolbox.h>
|
|
47
|
+
|
|
48
|
+
#include <cmath>
|
|
49
|
+
|
|
50
|
+
#include <cstdint>
|
|
51
|
+
#include <cstring>
|
|
52
|
+
#include <string>
|
|
53
|
+
#include <vector>
|
|
54
|
+
|
|
55
|
+
// A 2D surface's bitmap (backend.mm): false, with a JS error pending, when
|
|
56
|
+
// `v` is not a live surface handle.
|
|
57
|
+
struct CALSurfaceBits {
|
|
58
|
+
uint8_t* data;
|
|
59
|
+
size_t width, height, bytesPerRow;
|
|
60
|
+
};
|
|
61
|
+
bool CALSurfaceBitmap(Napi::Value v, CALSurfaceBits* out);
|
|
62
|
+
// Name an IOSurface's colour space sRGB (backend.mm).
|
|
63
|
+
void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep);
|
|
64
|
+
// Name an IOSurface's colour space from its video tags (below).
|
|
65
|
+
bool CALNameVideoColorSpace(IOSurfaceRef ios);
|
|
66
|
+
|
|
67
|
+
namespace {
|
|
68
|
+
|
|
69
|
+
// What tells a video surface's handle from a 2D surface's: both are
|
|
70
|
+
// Externals, and writeVideoSurface takes either.
|
|
71
|
+
const napi_type_tag kVideoSurfaceTag = {0x8c1e5b2d7a4f4e19ULL,
|
|
72
|
+
0xb36d0f2a91c84e57ULL};
|
|
73
|
+
|
|
74
|
+
const size_t kMaxSide = 16384;
|
|
75
|
+
|
|
76
|
+
enum class Format { NV12, I420, BGRA };
|
|
77
|
+
|
|
78
|
+
const char* FormatName(Format f) {
|
|
79
|
+
switch (f) {
|
|
80
|
+
case Format::NV12:
|
|
81
|
+
return "NV12";
|
|
82
|
+
case Format::I420:
|
|
83
|
+
return "I420";
|
|
84
|
+
case Format::BGRA:
|
|
85
|
+
return "BGRA";
|
|
86
|
+
}
|
|
87
|
+
return "?";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
bool ParseFormat(Napi::Value v, Format* out) {
|
|
91
|
+
if (!v.IsString()) return false;
|
|
92
|
+
std::string s = v.As<Napi::String>().Utf8Value();
|
|
93
|
+
if (s == "NV12") *out = Format::NV12;
|
|
94
|
+
else if (s == "I420") *out = Format::I420;
|
|
95
|
+
else if (s == "BGRA") *out = Format::BGRA;
|
|
96
|
+
else return false;
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// What a frame's numbers mean: the attachments CoreVideo puts on a decoded
|
|
101
|
+
// buffer, which Core Animation and VideoToolbox both read.
|
|
102
|
+
struct Colour {
|
|
103
|
+
CFStringRef matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
|
|
104
|
+
CFStringRef primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
|
|
105
|
+
CFStringRef transfer = kCVImageBufferTransferFunction_ITU_R_709_2;
|
|
106
|
+
bool full = false;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
// `colorSpace` ('bt709' by default, 'bt601', 'bt2020') and `range`
|
|
110
|
+
// ('video' by default, 'full') off an options object. False, with a
|
|
111
|
+
// TypeError pending, for a value that is not one of those.
|
|
112
|
+
bool ParseColour(Napi::Env env, const char* verb, Napi::Object o, Colour* c) {
|
|
113
|
+
if (o.Has("colorSpace") && !o.Get("colorSpace").IsUndefined()) {
|
|
114
|
+
Napi::Value v = o.Get("colorSpace");
|
|
115
|
+
std::string s = v.IsString() ? v.As<Napi::String>().Utf8Value() : "";
|
|
116
|
+
if (s == "bt709") {
|
|
117
|
+
// the defaults
|
|
118
|
+
} else if (s == "bt601") {
|
|
119
|
+
// SD: the 601 matrix with SMPTE C primaries (SMPTE 170M), which is
|
|
120
|
+
// what an untagged SD stream is taken to be
|
|
121
|
+
c->matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
|
|
122
|
+
c->primaries = kCVImageBufferColorPrimaries_SMPTE_C;
|
|
123
|
+
} else if (s == "bt2020") {
|
|
124
|
+
// SDR only: the 2020 matrix and primaries, the 709 curve (which is
|
|
125
|
+
// what 2020's SDR transfer is)
|
|
126
|
+
c->matrix = kCVImageBufferYCbCrMatrix_ITU_R_2020;
|
|
127
|
+
c->primaries = kCVImageBufferColorPrimaries_ITU_R_2020;
|
|
128
|
+
} else {
|
|
129
|
+
Napi::TypeError::New(env, std::string(verb) +
|
|
130
|
+
": colorSpace must be 'bt709', 'bt601' "
|
|
131
|
+
"or 'bt2020'")
|
|
132
|
+
.ThrowAsJavaScriptException();
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (o.Has("range") && !o.Get("range").IsUndefined()) {
|
|
137
|
+
Napi::Value v = o.Get("range");
|
|
138
|
+
std::string s = v.IsString() ? v.As<Napi::String>().Utf8Value() : "";
|
|
139
|
+
if (s == "full") {
|
|
140
|
+
c->full = true;
|
|
141
|
+
} else if (s != "video") {
|
|
142
|
+
Napi::TypeError::New(env, std::string(verb) +
|
|
143
|
+
": range must be 'video' or 'full'")
|
|
144
|
+
.ThrowAsJavaScriptException();
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
void Attach(CVPixelBufferRef pb, const Colour& c) {
|
|
152
|
+
CVBufferSetAttachment(pb, kCVImageBufferYCbCrMatrixKey, c.matrix,
|
|
153
|
+
kCVAttachmentMode_ShouldPropagate);
|
|
154
|
+
CVBufferSetAttachment(pb, kCVImageBufferColorPrimariesKey, c.primaries,
|
|
155
|
+
kCVAttachmentMode_ShouldPropagate);
|
|
156
|
+
CVBufferSetAttachment(pb, kCVImageBufferTransferFunctionKey, c.transfer,
|
|
157
|
+
kCVAttachmentMode_ShouldPropagate);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// sRGB, as attachments: what every bitmap this bridge draws into is, and so
|
|
161
|
+
// what a converted frame is matched to.
|
|
162
|
+
void AttachSRGB(CVPixelBufferRef pb) {
|
|
163
|
+
CVBufferSetAttachment(pb, kCVImageBufferColorPrimariesKey,
|
|
164
|
+
kCVImageBufferColorPrimaries_ITU_R_709_2,
|
|
165
|
+
kCVAttachmentMode_ShouldPropagate);
|
|
166
|
+
CVBufferSetAttachment(pb, kCVImageBufferTransferFunctionKey,
|
|
167
|
+
kCVImageBufferTransferFunction_sRGB,
|
|
168
|
+
kCVAttachmentMode_ShouldPropagate);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// The IOSurface alone, not the CVPixelBuffer it was made through: a pixel
|
|
172
|
+
// buffer holds a use count on its surface for as long as it lives, so
|
|
173
|
+
// IOSurfaceIsInUse would answer true for a surface nothing shows, and a
|
|
174
|
+
// renderer could never tell which of its ring the render server let go.
|
|
175
|
+
// The attachments are the surface's own values by then, and a pixel buffer
|
|
176
|
+
// is wrapped around it again only for the call that needs one.
|
|
177
|
+
struct VideoSurface {
|
|
178
|
+
IOSurfaceRef ios = nullptr; // nullptr once released
|
|
179
|
+
bool nv12 = true;
|
|
180
|
+
size_t width = 0, height = 0;
|
|
181
|
+
Colour colour;
|
|
182
|
+
int64_t bytes = 0;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
void VideoSurfaceFree(Napi::Env env, VideoSurface* s) {
|
|
186
|
+
if (!s->ios) return;
|
|
187
|
+
CFRelease(s->ios);
|
|
188
|
+
s->ios = nullptr;
|
|
189
|
+
if (s->bytes) {
|
|
190
|
+
Napi::MemoryManagement::AdjustExternalMemory(env, -s->bytes);
|
|
191
|
+
s->bytes = 0;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
bool IsVideoSurface(Napi::Value v) {
|
|
196
|
+
return v.IsExternal() &&
|
|
197
|
+
v.As<Napi::External<VideoSurface>>().CheckTypeTag(&kVideoSurfaceTag);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// The surface behind a handle, or nullptr with an error pending: not a
|
|
201
|
+
// video surface's handle, or one released.
|
|
202
|
+
VideoSurface* VideoSurfaceFrom(Napi::Value v, const char* verb) {
|
|
203
|
+
if (!IsVideoSurface(v)) {
|
|
204
|
+
Napi::TypeError::New(v.Env(), std::string(verb) +
|
|
205
|
+
": expected a handle from "
|
|
206
|
+
"createVideoSurface")
|
|
207
|
+
.ThrowAsJavaScriptException();
|
|
208
|
+
return nullptr;
|
|
209
|
+
}
|
|
210
|
+
VideoSurface* s = v.As<Napi::External<VideoSurface>>().Data();
|
|
211
|
+
if (!s->ios) {
|
|
212
|
+
Napi::Error::New(v.Env(), std::string(verb) + ": video surface was released")
|
|
213
|
+
.ThrowAsJavaScriptException();
|
|
214
|
+
return nullptr;
|
|
215
|
+
}
|
|
216
|
+
return s;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// --- a frame's planes ---------------------------------------------------------
|
|
220
|
+
|
|
221
|
+
// One plane as handed over: its bytes, and how far apart its rows are.
|
|
222
|
+
struct Plane {
|
|
223
|
+
const uint8_t* data = nullptr;
|
|
224
|
+
size_t length = 0;
|
|
225
|
+
size_t stride = 0;
|
|
226
|
+
size_t rowBytes = 0; // what one row holds of the picture
|
|
227
|
+
size_t rows = 0;
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
// A frame of `format` at width x height: its planes out of `planes` (an
|
|
231
|
+
// array of Buffers or typed arrays) with `strides` (an array of numbers, or
|
|
232
|
+
// undefined for rows packed edge to edge), each checked to hold every row
|
|
233
|
+
// it claims. False, with a TypeError pending, otherwise.
|
|
234
|
+
bool ReadPlanes(Napi::Env env, const char* verb, Format format, size_t w,
|
|
235
|
+
size_t h, Napi::Value planesV, Napi::Value stridesV,
|
|
236
|
+
std::vector<Plane>* out) {
|
|
237
|
+
const size_t cw = (w + 1) / 2, ch = (h + 1) / 2;
|
|
238
|
+
std::vector<Plane> want;
|
|
239
|
+
switch (format) {
|
|
240
|
+
case Format::NV12:
|
|
241
|
+
want = {{nullptr, 0, 0, w, h}, {nullptr, 0, 0, cw * 2, ch}};
|
|
242
|
+
break;
|
|
243
|
+
case Format::I420:
|
|
244
|
+
want = {{nullptr, 0, 0, w, h}, {nullptr, 0, 0, cw, ch}, {nullptr, 0, 0, cw, ch}};
|
|
245
|
+
break;
|
|
246
|
+
case Format::BGRA:
|
|
247
|
+
want = {{nullptr, 0, 0, w * 4, h}};
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
if (!planesV.IsArray() || planesV.As<Napi::Array>().Length() != want.size()) {
|
|
251
|
+
Napi::TypeError::New(env, std::string(verb) + ": a " + FormatName(format) +
|
|
252
|
+
" frame is an array of " +
|
|
253
|
+
std::to_string(want.size()) + " plane" +
|
|
254
|
+
(want.size() == 1 ? "" : "s"))
|
|
255
|
+
.ThrowAsJavaScriptException();
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
Napi::Array planes = planesV.As<Napi::Array>();
|
|
259
|
+
Napi::Array strides;
|
|
260
|
+
bool hasStrides = stridesV.IsArray();
|
|
261
|
+
if (hasStrides) strides = stridesV.As<Napi::Array>();
|
|
262
|
+
else if (!stridesV.IsUndefined() && !stridesV.IsNull()) {
|
|
263
|
+
Napi::TypeError::New(env, std::string(verb) + ": strides must be an array")
|
|
264
|
+
.ThrowAsJavaScriptException();
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
for (uint32_t i = 0; i < want.size(); i++) {
|
|
268
|
+
Plane& p = want[i];
|
|
269
|
+
Napi::Value pv = planes.Get(i);
|
|
270
|
+
if (pv.IsTypedArray()) {
|
|
271
|
+
Napi::TypedArray t = pv.As<Napi::TypedArray>();
|
|
272
|
+
p.data = (const uint8_t*)t.ArrayBuffer().Data() + t.ByteOffset();
|
|
273
|
+
p.length = t.ByteLength();
|
|
274
|
+
} else if (pv.IsArrayBuffer()) {
|
|
275
|
+
Napi::ArrayBuffer b = pv.As<Napi::ArrayBuffer>();
|
|
276
|
+
p.data = (const uint8_t*)b.Data();
|
|
277
|
+
p.length = b.ByteLength();
|
|
278
|
+
} else {
|
|
279
|
+
Napi::TypeError::New(env, std::string(verb) + ": plane " +
|
|
280
|
+
std::to_string(i) +
|
|
281
|
+
" is not a Buffer or a typed array")
|
|
282
|
+
.ThrowAsJavaScriptException();
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
p.stride = p.rowBytes;
|
|
286
|
+
if (hasStrides && i < strides.Length()) {
|
|
287
|
+
Napi::Value sv = strides.Get(i);
|
|
288
|
+
if (!sv.IsUndefined()) {
|
|
289
|
+
double sd = sv.IsNumber() ? sv.As<Napi::Number>().DoubleValue() : -1;
|
|
290
|
+
if (!(sd >= (double)p.rowBytes) || sd != (double)(size_t)sd) {
|
|
291
|
+
Napi::TypeError::New(env, std::string(verb) + ": the stride of plane " +
|
|
292
|
+
std::to_string(i) + " must be a whole number of at least " +
|
|
293
|
+
std::to_string(p.rowBytes))
|
|
294
|
+
.ThrowAsJavaScriptException();
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
p.stride = (size_t)sd;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
size_t need = p.stride * (p.rows - 1) + p.rowBytes;
|
|
301
|
+
if (p.length < need) {
|
|
302
|
+
Napi::TypeError::New(env, std::string(verb) + ": plane " + std::to_string(i) +
|
|
303
|
+
" of a " + std::to_string(w) + "x" + std::to_string(h) +
|
|
304
|
+
" " + FormatName(format) + " frame needs " +
|
|
305
|
+
std::to_string(need) + " bytes, and has " +
|
|
306
|
+
std::to_string(p.length))
|
|
307
|
+
.ThrowAsJavaScriptException();
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
*out = std::move(want);
|
|
312
|
+
return true;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
void CopyRows(uint8_t* dst, size_t dstStride, const Plane& p) {
|
|
316
|
+
for (size_t y = 0; y < p.rows; y++)
|
|
317
|
+
memcpy(dst + y * dstStride, p.data + y * p.stride, p.rowBytes);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// I420's two chroma planes into NV12's one, CbCr pairs.
|
|
321
|
+
void InterleaveRows(uint8_t* dst, size_t dstStride, const Plane& u, const Plane& v) {
|
|
322
|
+
for (size_t y = 0; y < u.rows; y++) {
|
|
323
|
+
uint8_t* d = dst + y * dstStride;
|
|
324
|
+
const uint8_t* cb = u.data + y * u.stride;
|
|
325
|
+
const uint8_t* cr = v.data + y * v.stride;
|
|
326
|
+
for (size_t x = 0; x < u.rowBytes; x++) {
|
|
327
|
+
d[2 * x] = cb[x];
|
|
328
|
+
d[2 * x + 1] = cr[x];
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// BGRA rows with the alpha byte set: a frame is opaque, whatever a decoder
|
|
334
|
+
// left in its fourth byte, and a bitmap that is premultiplied would read a
|
|
335
|
+
// zero there as a hole.
|
|
336
|
+
void CopyOpaqueRows(uint8_t* dst, size_t dstStride, const Plane& p, size_t w) {
|
|
337
|
+
for (size_t y = 0; y < p.rows; y++) {
|
|
338
|
+
const uint8_t* s = p.data + y * p.stride;
|
|
339
|
+
uint8_t* d = dst + y * dstStride;
|
|
340
|
+
for (size_t x = 0; x < w; x++) {
|
|
341
|
+
uint32_t px;
|
|
342
|
+
memcpy(&px, s + 4 * x, 4);
|
|
343
|
+
px |= 0xff000000u;
|
|
344
|
+
memcpy(d + 4 * x, &px, 4);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// --- conversion ---------------------------------------------------------------
|
|
350
|
+
//
|
|
351
|
+
// Into a bitmap, a frame has to come out the colours Core Animation shows
|
|
352
|
+
// for the same frame on a layer, or a video moving between the two — which
|
|
353
|
+
// a renderer does whenever something is drawn over it — visibly changes
|
|
354
|
+
// shade. Since a surface is named the colour space its tags make
|
|
355
|
+
// (CALNameVideoColorSpace, below), Core Animation shows it as AVPlayerLayer
|
|
356
|
+
// shows a frame and as VideoToolbox's pixel transfer converts one, so the
|
|
357
|
+
// conversion is VideoToolbox's, colour-matched to sRGB, for every tagging.
|
|
358
|
+
// Measured on screen against a ramp and five hues (test/video-surface.js),
|
|
359
|
+
// the two agree to within two levels.
|
|
360
|
+
//
|
|
361
|
+
// What still differs is gamut: a layer keeps a colour that is outside sRGB
|
|
362
|
+
// and shows it on a wide-gamut panel, and an 8-bit sRGB bitmap clips it, so
|
|
363
|
+
// a saturated frame can lose a few levels in the drawn half.
|
|
364
|
+
|
|
365
|
+
// One per thread: a session is not safe to share across threads, and a
|
|
366
|
+
// worker's renderer converts on its own. Its destination is always plain
|
|
367
|
+
// memory (a BGRA video surface's is wrapped as bytes too): a session that
|
|
368
|
+
// has written into an IOSurface-backed buffer refuses
|
|
369
|
+
// (kVTPixelTransferNotSupportedErr) a three-plane frame into plain memory
|
|
370
|
+
// afterwards, and converts the same frame to other numbers.
|
|
371
|
+
thread_local VTPixelTransferSessionRef tlTransfer = nullptr;
|
|
372
|
+
|
|
373
|
+
VTPixelTransferSessionRef Transfer(bool fresh) {
|
|
374
|
+
if (tlTransfer && fresh) {
|
|
375
|
+
VTPixelTransferSessionInvalidate(tlTransfer);
|
|
376
|
+
CFRelease(tlTransfer);
|
|
377
|
+
tlTransfer = nullptr;
|
|
378
|
+
}
|
|
379
|
+
if (tlTransfer) return tlTransfer;
|
|
380
|
+
if (VTPixelTransferSessionCreate(kCFAllocatorDefault, &tlTransfer) != noErr) {
|
|
381
|
+
tlTransfer = nullptr;
|
|
382
|
+
return nullptr;
|
|
383
|
+
}
|
|
384
|
+
VTSessionSetProperty(tlTransfer, kVTPixelTransferPropertyKey_DestinationColorPrimaries,
|
|
385
|
+
kCVImageBufferColorPrimaries_ITU_R_709_2);
|
|
386
|
+
VTSessionSetProperty(tlTransfer, kVTPixelTransferPropertyKey_DestinationTransferFunction,
|
|
387
|
+
kCVImageBufferTransferFunction_sRGB);
|
|
388
|
+
VTSessionSetProperty(tlTransfer, kVTPixelTransferPropertyKey_RealTime, kCFBooleanTrue);
|
|
389
|
+
return tlTransfer;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
bool ConvertMatched(Napi::Env env, const char* verb, Format format,
|
|
393
|
+
const std::vector<Plane>& planes, size_t w, size_t h, const Colour& colour,
|
|
394
|
+
uint8_t* dstData, size_t dstStride) {
|
|
395
|
+
OSType type = format == Format::NV12
|
|
396
|
+
? (colour.full ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
|
|
397
|
+
: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)
|
|
398
|
+
: (colour.full ? kCVPixelFormatType_420YpCbCr8PlanarFullRange
|
|
399
|
+
: kCVPixelFormatType_420YpCbCr8Planar);
|
|
400
|
+
size_t n = planes.size();
|
|
401
|
+
void* bases[3];
|
|
402
|
+
size_t widths[3], heights[3], bprs[3];
|
|
403
|
+
const size_t cw = (w + 1) / 2, ch = (h + 1) / 2;
|
|
404
|
+
for (size_t i = 0; i < n; i++) {
|
|
405
|
+
bases[i] = (void*)planes[i].data;
|
|
406
|
+
widths[i] = i == 0 ? w : cw;
|
|
407
|
+
heights[i] = i == 0 ? h : ch;
|
|
408
|
+
bprs[i] = planes[i].stride;
|
|
409
|
+
}
|
|
410
|
+
CVPixelBufferRef src = nullptr, dst = nullptr;
|
|
411
|
+
CVReturn rv = CVPixelBufferCreateWithPlanarBytes(
|
|
412
|
+
kCFAllocatorDefault, w, h, type, nullptr, 0, n, bases, widths, heights, bprs,
|
|
413
|
+
nullptr, nullptr, nullptr, &src);
|
|
414
|
+
if (rv == kCVReturnSuccess)
|
|
415
|
+
rv = CVPixelBufferCreateWithBytes(kCFAllocatorDefault, w, h, kCVPixelFormatType_32BGRA,
|
|
416
|
+
dstData, dstStride, nullptr, nullptr, nullptr, &dst);
|
|
417
|
+
if (rv != kCVReturnSuccess || !src || !dst) {
|
|
418
|
+
if (src) CVPixelBufferRelease(src);
|
|
419
|
+
if (dst) CVPixelBufferRelease(dst);
|
|
420
|
+
Napi::Error::New(env, std::string(verb) + ": could not wrap the frame (" +
|
|
421
|
+
std::to_string(rv) + ")")
|
|
422
|
+
.ThrowAsJavaScriptException();
|
|
423
|
+
return false;
|
|
424
|
+
}
|
|
425
|
+
Attach(src, colour);
|
|
426
|
+
AttachSRGB(dst);
|
|
427
|
+
VTPixelTransferSessionRef session = Transfer(false);
|
|
428
|
+
OSStatus st = session ? VTPixelTransferSessionTransferImage(session, src, dst) : -1;
|
|
429
|
+
if (st != noErr) {
|
|
430
|
+
// and once more on a session of its own, for whatever else a long-lived
|
|
431
|
+
// one turns out to remember
|
|
432
|
+
session = Transfer(true);
|
|
433
|
+
st = session ? VTPixelTransferSessionTransferImage(session, src, dst) : -1;
|
|
434
|
+
}
|
|
435
|
+
CVPixelBufferRelease(src);
|
|
436
|
+
CVPixelBufferRelease(dst);
|
|
437
|
+
if (st != noErr) {
|
|
438
|
+
Napi::Error::New(env, std::string(verb) + ": VideoToolbox could not convert the frame (" +
|
|
439
|
+
std::to_string(st) + ")")
|
|
440
|
+
.ThrowAsJavaScriptException();
|
|
441
|
+
return false;
|
|
442
|
+
}
|
|
443
|
+
return true;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// A YCbCr frame converted into BGRA rows at `dst`, opaque, in sRGB, the
|
|
447
|
+
// colours Core Animation shows it in on a layer. False with an error
|
|
448
|
+
// pending when the conversion was refused.
|
|
449
|
+
bool ConvertToBGRA(Napi::Env env, const char* verb, Format format,
|
|
450
|
+
const std::vector<Plane>& planes, size_t w, size_t h, const Colour& colour,
|
|
451
|
+
uint8_t* dst, size_t dstStride) {
|
|
452
|
+
return ConvertMatched(env, verb, format, planes, w, h, colour, dst, dstStride);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// --- verbs --------------------------------------------------------------------
|
|
456
|
+
|
|
457
|
+
Napi::Value CreateVideoSurface(const Napi::CallbackInfo& info) {
|
|
458
|
+
Napi::Env env = info.Env();
|
|
459
|
+
const char* verb = "createVideoSurface";
|
|
460
|
+
double wd = info[0].IsNumber() ? info[0].As<Napi::Number>().DoubleValue() : 0;
|
|
461
|
+
double hd = info[1].IsNumber() ? info[1].As<Napi::Number>().DoubleValue() : 0;
|
|
462
|
+
if (!(wd >= 1 && hd >= 1 && wd <= kMaxSide && hd <= kMaxSide) ||
|
|
463
|
+
wd != (double)(size_t)wd || hd != (double)(size_t)hd) {
|
|
464
|
+
Napi::TypeError::New(env, "createVideoSurface(width, height, options): width and "
|
|
465
|
+
"height are whole numbers of pixels, 1 to 16384")
|
|
466
|
+
.ThrowAsJavaScriptException();
|
|
467
|
+
return env.Undefined();
|
|
468
|
+
}
|
|
469
|
+
size_t w = (size_t)wd, h = (size_t)hd;
|
|
470
|
+
Format format = Format::NV12;
|
|
471
|
+
Colour colour;
|
|
472
|
+
if (info.Length() > 2 && info[2].IsObject()) {
|
|
473
|
+
Napi::Object o = info[2].As<Napi::Object>();
|
|
474
|
+
if (o.Has("format") && !o.Get("format").IsUndefined() &&
|
|
475
|
+
(!ParseFormat(o.Get("format"), &format) || format == Format::I420)) {
|
|
476
|
+
Napi::TypeError::New(env, "createVideoSurface: format must be 'NV12' or 'BGRA' "
|
|
477
|
+
"(an I420 frame is written into an NV12 surface)")
|
|
478
|
+
.ThrowAsJavaScriptException();
|
|
479
|
+
return env.Undefined();
|
|
480
|
+
}
|
|
481
|
+
if (!ParseColour(env, verb, o, &colour)) return env.Undefined();
|
|
482
|
+
}
|
|
483
|
+
bool nv12 = format == Format::NV12;
|
|
484
|
+
OSType type = nv12 ? (colour.full ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
|
|
485
|
+
: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)
|
|
486
|
+
: kCVPixelFormatType_32BGRA;
|
|
487
|
+
NSDictionary* attrs = @{
|
|
488
|
+
(id)kCVPixelBufferIOSurfacePropertiesKey : @{},
|
|
489
|
+
(id)kCVPixelBufferPixelFormatTypeKey : @(type),
|
|
490
|
+
};
|
|
491
|
+
CVPixelBufferRef pb = nullptr;
|
|
492
|
+
CVReturn rv = CVPixelBufferCreate(kCFAllocatorDefault, w, h, type,
|
|
493
|
+
(__bridge CFDictionaryRef)attrs, &pb);
|
|
494
|
+
IOSurfaceRef ios = pb ? CVPixelBufferGetIOSurface(pb) : nullptr;
|
|
495
|
+
if (rv != kCVReturnSuccess || !ios) {
|
|
496
|
+
if (pb) CVPixelBufferRelease(pb);
|
|
497
|
+
Napi::Error::New(env, "createVideoSurface: CVPixelBufferCreate failed (" +
|
|
498
|
+
std::to_string(rv) + ")")
|
|
499
|
+
.ThrowAsJavaScriptException();
|
|
500
|
+
return env.Undefined();
|
|
501
|
+
}
|
|
502
|
+
// black, so a surface shown before its first frame shows no garbage
|
|
503
|
+
CVPixelBufferLockBaseAddress(pb, 0);
|
|
504
|
+
if (nv12) {
|
|
505
|
+
uint8_t* y = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(pb, 0);
|
|
506
|
+
memset(y, colour.full ? 0 : 16, CVPixelBufferGetBytesPerRowOfPlane(pb, 0) * h);
|
|
507
|
+
uint8_t* uv = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(pb, 1);
|
|
508
|
+
memset(uv, 128, CVPixelBufferGetBytesPerRowOfPlane(pb, 1) * ((h + 1) / 2));
|
|
509
|
+
} else {
|
|
510
|
+
uint8_t* p = (uint8_t*)CVPixelBufferGetBaseAddress(pb);
|
|
511
|
+
size_t bpr = CVPixelBufferGetBytesPerRow(pb);
|
|
512
|
+
for (size_t r = 0; r < h; r++) {
|
|
513
|
+
uint32_t* row = (uint32_t*)(p + r * bpr);
|
|
514
|
+
for (size_t x = 0; x < w; x++) row[x] = 0xff000000u;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
CVPixelBufferUnlockBaseAddress(pb, 0);
|
|
518
|
+
if (nv12) {
|
|
519
|
+
// named the colour space these make when it is shown
|
|
520
|
+
// (setLayerContentsIOSurface, CALNameVideoColorSpace)
|
|
521
|
+
Attach(pb, colour);
|
|
522
|
+
} else {
|
|
523
|
+
// what is written into it is what an sRGB bitmap holds
|
|
524
|
+
AttachSRGB(pb);
|
|
525
|
+
CALNameSurfaceSRGB(ios, false);
|
|
526
|
+
}
|
|
527
|
+
CFRetain(ios);
|
|
528
|
+
CVPixelBufferRelease(pb);
|
|
529
|
+
auto* s = new VideoSurface();
|
|
530
|
+
s->ios = ios;
|
|
531
|
+
s->nv12 = nv12;
|
|
532
|
+
s->width = w;
|
|
533
|
+
s->height = h;
|
|
534
|
+
s->colour = colour;
|
|
535
|
+
s->bytes = (int64_t)IOSurfaceGetAllocSize(ios);
|
|
536
|
+
Napi::MemoryManagement::AdjustExternalMemory(env, s->bytes);
|
|
537
|
+
auto handle = Napi::External<VideoSurface>::New(env, s, [](Napi::Env e, VideoSurface* d) {
|
|
538
|
+
VideoSurfaceFree(e, d);
|
|
539
|
+
delete d;
|
|
540
|
+
});
|
|
541
|
+
handle.TypeTag(&kVideoSurfaceTag);
|
|
542
|
+
Napi::Object out = Napi::Object::New(env);
|
|
543
|
+
out.Set("handle", handle);
|
|
544
|
+
out.Set("iosurfaceId", (double)IOSurfaceGetID(ios));
|
|
545
|
+
return out;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
Napi::Value WriteVideoSurface(const Napi::CallbackInfo& info) {
|
|
549
|
+
Napi::Env env = info.Env();
|
|
550
|
+
const char* verb = "writeVideoSurface";
|
|
551
|
+
Format format;
|
|
552
|
+
if (!ParseFormat(info[1], &format)) {
|
|
553
|
+
Napi::TypeError::New(env, "writeVideoSurface(target, format, planes, options): format "
|
|
554
|
+
"must be 'NV12', 'I420' or 'BGRA'")
|
|
555
|
+
.ThrowAsJavaScriptException();
|
|
556
|
+
return env.Undefined();
|
|
557
|
+
}
|
|
558
|
+
Napi::Object opts = info.Length() > 3 && info[3].IsObject() ? info[3].As<Napi::Object>()
|
|
559
|
+
: Napi::Object::New(env);
|
|
560
|
+
Napi::Value strides = opts.Has("strides") ? opts.Get("strides") : env.Undefined();
|
|
561
|
+
bool yuv = format != Format::BGRA;
|
|
562
|
+
|
|
563
|
+
if (IsVideoSurface(info[0])) {
|
|
564
|
+
VideoSurface* s = VideoSurfaceFrom(info[0], verb);
|
|
565
|
+
if (!s) return env.Undefined();
|
|
566
|
+
if (s->nv12 && !yuv) {
|
|
567
|
+
Napi::TypeError::New(env, "writeVideoSurface: an NV12 surface takes an NV12 or I420 "
|
|
568
|
+
"frame, not BGRA — make the surface with format 'BGRA'")
|
|
569
|
+
.ThrowAsJavaScriptException();
|
|
570
|
+
return env.Undefined();
|
|
571
|
+
}
|
|
572
|
+
std::vector<Plane> planes;
|
|
573
|
+
if (!ReadPlanes(env, verb, format, s->width, s->height, info[2], strides, &planes))
|
|
574
|
+
return env.Undefined();
|
|
575
|
+
if (!s->nv12 && yuv) {
|
|
576
|
+
// into a BGRA surface: converted, in the frame's own colour
|
|
577
|
+
Colour colour;
|
|
578
|
+
if (!ParseColour(env, verb, opts, &colour)) return env.Undefined();
|
|
579
|
+
IOSurfaceLock(s->ios, 0, nullptr);
|
|
580
|
+
ConvertToBGRA(env, verb, format, planes, s->width, s->height, colour,
|
|
581
|
+
(uint8_t*)IOSurfaceGetBaseAddress(s->ios), IOSurfaceGetBytesPerRow(s->ios));
|
|
582
|
+
IOSurfaceUnlock(s->ios, 0, nullptr);
|
|
583
|
+
return env.Undefined();
|
|
584
|
+
}
|
|
585
|
+
IOSurfaceLock(s->ios, 0, nullptr);
|
|
586
|
+
if (!s->nv12) {
|
|
587
|
+
CopyOpaqueRows((uint8_t*)IOSurfaceGetBaseAddress(s->ios),
|
|
588
|
+
IOSurfaceGetBytesPerRow(s->ios), planes[0], s->width);
|
|
589
|
+
} else {
|
|
590
|
+
CopyRows((uint8_t*)IOSurfaceGetBaseAddressOfPlane(s->ios, 0),
|
|
591
|
+
IOSurfaceGetBytesPerRowOfPlane(s->ios, 0), planes[0]);
|
|
592
|
+
uint8_t* uv = (uint8_t*)IOSurfaceGetBaseAddressOfPlane(s->ios, 1);
|
|
593
|
+
size_t bpr = IOSurfaceGetBytesPerRowOfPlane(s->ios, 1);
|
|
594
|
+
if (format == Format::NV12) CopyRows(uv, bpr, planes[1]);
|
|
595
|
+
else InterleaveRows(uv, bpr, planes[1], planes[2]);
|
|
596
|
+
}
|
|
597
|
+
IOSurfaceUnlock(s->ios, 0, nullptr);
|
|
598
|
+
return env.Undefined();
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// a 2D surface: the frame at its top-left corner, `width` x `height` of it
|
|
602
|
+
CALSurfaceBits bits;
|
|
603
|
+
if (!CALSurfaceBitmap(info[0], &bits)) return env.Undefined();
|
|
604
|
+
size_t w = bits.width, h = bits.height;
|
|
605
|
+
for (const char* key : {"width", "height"}) {
|
|
606
|
+
if (!opts.Has(key) || opts.Get(key).IsUndefined()) continue;
|
|
607
|
+
Napi::Value v = opts.Get(key);
|
|
608
|
+
double d = v.IsNumber() ? v.As<Napi::Number>().DoubleValue() : 0;
|
|
609
|
+
size_t limit = key[0] == 'w' ? bits.width : bits.height;
|
|
610
|
+
if (!(d >= 1 && d <= (double)limit) || d != (double)(size_t)d) {
|
|
611
|
+
Napi::TypeError::New(env, std::string("writeVideoSurface: ") + key +
|
|
612
|
+
" must be a whole number of pixels, at most the "
|
|
613
|
+
"surface's " + std::to_string(limit))
|
|
614
|
+
.ThrowAsJavaScriptException();
|
|
615
|
+
return env.Undefined();
|
|
616
|
+
}
|
|
617
|
+
(key[0] == 'w' ? w : h) = (size_t)d;
|
|
618
|
+
}
|
|
619
|
+
std::vector<Plane> planes;
|
|
620
|
+
if (!ReadPlanes(env, verb, format, w, h, info[2], strides, &planes)) return env.Undefined();
|
|
621
|
+
if (!yuv) {
|
|
622
|
+
CopyOpaqueRows(bits.data, bits.bytesPerRow, planes[0], w);
|
|
623
|
+
return env.Undefined();
|
|
624
|
+
}
|
|
625
|
+
Colour colour;
|
|
626
|
+
if (!ParseColour(env, verb, opts, &colour)) return env.Undefined();
|
|
627
|
+
ConvertToBGRA(env, verb, format, planes, w, h, colour, bits.data, bits.bytesPerRow);
|
|
628
|
+
return env.Undefined();
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
Napi::Value VideoSurfaceIsInUse(const Napi::CallbackInfo& info) {
|
|
632
|
+
VideoSurface* s = VideoSurfaceFrom(info[0], "videoSurfaceIsInUse");
|
|
633
|
+
if (!s) return info.Env().Undefined();
|
|
634
|
+
return Napi::Boolean::New(info.Env(), IOSurfaceIsInUse(s->ios));
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// Free the surface now rather than when the collector reaches the handle.
|
|
638
|
+
// A layer showing it keeps it alive until the layer lets it go. Idempotent.
|
|
639
|
+
Napi::Value ReleaseVideoSurface(const Napi::CallbackInfo& info) {
|
|
640
|
+
Napi::Env env = info.Env();
|
|
641
|
+
if (!IsVideoSurface(info[0])) {
|
|
642
|
+
Napi::TypeError::New(env, "releaseVideoSurface: expected a handle from createVideoSurface")
|
|
643
|
+
.ThrowAsJavaScriptException();
|
|
644
|
+
return env.Undefined();
|
|
645
|
+
}
|
|
646
|
+
VideoSurfaceFree(env, info[0].As<Napi::External<VideoSurface>>().Data());
|
|
647
|
+
return env.Undefined();
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
Napi::Value VideoFormats(const Napi::CallbackInfo& info) {
|
|
651
|
+
Napi::Env env = info.Env();
|
|
652
|
+
Napi::Object out = Napi::Object::New(env);
|
|
653
|
+
Napi::Array surfaces = Napi::Array::New(env, 2);
|
|
654
|
+
surfaces.Set(0u, "NV12");
|
|
655
|
+
surfaces.Set(1u, "BGRA");
|
|
656
|
+
Napi::Array frames = Napi::Array::New(env, 3);
|
|
657
|
+
frames.Set(0u, "NV12");
|
|
658
|
+
frames.Set(1u, "I420");
|
|
659
|
+
frames.Set(2u, "BGRA");
|
|
660
|
+
out.Set("surfaces", surfaces);
|
|
661
|
+
out.Set("frames", frames);
|
|
662
|
+
return out;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
} // namespace
|
|
666
|
+
|
|
667
|
+
// Name `ios`'s colour space from the video tags CoreVideo writes onto a
|
|
668
|
+
// frame's IOSurface — its matrix, primaries and transfer function — as the
|
|
669
|
+
// space CoreVideo makes of them (CVImageBufferCreateColorSpaceFromAttachments).
|
|
670
|
+
// True when it named one; false for a surface with no such tags.
|
|
671
|
+
//
|
|
672
|
+
// Why a surface needs the space as well as the tags: shown with only the
|
|
673
|
+
// tags, Core Animation linearises a frame tagged BT.709 throughout with the
|
|
674
|
+
// exact 709 curve, while AVPlayerLayer — the platform's own player — shows
|
|
675
|
+
// the same frame through the space, on Apple's 1.961 gamma, as VideoToolbox's
|
|
676
|
+
// pixel transfer and Core Image convert it. A video-range grey of Y'=47 was
|
|
677
|
+
// sRGB 51 on a tagged layer and 40 under AVPlayerLayer (test/video-surface.js
|
|
678
|
+
// and test/player.js hold both to the player's). Named, a frame on a layer,
|
|
679
|
+
// the same frame drawn into a bitmap, and AVPlayerLayer playing it agree.
|
|
680
|
+
bool CALNameVideoColorSpace(IOSurfaceRef ios) {
|
|
681
|
+
if (!ios) return false;
|
|
682
|
+
CFTypeRef primaries = IOSurfaceCopyValue(ios, CFSTR("IOSurfaceColorPrimaries"));
|
|
683
|
+
if (!primaries) return false;
|
|
684
|
+
CFTypeRef matrix = IOSurfaceCopyValue(ios, CFSTR("IOSurfaceYCbCrMatrix"));
|
|
685
|
+
CFTypeRef transfer = IOSurfaceCopyValue(ios, CFSTR("IOSurfaceTransferFunction"));
|
|
686
|
+
NSMutableDictionary* tags = [NSMutableDictionary dictionary];
|
|
687
|
+
tags[(id)kCVImageBufferColorPrimariesKey] = (__bridge id)primaries;
|
|
688
|
+
if (matrix) tags[(id)kCVImageBufferYCbCrMatrixKey] = (__bridge id)matrix;
|
|
689
|
+
if (transfer) tags[(id)kCVImageBufferTransferFunctionKey] = (__bridge id)transfer;
|
|
690
|
+
CGColorSpaceRef cs = CVImageBufferCreateColorSpaceFromAttachments((__bridge CFDictionaryRef)tags);
|
|
691
|
+
CFRelease(primaries);
|
|
692
|
+
if (matrix) CFRelease(matrix);
|
|
693
|
+
if (transfer) CFRelease(transfer);
|
|
694
|
+
if (!cs) return false;
|
|
695
|
+
CFPropertyListRef named = CGColorSpaceCopyPropertyList(cs);
|
|
696
|
+
CGColorSpaceRelease(cs);
|
|
697
|
+
if (!named) return false;
|
|
698
|
+
IOSurfaceSetValue(ios, kIOSurfaceColorSpace, named);
|
|
699
|
+
CFRelease(named);
|
|
700
|
+
return true;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
void InitVideo(Napi::Env env, Napi::Object exports) {
|
|
704
|
+
exports.Set("createVideoSurface", Napi::Function::New(env, CreateVideoSurface));
|
|
705
|
+
exports.Set("writeVideoSurface", Napi::Function::New(env, WriteVideoSurface));
|
|
706
|
+
exports.Set("videoSurfaceIsInUse", Napi::Function::New(env, VideoSurfaceIsInUse));
|
|
707
|
+
exports.Set("releaseVideoSurface", Napi::Function::New(env, ReleaseVideoSurface));
|
|
708
|
+
exports.Set("videoFormats", Napi::Function::New(env, VideoFormats));
|
|
709
|
+
}
|