Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improved custom cursor + experimental toggle (#417)

Brendan Allan19424852cc1f
diff --git a/Cargo.lock b/Cargo.lock
index 2cfdb5625..0ee1a1b16 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -84,7 +84,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed7572b7ba83a31e20d1b48970ee402d2e3e0537dcfe0a3ff4d6eb7508617d43"
dependencies = [
"alsa-sys",
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"cfg-if 1.0.0",
"libc",
]
@@ -621,7 +621,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0"
dependencies = [
"annotate-snippets",
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"cexpr 0.6.0",
"clang-sys",
"itertools",
@@ -641,7 +641,7 @@ version = "0.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"cexpr 0.6.0",
"clang-sys",
"itertools",
@@ -682,9 +682,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
-version = "2.6.0"
+version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
+checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
dependencies = [
"serde",
]
@@ -808,9 +808,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]]
name = "bytemuck"
-version = "1.17.0"
+version = "1.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6fd4c6dcc3b0aea2f5c0b4b82c2b15fe39ddbc76041a310848f4706edf76bb31"
+checksum = "b6b1fc10dbac614ebc03540c9dbd60e83887fda27794998c6528f1782047d540"
dependencies = [
"bytemuck_derive",
]
@@ -853,7 +853,7 @@ version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"cairo-sys-rs",
"glib",
"libc",
@@ -1483,7 +1483,7 @@ version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f79398230a6e2c08f5c9760610eb6924b52aa9e7950a619602baba59dcbbdbb2"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block",
"cocoa-foundation 0.2.0",
"core-foundation 0.10.0",
@@ -1513,7 +1513,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e14045fb83be07b5acf1c0884b2180461635b433455fa35d1cd6f17f1450679d"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block",
"core-foundation 0.10.0",
"core-graphics-types 0.2.0",
@@ -1758,7 +1758,7 @@ version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"core-foundation 0.10.0",
"core-graphics-types 0.2.0",
"foreign-types 0.5.0",
@@ -1771,7 +1771,7 @@ version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32eb7c354ae9f6d437a6039099ce7ecd049337a8109b23d73e48e8ffba8e9cd5"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"core-foundation 0.9.4",
"core-graphics-types 0.1.3",
"foreign-types 0.5.0",
@@ -1795,7 +1795,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"core-foundation 0.10.0",
"libc",
]
@@ -1806,7 +1806,7 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e4583956b9806b69f73fcb23aee05eb3620efc282972f08f6a6db7504f8334d"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block",
"cfg-if 1.0.0",
"core-foundation 0.10.0",
@@ -2025,7 +2025,7 @@ version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"crossterm_winapi",
"libc",
"mio 0.8.11",
@@ -2113,7 +2113,7 @@ version = "22.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdbd1f579714e3c809ebd822c81ef148b1ceaeb3d535352afc73fd0c4c6a0017"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"libloading 0.8.5",
"winapi",
]
@@ -2609,7 +2609,7 @@ name = "ffmpeg-next"
version = "7.1.0"
source = "git+https://github.com/CapSoftware/rust-ffmpeg?rev=29433c248bcd#29433c248bcd4c126e27f7461010354dd62a462e"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"ffmpeg-sys-next",
"libc",
]
@@ -3116,7 +3116,7 @@ version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"futures-channel",
"futures-core",
"futures-executor",
@@ -3218,7 +3218,7 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbcd2dba93594b227a1f57ee09b8b9da8892c34d55aa332e034a228d0fe6a171"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"gpu-alloc-types",
]
@@ -3228,7 +3228,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98ff03b468aa837d70984d55f5d3f846f6ec31fe34bbb97c4f85219caeee1ca4"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
]
[[package]]
@@ -3250,7 +3250,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c08c1f623a8d0b722b8b99f821eb0ba672a1618f0d3b16ddbee1cedd2dd8557"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"gpu-descriptor-types",
"hashbrown 0.14.5",
]
@@ -3261,7 +3261,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
]
[[package]]
@@ -3373,7 +3373,7 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af2a7e73e1f34c48da31fb668a907f250794837e08faa144fd24f0b8b741e890"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"com",
"libc",
"libloading 0.8.5",
@@ -3934,7 +3934,7 @@ version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"serde",
"unicode-segmentation",
]
@@ -4098,7 +4098,7 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"libc",
"redox_syscall",
]
@@ -4109,7 +4109,7 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65f3a4b81b2a2d8c7f300643676202debd1b7c929dbf5c9bb89402ea11d19810"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"cc",
"convert_case 0.6.0",
"cookie-factory",
@@ -4302,7 +4302,7 @@ version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ecfd3296f8c56b7c1f6fbac3c71cefa9d78ce009850c45000015f206dc7fa21"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block",
"core-graphics-types 0.1.3",
"foreign-types 0.5.0",
@@ -4450,7 +4450,7 @@ checksum = "8bd5a652b6faf21496f2cfd88fc49989c8db0825d1f6746b1a71a6ede24a63ad"
dependencies = [
"arrayvec",
"bit-set",
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"cfg_aliases 0.1.1",
"codespan-reporting",
"hexf-parse",
@@ -4504,7 +4504,7 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2076a31b7010b17a38c01907c45b945e8f11495ee4dd588309718901b1f7a5b7"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"jni-sys",
"log",
"ndk-sys 0.5.0+25.2.9519653",
@@ -4518,7 +4518,7 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"jni-sys",
"log",
"ndk-sys 0.6.0+11769913",
@@ -4563,7 +4563,7 @@ version = "0.27.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"cfg-if 1.0.0",
"libc",
]
@@ -4574,7 +4574,7 @@ version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"cfg-if 1.0.0",
"cfg_aliases 0.2.1",
"libc",
@@ -4849,7 +4849,7 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block2 0.5.1",
"libc",
"objc2 0.5.2",
@@ -4865,7 +4865,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5906f93257178e2f7ae069efb89fbd6ee94f0592740b5f8a1512ca498814d0fb"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block2 0.6.0",
"libc",
"objc2 0.6.0",
@@ -4884,7 +4884,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c1948a9be5f469deadbd6bcb86ad7ff9e47b4f632380139722f7d9840c0d42c"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"objc2 0.6.0",
"objc2-foundation 0.3.0",
]
@@ -4895,7 +4895,7 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block2 0.5.1",
"objc2 0.5.2",
"objc2-foundation 0.2.2",
@@ -4907,7 +4907,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f860f8e841f6d32f754836f51e6bc7777cd7e7053cf18528233f6811d3eceb4"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"objc2 0.6.0",
"objc2-foundation 0.3.0",
]
@@ -4918,7 +4918,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daeaf60f25471d26948a1c2f840e3f7d86f4109e3af4e8e4b5cd70c39690d925"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"objc2 0.6.0",
]
@@ -4928,7 +4928,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dca602628b65356b6513290a21a6405b4d4027b8b250f0b98dddbb28b7de02"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"objc2 0.6.0",
"objc2-core-foundation",
"objc2-io-surface",
@@ -4977,7 +4977,7 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block2 0.5.1",
"dispatch",
"libc",
@@ -4990,7 +4990,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a21c6c9014b82c39515db5b396f91645182611c97d24637cf56ac01e5f8d998"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block2 0.6.0",
"libc",
"objc2 0.6.0",
@@ -5003,7 +5003,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "161a8b87e32610086e1a7a9e9ec39f84459db7b3a0881c1f16ca5a2605581c19"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"objc2 0.6.0",
"objc2-core-foundation",
]
@@ -5014,7 +5014,7 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block2 0.5.1",
"objc2 0.5.2",
"objc2-foundation 0.2.2",
@@ -5026,7 +5026,7 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6788b04a18ea31e3dc3ab256b8546639e5bbae07c1a0dc4ea8615252bc6aee9a"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"objc2 0.5.2",
"objc2-app-kit 0.2.2",
"objc2-foundation 0.2.2",
@@ -5038,7 +5038,7 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block2 0.5.1",
"objc2 0.5.2",
"objc2-foundation 0.2.2",
@@ -5051,7 +5051,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fb3794501bb1bee12f08dcad8c61f2a5875791ad1c6f47faa71a0f033f20071"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"objc2 0.6.0",
"objc2-foundation 0.3.0",
]
@@ -5062,7 +5062,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "777a571be14a42a3990d4ebedaeb8b54cd17377ec21b92e8200ac03797b3bee1"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"objc2 0.6.0",
"objc2-core-foundation",
"objc2-foundation 0.3.0",
@@ -5074,7 +5074,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b717127e4014b0f9f3e8bba3d3f2acec81f1bde01f656823036e823ed2c94dce"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block2 0.6.0",
"objc2 0.6.0",
"objc2-app-kit 0.3.0",
@@ -5164,7 +5164,7 @@ version = "0.10.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9529f4786b70a3e8c61e11179af17ab6188ad8d0ded78c5529441ed39d4bd9c1"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"cfg-if 1.0.0",
"foreign-types 0.3.2",
"libc",
@@ -5537,7 +5537,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08e645ba5c45109106d56610b3ee60eb13a6f2beb8b74f8dc8186cf261788dda"
dependencies = [
"anyhow",
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"libc",
"libspa",
"libspa-sys",
@@ -6049,7 +6049,7 @@ version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
]
[[package]]
@@ -6302,7 +6302,7 @@ version = "0.38.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "375116bee2be9ed569afe2154ea6a99dfdffd257f533f187498c2a8f5feaf4ee"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"errno",
"libc",
"linux-raw-sys",
@@ -6463,7 +6463,7 @@ version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"core-foundation 0.9.4",
"core-foundation-sys 0.8.7",
"libc",
@@ -7044,7 +7044,7 @@ version = "0.3.0+sdk-1.3.268.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
]
[[package]]
@@ -7230,7 +7230,7 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"core-foundation 0.9.4",
"system-configuration-sys",
]
@@ -7264,7 +7264,7 @@ version = "0.32.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63c8b1020610b9138dd7b1e06cf259ae91aa05c30f3bd0d6b42a03997b92dec1"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"core-foundation 0.10.0",
"core-graphics 0.24.0",
"crossbeam-channel",
@@ -7458,7 +7458,7 @@ name = "tauri-nspanel"
version = "2.0.1"
source = "git+https://github.com/ahkohd/tauri-nspanel?branch=v2#356843c8433f89feea4f0f666be8b8d73715a57a"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block",
"cocoa 0.26.0",
"core-foundation 0.10.0",
@@ -7787,7 +7787,7 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "234dd891cc7960fa28f93ea911f3e0d9ce8375ebf9ff303831bdd7a3443d5714"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"log",
"serde",
"serde_json",
@@ -8523,9 +8523,9 @@ checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d"
[[package]]
name = "unicode-xid"
-version = "0.2.5"
+version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "229730647fbc343e3a80e463c1db7f78f3855d3f3739bee0dda773c9a037c90a"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "untrusted"
@@ -8732,12 +8732,13 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
-version = "0.4.43"
+version = "0.4.50"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61e9300f63a621e96ed275155c108eb6f843b6a26d053f122ab69724559dc8ed"
+checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61"
dependencies = [
"cfg-if 1.0.0",
"js-sys",
+ "once_cell",
"wasm-bindgen",
"web-sys",
]
@@ -8807,7 +8808,7 @@ version = "0.31.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66249d3fc69f76fd74c82cc319300faa554e9d865dab1f7cd66cc20db10b280"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"rustix",
"wayland-backend",
"wayland-scanner",
@@ -8819,7 +8820,7 @@ version = "0.32.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd0ade57c4e6e9a8952741325c30bf82f4246885dca8bf561898b86d0c1f58e"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"wayland-backend",
"wayland-client",
"wayland-scanner",
@@ -8985,7 +8986,7 @@ checksum = "0348c840d1051b8e86c3bcd31206080c5e71e5933dabd79be1ce732b0b2f089a"
dependencies = [
"arrayvec",
"bit-vec",
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"cfg_aliases 0.1.1",
"document-features",
"indexmap 2.5.0",
@@ -9012,7 +9013,7 @@ dependencies = [
"arrayvec",
"ash",
"bit-set",
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"block",
"cfg_aliases 0.1.1",
"core-graphics-types 0.1.3",
@@ -9053,7 +9054,7 @@ version = "22.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc9d91f0e2c4b51434dfa6db77846f2793149d8e73f800fa2e41f52b8eac3c5d"
dependencies = [
- "bitflags 2.6.0",
+ "bitflags 2.9.0",
"js-sys",
"web-sys",
]
@@ -9069,9 +9070,9 @@ dependencies = [
[[package]]
name = "widestring"
-version = "1.1.0"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7219d36b6eac893fa81e84ebe06485e7dcbb616177469b142df14f1f4deb1311"
+checksum = "dd7cf3379ca1aac9eea11fba24fd7e315d621f8dfe35c8d7d2be8b793726e07d"
[[package]]
name = "winapi"
@@ -9095,7 +9096,7 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
dependencies = [
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs
index db1fdf59b..4849bb401 100644
--- a/apps/cli/src/main.rs
+++ b/apps/cli/src/main.rs
@@ -1,11 +1,15 @@
mod record;
-use std::{path::PathBuf, sync::Arc};
+use std::{
+ io::{stdout, Write},
+ path::PathBuf,
+ sync::Arc,
+};
use cap_editor::create_segments;
use cap_media::sources::get_target_fps;
use cap_project::{RecordingMeta, XY};
-use cap_rendering::RenderVideoConstants;
+use cap_rendering::{ProjectRecordings, RenderVideoConstants};
use clap::{Args, Parser, Subcommand};
use record::RecordStart;
use serde_json::json;
@@ -163,7 +167,8 @@ impl Export {
let recording_meta = RecordingMeta::load_for_project(&self.project_path).unwrap();
let meta = recording_meta.studio_meta().unwrap();
- let recordings = cap_rendering::ProjectRecordings::new(&recording_meta.project_path, meta);
+ let recordings =
+ Arc::new(ProjectRecordings::new(&recording_meta.project_path, meta).unwrap());
let render_options = cap_rendering::RenderOptions {
screen_size: XY::new(
@@ -183,18 +188,23 @@ impl Export {
let segments = create_segments(&recording_meta, meta).await.unwrap();
- let fps = meta.max_fps();
let project_output_path = self.project_path.join("output/result.mp4");
+ let mut stdout = stdout();
let exporter = cap_export::Exporter::new(
project,
project_output_path.clone(),
- |_| {},
+ move |f| {
+ print!("\rrendered frame {f}");
+
+ stdout.flush().unwrap();
+ },
self.project_path.clone(),
recording_meta,
render_constants,
&segments,
60,
XY::new(1920, 1080),
+ recordings.clone(),
)
.await
.unwrap();
diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rs
index 0e1a62d39..9b86f7c13 100644
--- a/apps/cli/src/record.rs
+++ b/apps/cli/src/record.rs
@@ -84,6 +84,7 @@ impl RecordStart {
},
camera.map(|c| Arc::new(Mutex::new(c))),
&None,
+ false,
)
.await
.map_err(|e| e.to_string())?;
diff --git a/apps/desktop/app.config.ts b/apps/desktop/app.config.ts
index f146a64e9..248890c4d 100644
--- a/apps/desktop/app.config.ts
+++ b/apps/desktop/app.config.ts
@@ -20,7 +20,7 @@ export default defineConfig({
// 3. to make use of `TAURI_DEBUG` and other env variables
// https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
envPrefix: ["VITE_", "TAURI_"],
- assetsInclude: ['**/*.riv'],
+ assetsInclude: ["**/*.riv"],
plugins: [
capUIPlugin,
tsconfigPaths({
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index 07d583756..bb8d60011 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -87,6 +87,7 @@ pub async fn export_video(
&editor_instance.segments,
fps,
resolution_base,
+ editor_instance.recordings.clone(),
)
.await
.map_err(|e| {
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index 3446b4699..a7ccbfcbd 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -53,6 +53,8 @@ pub struct GeneralSettingsStore {
pub post_studio_recording_behaviour: PostStudioRecordingBehaviour,
#[serde(default)]
pub main_window_recording_start_behaviour: MainWindowRecordingStartBehaviour,
+ #[serde(default)]
+ pub custom_cursor_capture: bool,
#[serde(default, alias = "open_editor_after_recording")]
#[deprecated]
_open_editor_after_recording: bool,
@@ -84,6 +86,7 @@ impl Default for GeneralSettingsStore {
window_transparency: false,
post_studio_recording_behaviour: PostStudioRecordingBehaviour::OpenEditor,
main_window_recording_start_behaviour: MainWindowRecordingStartBehaviour::Close,
+ custom_cursor_capture: false,
_open_editor_after_recording: false,
}
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 05a8e0078..c6673e9c7 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -975,9 +975,9 @@ struct SerializedEditorInstance {
frames_socket_url: String,
recording_duration: f64,
saved_project_config: ProjectConfiguration,
- recordings: ProjectRecordings,
+ recordings: Arc<ProjectRecordings>,
path: PathBuf,
- pretty_name: String,
+ meta: RecordingMeta,
}
#[tauri::command]
@@ -1003,7 +1003,7 @@ async fn create_editor_instance(
},
recordings: editor_instance.recordings.clone(),
path: editor_instance.project_path.clone(),
- pretty_name: meta.pretty_name,
+ meta,
})
}
@@ -1077,7 +1077,7 @@ async fn get_video_metadata(
StudioRecordingMeta::SingleSegment { segment } => {
vec![recording_meta.path(&segment.display.path)]
}
- StudioRecordingMeta::MultipleSegments { inner } => inner
+ StudioRecordingMeta::MultipleSegments { inner, .. } => inner
.segments
.iter()
.map(|s| recording_meta.path(&s.display.path))
@@ -2415,6 +2415,9 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
tokio::spawn(EditorInstances::remove(window.clone()));
}
CapWindowId::Settings | CapWindowId::Upgrade => {
+ if let Some(window) = CapWindowId::Main.get(&app) {
+ let _ = window.show();
+ }
// Don't quit the app when settings or upgrade window is closed
return;
}
@@ -2492,26 +2495,12 @@ async fn create_editor_instance_impl(
) -> Result<Arc<EditorInstance>, String> {
let app = app.clone();
- let instance = EditorInstance::new(
- recordings_path(&app),
- video_id,
- {
- let app = app.clone();
- move |state| {
- EditorStateChanged::new(state).emit(&app).ok();
- }
- },
- {
- let app = app.clone();
- move || {
- AuthStore::get(&app)
- .ok()
- .flatten()
- .map(|s| s.is_upgraded())
- .unwrap_or(false)
- }
- },
- )
+ let instance = EditorInstance::new(recordings_path(&app), video_id, {
+ let app = app.clone();
+ move |state| {
+ EditorStateChanged::new(state).emit(&app).ok();
+ }
+ })
.await?;
RenderFrameEvent::listen_any(&app, {
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 0a589249a..dd7dea55f 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -9,7 +9,7 @@ use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
fn main() {
// We have to hold onto the ClientInitGuard until the very end
let _guard = std::option_env!("CAP_DESKTOP_SENTRY_URL").map(|url| {
- Some(sentry::init((
+ sentry::init((
url,
sentry::ClientOptions {
release: sentry::release_name!(),
@@ -35,7 +35,7 @@ fn main() {
})),
..Default::default()
},
- )))
+ ))
});
let (layer, handle) = tracing_subscriber::reload::Layer::new(None::<DynLoggingLayer>);
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 249859197..969554908 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -246,6 +246,7 @@ pub async fn start_recording(
// done in spawn to catch panics just in case
let actor_done_rx = spawn_actor({
let state_mtx = Arc::clone(&state_mtx);
+ let app = app.clone();
async move {
fail!("recording::spawn_actor");
let mut state = state_mtx.write().await;
@@ -258,6 +259,11 @@ pub async fn start_recording(
recording_options.clone(),
state.camera_feed.clone(),
&state.mic_feed,
+ GeneralSettingsStore::get(&app)
+ .ok()
+ .flatten()
+ .map(|s| s.custom_cursor_capture)
+ .unwrap_or_default(),
)
.await
.map_err(|e| {
@@ -446,7 +452,7 @@ async fn handle_recording_finish(
StudioRecordingMeta::SingleSegment { segment } => {
segment.display.path.to_path(&recording_dir)
}
- StudioRecordingMeta::MultipleSegments { inner } => {
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
inner.segments[0].display.path.to_path(&recording_dir)
}
},
@@ -464,7 +470,7 @@ async fn handle_recording_finish(
let (meta_inner, sharing) = match completed_recording {
CompletedRecording::Studio(recording) => {
- let recordings = ProjectRecordings::new(&recording_dir, &recording.meta);
+ let recordings = ProjectRecordings::new(&recording_dir, &recording.meta)?;
let config = project_config_from_recording(
&recording,
@@ -532,7 +538,9 @@ async fn handle_recording_finish(
.await;
match resp {
- Ok(r) if r.status() == 204 => {
+ Ok(r)
+ if r.status().as_u16() >= 200 && r.status().as_u16() < 300 =>
+ {
info!("Screenshot uploaded successfully");
}
Ok(r) => {
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index 71c964dbf..39543ce49 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -189,6 +189,7 @@ impl ShowCapWindow {
.maximized(false)
.maximizable(false)
.always_on_top(true)
+ .visible_on_all_workspaces(true)
.center()
.build()?;
diff --git a/apps/desktop/src/declaration.d.ts b/apps/desktop/src/declaration.d.ts
index 1d471fb50..67704bd9c 100644
--- a/apps/desktop/src/declaration.d.ts
+++ b/apps/desktop/src/declaration.d.ts
@@ -1,5 +1,4 @@
-declare module '*.riv' {
- const src: string;
- export default src;
- }
-
\ No newline at end of file
+declare module "*.riv" {
+ const src: string;
+ export default src;
+}
diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsx
index 31fed2fa8..010402c31 100644
--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx
+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx
@@ -167,9 +167,10 @@ export default function () {
<Tooltip.Trigger>
<button
type="button"
- onClick={() =>
- commands.showWindow({ Settings: { page: "general" } })
- }
+ onClick={async () => {
+ await commands.showWindow({ Settings: { page: "general" } });
+ getCurrentWindow().hide();
+ }}
class="flex items-center justify-center w-5 h-5 -ml-[1.5px]"
>
<IconCapSettings class="text-gray-400 size-5 hover:text-gray-500" />
@@ -186,9 +187,10 @@ export default function () {
<Tooltip.Trigger>
<button
type="button"
- onClick={() =>
- commands.showWindow({ Settings: { page: "recordings" } })
- }
+ onClick={async () => {
+ await commands.showWindow({ Settings: { page: "recordings" } });
+ getCurrentWindow().hide();
+ }}
class="flex justify-center items-center w-5 h-5"
>
<IconLucideSquarePlay class="text-gray-400 size-5 hover:text-gray-500" />
@@ -1074,6 +1076,7 @@ function ChangelogButton() {
const handleChangelogClick = () => {
commands.showWindow({ Settings: { page: "changelog" } });
+ getCurrentWindow().hide();
const version = currentVersion();
if (version) {
setChangelogState({
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
index e9e439960..2109a449a 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
@@ -243,6 +243,12 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
<IconCapChevronDown class="size-4" />
</button>
</Setting>
+ <ToggleSetting
+ label="Enable custom cursor capture in Studio Mode (Experimental)"
+ description="Whether Studio Mode recordings should capture cursor state separately, for customisation (size, smoothing) in the editor. Currently experimental as cursor events may not be captured accurately."
+ value={!!settings.customCursorCapture}
+ onChange={(value) => handleChange("customCursorCapture", value)}
+ />
</div>
</div>
</div>
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index 3794d23f0..905a5a945 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -423,7 +423,14 @@ export function ConfigSidebar() {
// icon: IconCapMessageBubble,
// },
{ id: "audio" as const, icon: IconCapAudioOn },
- { id: "cursor" as const, icon: IconCapCursor },
+ {
+ id: "cursor" as const,
+ icon: IconCapCursor,
+ disabled: !(
+ editorInstance.meta.type === "multiple" &&
+ editorInstance.meta.segments[0].cursor
+ ),
+ },
// { id: "hotkeys" as const, icon: IconCapHotkeys },
]}
>
@@ -1405,73 +1412,71 @@ export function ConfigSidebar() {
</Field>
</KTabs.Content>
<KTabs.Content value="cursor" class="flex flex-col gap-6">
- {window.FLAGS.recordMouseState === true ? (
- <>
- <Field name="Cursor" icon={<IconCapCursor />}>
- <Subfield name="Hide cursor when not moving">
- <Toggle
- checked={project.cursor.hideWhenIdle}
- onChange={(v) => setProject("cursor", "hideWhenIdle", v)}
- />
- </Subfield>
- </Field>
- <Field name="Size" icon={<IconCapEnlarge />}>
- <Slider
- value={[project.cursor.size]}
- onChange={(v) => setProject("cursor", "size", v[0])}
- minValue={20}
- maxValue={300}
- step={1}
- />
- </Field>
- <KCollapsible open={!project.cursor.raw}>
- <Field
- name="Smooth Movement"
- icon={<IconHugeiconsEaseCurveControlPoints />}
- value={
- <Toggle
- checked={!project.cursor.raw}
- onChange={(value) => {
- setProject("cursor", "raw", !value);
- }}
- />
- }
+ <Field name="Cursor" icon={<IconCapCursor />}>
+ <Subfield name="Hide cursor when not moving">
+ <Toggle
+ checked={project.cursor.hideWhenIdle}
+ onChange={(v) => setProject("cursor", "hideWhenIdle", v)}
+ />
+ </Subfield>
+ </Field>
+ <Field name="Size" icon={<IconCapEnlarge />}>
+ <Slider
+ value={[project.cursor.size]}
+ onChange={(v) => setProject("cursor", "size", v[0])}
+ minValue={20}
+ maxValue={300}
+ step={1}
+ />
+ </Field>
+ <KCollapsible open={!project.cursor.raw}>
+ <Field
+ name="Smooth Movement"
+ icon={<IconHugeiconsEaseCurveControlPoints />}
+ value={
+ <Toggle
+ checked={!project.cursor.raw}
+ onChange={(value) => {
+ setProject("cursor", "raw", !value);
+ }}
/>
- <KCollapsible.Content class="overflow-hidden border-b border-gray-200 opacity-0 transition-opacity animate-collapsible-up ui-expanded:animate-collapsible-down ui-expanded:opacity-100">
- {/* if Content has padding or margin the animation doesn't look as good */}
- <div class="flex flex-col gap-4 pt-4 pb-6">
- <Field name="Tension">
- <Slider
- value={[project.cursor.tension]}
- onChange={(v) => setProject("cursor", "tension", v[0])}
- minValue={1}
- maxValue={500}
- step={1}
- />
- </Field>
- <Field name="Friction">
- <Slider
- value={[project.cursor.friction]}
- onChange={(v) => setProject("cursor", "friction", v[0])}
- minValue={0}
- maxValue={50}
- step={0.1}
- />
- </Field>
- <Field name="Mass">
- <Slider
- value={[project.cursor.mass]}
- onChange={(v) => setProject("cursor", "mass", v[0])}
- minValue={0.1}
- maxValue={10}
- step={0.01}
- />
- </Field>
- </div>
- </KCollapsible.Content>
- </KCollapsible>
+ }
+ />
+ <KCollapsible.Content class="overflow-hidden border-b border-gray-200 opacity-0 transition-opacity animate-collapsible-up ui-expanded:animate-collapsible-down ui-expanded:opacity-100">
+ {/* if Content has padding or margin the animation doesn't look as good */}
+ <div class="flex flex-col gap-4 pt-4 pb-6">
+ <Field name="Tension">
+ <Slider
+ value={[project.cursor.tension]}
+ onChange={(v) => setProject("cursor", "tension", v[0])}
+ minValue={1}
+ maxValue={500}
+ step={1}
+ />
+ </Field>
+ <Field name="Friction">
+ <Slider
+ value={[project.cursor.friction]}
+ onChange={(v) => setProject("cursor", "friction", v[0])}
+ minValue={0}
+ maxValue={50}
+ step={0.1}
+ />
+ </Field>
+ <Field name="Mass">
+ <Slider
+ value={[project.cursor.mass]}
+ onChange={(v) => setProject("cursor", "mass", v[0])}
+ minValue={0.1}
+ maxValue={10}
+ step={0.01}
+ />
+ </Field>
+ </div>
+ </KCollapsible.Content>
+ </KCollapsible>
- {/* <Field name="Motion Blur">
+ {/* <Field name="Motion Blur">
<Slider
value={[project.cursor.motionBlur]}
onChange={(v) => setProject("cursor", "motionBlur", v[0])}
@@ -1480,7 +1485,7 @@ export function ConfigSidebar() {
step={0.001}
/>
</Field> */}
- {/* <Field name="Animation Style" icon={<IconLucideRabbit />}>
+ {/* <Field name="Animation Style" icon={<IconLucideRabbit />}>
<RadioGroup
defaultValue="regular"
value={project.cursor.animationStyle}
@@ -1525,13 +1530,6 @@ export function ConfigSidebar() {
))}
</RadioGroup>
</Field> */}
- </>
- ) : (
- <div class="flex flex-col gap-2 justify-center items-center p-4 text-gray-400">
- <IconCapCursor class="size-6" />
- <span>Cursor settings coming soon</span>
- </div>
- )}
</KTabs.Content>
<KTabs.Content value="hotkeys">
<Field name="Hotkeys" icon={<IconCapHotkeys />}>
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 724bfc03d..e7b1b5b78 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -57,9 +57,7 @@ export function Editor() {
if (!editorInstance) return;
- return {
- editorInstance,
- };
+ return { editorInstance };
})()}
>
{(values) => (
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index 7e772b5c9..3bc265c14 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -76,7 +76,7 @@ export function Header() {
/>
<p class="text-sm text-gray-500">
- {editorInstance.prettyName}
+ {editorInstance.meta.prettyName}
<span class="text-sm text-gray-400">.cap</span>
</p>
{/* <ErrorBoundary fallback={<></>}>
diff --git a/apps/desktop/src/routes/editor/Timeline/context.ts b/apps/desktop/src/routes/editor/Timeline/context.ts
index 1c511a124..56a449d38 100644
--- a/apps/desktop/src/routes/editor/Timeline/context.ts
+++ b/apps/desktop/src/routes/editor/Timeline/context.ts
@@ -9,51 +9,52 @@ export const MAX_TIMELINE_MARKINGS = 20;
const TIMELINE_MARKING_RESOLUTIONS = [0.5, 1, 2.5, 5, 10, 30];
export const [TimelineContextProvider, useTimelineContext] =
- createContextProvider(
- (props: {
- duration: number;
- secsPerPixel: number;
- timelineBounds: Readonly<NullableBounds>;
- }) => {
- const { state } = useEditorContext();
-
- const markingResolution = () => TIMELINE_MARKING_RESOLUTIONS.find(
- (r) => state.timelineTransform.zoom / r <= MAX_TIMELINE_MARKINGS
- ) ?? 30;
-
- return {
- duration: () => props.duration,
- secsPerPixel: () => props.secsPerPixel,
- timelineBounds: props.timelineBounds,
- markingResolution
- }
- },
- null!
- );
+ createContextProvider(
+ (props: {
+ duration: number;
+ secsPerPixel: number;
+ timelineBounds: Readonly<NullableBounds>;
+ }) => {
+ const { state } = useEditorContext();
+
+ const markingResolution = () =>
+ TIMELINE_MARKING_RESOLUTIONS.find(
+ (r) => state.timelineTransform.zoom / r <= MAX_TIMELINE_MARKINGS
+ ) ?? 30;
+
+ return {
+ duration: () => props.duration,
+ secsPerPixel: () => props.secsPerPixel,
+ timelineBounds: props.timelineBounds,
+ markingResolution,
+ };
+ },
+ null!
+ );
export const [TrackContextProvider, useTrackContext] = createContextProvider(
- (props: { ref: Accessor<Element | undefined> }) => {
- const { state } = useEditorContext();
-
- const [trackState, setTrackState] = createStore({
- draggingSegment: false,
- });
- const bounds = createElementBounds(() => props.ref());
-
- const secsPerPixel = () =>
- state.timelineTransform.zoom / (bounds.width ?? 1);
-
- return {
- secsPerPixel,
- trackBounds: bounds,
- trackState,
- setTrackState,
- };
- },
- null!
+ (props: { ref: Accessor<Element | undefined> }) => {
+ const { state } = useEditorContext();
+
+ const [trackState, setTrackState] = createStore({
+ draggingSegment: false,
+ });
+ const bounds = createElementBounds(() => props.ref());
+
+ const secsPerPixel = () =>
+ state.timelineTransform.zoom / (bounds.width ?? 1);
+
+ return {
+ secsPerPixel,
+ trackBounds: bounds,
+ trackState,
+ setTrackState,
+ };
+ },
+ null!
);
export const [SegmentContextProvider, useSegmentContext] =
- createContextProvider((props: { width: Accessor<number> }) => {
- return props;
- }, null!);
+ createContextProvider((props: { width: Accessor<number> }) => {
+ return props;
+ }, null!);
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index 5b3f8498f..1548c4851 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -5,390 +5,428 @@ import { createEventListener } from "@solid-primitives/event-listener";
import { createUndoHistory } from "@solid-primitives/history";
import { debounce } from "@solid-primitives/scheduled";
import {
- Accessor,
- batch,
- createEffect,
- createResource,
- createSignal,
- on,
+ Accessor,
+ batch,
+ createEffect,
+ createResource,
+ createSignal,
+ on,
} from "solid-js";
import { createStore, reconcile, unwrap } from "solid-js/store";
import { createPresets } from "~/utils/createPresets";
import { createImageDataWS, createLazySignal } from "~/utils/socket";
import {
- commands,
- events,
- type ProjectConfiguration,
- type SerializedEditorInstance,
- type XY,
+ commands,
+ events,
+ InstantRecordingMeta,
+ MultipleSegments,
+ RecordingMeta,
+ SingleSegment,
+ StudioRecordingMeta,
+ type ProjectConfiguration,
+ type SerializedEditorInstance,
+ type XY,
} from "~/utils/tauri";
export type CurrentDialog =
- | { type: "createPreset" }
- | { type: "renamePreset"; presetIndex: number }
- | { type: "deletePreset"; presetIndex: number }
- | { type: "crop"; position: XY<number>; size: XY<number> }
- | { type: "export" };
+ | { type: "createPreset" }
+ | { type: "renamePreset"; presetIndex: number }
+ | { type: "deletePreset"; presetIndex: number }
+ | { type: "crop"; position: XY<number>; size: XY<number> }
+ | { type: "export" };
export type DialogState = { open: false } | ({ open: boolean } & CurrentDialog);
export const FPS = 60;
export const OUTPUT_SIZE = {
- x: 1920,
- y: 1080,
+ x: 1920,
+ y: 1080,
};
export const BACKGROUND_THEMES = {
- macOS: "macOS",
- dark: "Dark",
- blue: "Blue",
- purple: "Purple",
- orange: "Orange",
+ macOS: "macOS",
+ dark: "Dark",
+ blue: "Blue",
+ purple: "Purple",
+ orange: "Orange",
};
export const MAX_ZOOM_IN = 3;
export const [EditorContextProvider, useEditorContext] = createContextProvider(
- (props: { editorInstance: SerializedEditorInstance }) => {
- const editorInstanceContext = useEditorInstanceContext();
- const [project, setProject] = createStore<ProjectConfiguration>(
- props.editorInstance.savedProjectConfig
- );
-
- createEffect(
- on(
- () => {
- trackStore(project);
- },
- debounce(() => {
- commands.setProjectConfig(project);
- }),
- { defer: true }
- )
- );
-
- const [selectedTab, setSelectedTab] = createSignal<
- "background" | "camera" | "transcript" | "audio" | "cursor" | "hotkeys"
- >("background");
-
- //Background tabs
- const [backgroundTab, setBackgroundTab] =
- createSignal<keyof typeof BACKGROUND_THEMES>("macOS");
-
- const [dialog, setDialog] = createSignal<DialogState>({
- open: false,
- });
-
- const [previewTime, setPreviewTime] = createSignal<number>();
- const [playbackTime, setPlaybackTime] = createSignal<number>(0);
- const [playing, setPlaying] = createSignal(false);
-
- //Export states
-
- const [exportProgress, setExportProgress] = createSignal<{
- totalFrames: number;
- renderedFrames: number;
- } | null>(null);
-
- type ExportState =
- | { type: "idle" }
- | { type: "starting" }
- | { type: "rendering" }
- | { type: "saving"; done: boolean };
-
- type CopyState =
- | { type: "idle" }
- | { type: "starting" }
- | { type: "rendering" }
- | { type: "copying" }
- | { type: "copied" };
-
- const [exportState, setExportState] = createStore<ExportState>({
- type: "idle",
- });
-
- const [copyState, setCopyState] = createStore<CopyState>({
- type: "idle",
- });
-
- const [uploadState, setUploadState] = createStore<
- | { type: "idle" }
- | { type: "starting" }
- | { type: "rendering" }
- | { type: "uploading"; progress: number }
- | { type: "link-copied" }
- | { type: "complete" }
- >({ type: "idle" });
-
- //This is used in ShareButton.tsx to notify the component that the metadata has changed, from ExportDialog.tsx
- //When a video is uploaded, the metadata is updated
-
- const [lastMetaUpdate, setLastMetaUpdate] = createSignal<{
- videoId: string;
- timestamp: number;
- } | null>(null);
-
- const metaUpdateStore = {
- notifyUpdate: (videoId: string) => {
- setLastMetaUpdate({ videoId, timestamp: Date.now() });
- },
- getLastUpdate: lastMetaUpdate,
- };
-
- createEffect(
- on(playing, () => {
- if (!playing())
- commands.setPlayheadPosition(Math.floor(playbackTime() * FPS));
- })
- );
-
- const [split, setSplit] = createSignal(false);
-
- const totalDuration = () =>
- project.timeline?.segments.reduce(
- (acc, s) => acc + (s.end - s.start) / s.timescale,
- 0
- ) ?? props.editorInstance.recordingDuration;
-
- type State = {
- zoom: number;
- position: number;
- };
-
- const zoomOutLimit = () => Math.min(totalDuration(), 60 * 10);
-
- function updateZoom(state: State, newZoom: number, origin: number): State {
- const zoom = Math.max(Math.min(newZoom, zoomOutLimit()), MAX_ZOOM_IN);
-
- const visibleOrigin = origin - state.position;
-
- const originPercentage = Math.min(1, visibleOrigin / state.zoom);
-
- const newVisibleOrigin = zoom * originPercentage;
- const newPosition = origin - newVisibleOrigin;
-
- return {
- zoom,
- position: newPosition,
- };
- }
-
- const [state, setState] = createStore({
- timelineSelection: null as null | { type: "zoom"; index: number },
- timelineTransform: {
- // visible seconds
- zoom: zoomOutLimit(),
- updateZoom(z: number, origin: number) {
- const { zoom, position } = updateZoom(
- {
- zoom: state.timelineTransform.zoom,
- position: state.timelineTransform.position,
- },
- z,
- origin
- );
-
- const transform = state.timelineTransform;
- batch(() => {
- setState("timelineTransform", "zoom", zoom);
- if (transform.zoom !== zoom) return;
- transform.setPosition(position);
- });
- },
- // number of seconds of leftmost point
- position: 0,
- setPosition(p: number) {
- setState(
- "timelineTransform",
- "position",
- Math.min(
- Math.max(p, 0),
- Math.max(zoomOutLimit(), totalDuration()) + 4 - state.timelineTransform.zoom
- )
- );
- },
- },
- });
-
- return {
- ...editorInstanceContext,
- editorInstance: props.editorInstance,
- dialog,
- setDialog,
- project,
- setProject,
- selectedTab,
- backgroundTab,
- exportProgress,
- setExportProgress,
- copyState,
- setCopyState,
- uploadState,
- setUploadState,
- exportState,
- setExportState,
- setBackgroundTab,
- setSelectedTab,
- metaUpdateStore,
- lastMetaUpdate,
- setLastMetaUpdate,
- history: createStoreHistory(project, setProject),
- playbackTime,
- setPlaybackTime,
- playing,
- setPlaying,
- previewTime,
- setPreviewTime,
- split,
- setSplit,
- state,
- setState,
- totalDuration,
- zoomOutLimit,
- };
- },
- // biome-ignore lint/style/noNonNullAssertion: it's ok
- null!
+ (props: {
+ editorInstance: Omit<SerializedEditorInstance, "meta"> & {
+ meta: TransformedMeta;
+ };
+ }) => {
+ const editorInstanceContext = useEditorInstanceContext();
+ const [project, setProject] = createStore<ProjectConfiguration>(
+ props.editorInstance.savedProjectConfig
+ );
+
+ createEffect(
+ on(
+ () => {
+ trackStore(project);
+ },
+ debounce(() => {
+ commands.setProjectConfig(project);
+ }),
+ { defer: true }
+ )
+ );
+
+ const [selectedTab, setSelectedTab] = createSignal<
+ "background" | "camera" | "transcript" | "audio" | "cursor" | "hotkeys"
+ >("background");
+
+ //Background tabs
+ const [backgroundTab, setBackgroundTab] =
+ createSignal<keyof typeof BACKGROUND_THEMES>("macOS");
+
+ const [dialog, setDialog] = createSignal<DialogState>({
+ open: false,
+ });
+
+ const [previewTime, setPreviewTime] = createSignal<number>();
+ const [playbackTime, setPlaybackTime] = createSignal<number>(0);
+ const [playing, setPlaying] = createSignal(false);
+
+ //Export states
+
+ const [exportProgress, setExportProgress] = createSignal<{
+ totalFrames: number;
+ renderedFrames: number;
+ } | null>(null);
+
+ type ExportState =
+ | { type: "idle" }
+ | { type: "starting" }
+ | { type: "rendering" }
+ | { type: "saving"; done: boolean };
+
+ type CopyState =
+ | { type: "idle" }
+ | { type: "starting" }
+ | { type: "rendering" }
+ | { type: "copying" }
+ | { type: "copied" };
+
+ const [exportState, setExportState] = createStore<ExportState>({
+ type: "idle",
+ });
+
+ const [copyState, setCopyState] = createStore<CopyState>({
+ type: "idle",
+ });
+
+ const [uploadState, setUploadState] = createStore<
+ | { type: "idle" }
+ | { type: "starting" }
+ | { type: "rendering" }
+ | { type: "uploading"; progress: number }
+ | { type: "link-copied" }
+ | { type: "complete" }
+ >({ type: "idle" });
+
+ // This is used in ShareButton.tsx to notify the component that the metadata has changed, from ExportDialog.tsx
+ // When a video is uploaded, the metadata is updated
+
+ const [lastMetaUpdate, setLastMetaUpdate] = createSignal<{
+ videoId: string;
+ timestamp: number;
+ } | null>(null);
+
+ const metaUpdateStore = {
+ notifyUpdate: (videoId: string) => {
+ setLastMetaUpdate({ videoId, timestamp: Date.now() });
+ },
+ getLastUpdate: lastMetaUpdate,
+ };
+
+ createEffect(
+ on(playing, () => {
+ if (!playing())
+ commands.setPlayheadPosition(Math.floor(playbackTime() * FPS));
+ })
+ );
+
+ const [split, setSplit] = createSignal(false);
+
+ const totalDuration = () =>
+ project.timeline?.segments.reduce(
+ (acc, s) => acc + (s.end - s.start) / s.timescale,
+ 0
+ ) ?? props.editorInstance.recordingDuration;
+
+ type State = {
+ zoom: number;
+ position: number;
+ };
+
+ const zoomOutLimit = () => Math.min(totalDuration(), 60 * 10);
+
+ function updateZoom(state: State, newZoom: number, origin: number): State {
+ const zoom = Math.max(Math.min(newZoom, zoomOutLimit()), MAX_ZOOM_IN);
+
+ const visibleOrigin = origin - state.position;
+
+ const originPercentage = Math.min(1, visibleOrigin / state.zoom);
+
+ const newVisibleOrigin = zoom * originPercentage;
+ const newPosition = origin - newVisibleOrigin;
+
+ return {
+ zoom,
+ position: newPosition,
+ };
+ }
+
+ const [state, setState] = createStore({
+ timelineSelection: null as null | { type: "zoom"; index: number },
+ timelineTransform: {
+ // visible seconds
+ zoom: zoomOutLimit(),
+ updateZoom(z: number, origin: number) {
+ const { zoom, position } = updateZoom(
+ {
+ zoom: state.timelineTransform.zoom,
+ position: state.timelineTransform.position,
+ },
+ z,
+ origin
+ );
+
+ const transform = state.timelineTransform;
+ batch(() => {
+ setState("timelineTransform", "zoom", zoom);
+ if (transform.zoom !== zoom) return;
+ transform.setPosition(position);
+ });
+ },
+ // number of seconds of leftmost point
+ position: 0,
+ setPosition(p: number) {
+ setState(
+ "timelineTransform",
+ "position",
+ Math.min(
+ Math.max(p, 0),
+ Math.max(zoomOutLimit(), totalDuration()) +
+ 4 -
+ state.timelineTransform.zoom
+ )
+ );
+ },
+ },
+ });
+
+ return {
+ ...editorInstanceContext,
+ editorInstance: props.editorInstance,
+ dialog,
+ setDialog,
+ project,
+ setProject,
+ selectedTab,
+ backgroundTab,
+ exportProgress,
+ setExportProgress,
+ copyState,
+ setCopyState,
+ uploadState,
+ setUploadState,
+ exportState,
+ setExportState,
+ setBackgroundTab,
+ setSelectedTab,
+ metaUpdateStore,
+ lastMetaUpdate,
+ setLastMetaUpdate,
+ history: createStoreHistory(project, setProject),
+ playbackTime,
+ setPlaybackTime,
+ playing,
+ setPlaying,
+ previewTime,
+ setPreviewTime,
+ split,
+ setSplit,
+ state,
+ setState,
+ totalDuration,
+ zoomOutLimit,
+ };
+ },
+ // biome-ignore lint/style/noNonNullAssertion: it's ok
+ null!
);
export type FrameData = { width: number; height: number; data: ImageData };
+function transformMeta(instance: SerializedEditorInstance) {
+ if ("fps" in instance.meta) {
+ throw new Error("Instant mode recordings cannot be edited");
+ }
+
+ let meta;
+
+ if ("segments" in instance.meta) {
+ meta = {
+ ...instance.meta,
+ type: "multiple",
+ } as unknown as MultipleSegments & { type: "multiple" };
+ } else {
+ meta = {
+ ...instance.meta,
+ type: "single",
+ } as unknown as SingleSegment & { type: "single" };
+ }
+
+ return { ...meta, prettyName: instance.meta.pretty_name };
+}
+
+export type TransformedMeta = ReturnType<typeof transformMeta>;
+
export const [EditorInstanceContextProvider, useEditorInstanceContext] =
- createContextProvider((props: { videoId: string }) => {
- const [latestFrame, setLatestFrame] = createLazySignal<{
- width: number;
- data: ImageData;
- }>();
-
- const [editorInstance] = createResource(async () => {
- const instance = await commands.createEditorInstance(props.videoId);
-
- const [ws, isConnected] = createImageDataWS(
- instance.framesSocketUrl,
- setLatestFrame
- );
-
- createEffect(() => {
- if (isConnected()) {
- events.renderFrameEvent.emit({
- frame_number: Math.floor(0),
- fps: FPS,
- resolution_base: OUTPUT_SIZE,
- });
- }
- });
-
- return instance;
- });
-
- return {
- editorInstance,
- videoId: props.videoId,
- latestFrame,
- presets: createPresets(),
- prettyName: () => editorInstance()?.prettyName ?? "Cap Recording",
- };
- }, null!);
+ createContextProvider((props: { videoId: string }) => {
+ const [latestFrame, setLatestFrame] = createLazySignal<{
+ width: number;
+ data: ImageData;
+ }>();
+
+ const [editorInstance] = createResource(async () => {
+ const instance = await commands.createEditorInstance(props.videoId);
+
+ const [ws, isConnected] = createImageDataWS(
+ instance.framesSocketUrl,
+ setLatestFrame
+ );
+
+ createEffect(() => {
+ if (isConnected()) {
+ events.renderFrameEvent.emit({
+ frame_number: Math.floor(0),
+ fps: FPS,
+ resolution_base: OUTPUT_SIZE,
+ });
+ }
+ });
+
+ return {
+ ...instance,
+ meta: transformMeta(instance),
+ };
+ });
+
+ return {
+ editorInstance,
+ videoId: props.videoId,
+ latestFrame,
+ presets: createPresets(),
+ prettyName: () => editorInstance()?.meta.prettyName ?? "Cap Recording",
+ };
+ }, null!);
function createStoreHistory<T extends Static>(
- ...[state, setState]: ReturnType<typeof createStore<T>>
+ ...[state, setState]: ReturnType<typeof createStore<T>>
) {
- // not working properly yet
- // const getDelta = captureStoreUpdates(state);
-
- const [pauseCount, setPauseCount] = createSignal(0);
-
- const history = createUndoHistory(() => {
- if (pauseCount() > 0) return;
-
- trackStore(state);
-
- const copy = structuredClone(unwrap(state));
-
- return () => setState(reconcile(copy));
- });
-
- createEventListener(window, "keydown", (e) => {
- if (!(e.ctrlKey || e.metaKey)) return;
-
- switch (e.code) {
- case "KeyZ": {
- if (e.shiftKey) history.redo();
- else history.undo();
- break;
- }
- case "KeyY": {
- history.redo();
- break;
- }
- default: {
- return;
- }
- }
-
- e.preventDefault();
- e.stopPropagation();
- });
-
- return Object.assign(history, {
- pause() {
- setPauseCount(pauseCount() + 1);
-
- return () => {
- setPauseCount(pauseCount() - 1);
- };
- },
- isPaused: () => pauseCount() > 0,
- });
+ // not working properly yet
+ // const getDelta = captureStoreUpdates(state);
+
+ const [pauseCount, setPauseCount] = createSignal(0);
+
+ const history = createUndoHistory(() => {
+ if (pauseCount() > 0) return;
+
+ trackStore(state);
+
+ const copy = structuredClone(unwrap(state));
+
+ return () => setState(reconcile(copy));
+ });
+
+ createEventListener(window, "keydown", (e) => {
+ if (!(e.ctrlKey || e.metaKey)) return;
+
+ switch (e.code) {
+ case "KeyZ": {
+ if (e.shiftKey) history.redo();
+ else history.undo();
+ break;
+ }
+ case "KeyY": {
+ history.redo();
+ break;
+ }
+ default: {
+ return;
+ }
+ }
+
+ e.preventDefault();
+ e.stopPropagation();
+ });
+
+ return Object.assign(history, {
+ pause() {
+ setPauseCount(pauseCount() + 1);
+
+ return () => {
+ setPauseCount(pauseCount() - 1);
+ };
+ },
+ isPaused: () => pauseCount() > 0,
+ });
}
type Static<T = unknown> =
- | {
- [K in number | string]: T;
- }
- | T[];
+ | {
+ [K in number | string]: T;
+ }
+ | T[];
export const [TimelineContextProvider, useTimelineContext] =
- createContextProvider(
- (props: {
- duration: number;
- secsPerPixel: number;
- timelineBounds: Readonly<NullableBounds>;
- }) => {
- return {
- duration: () => props.duration,
- secsPerPixel: () => props.secsPerPixel,
- timelineBounds: props.timelineBounds,
- };
- },
- null!
- );
+ createContextProvider(
+ (props: {
+ duration: number;
+ secsPerPixel: number;
+ timelineBounds: Readonly<NullableBounds>;
+ }) => {
+ return {
+ duration: () => props.duration,
+ secsPerPixel: () => props.secsPerPixel,
+ timelineBounds: props.timelineBounds,
+ };
+ },
+ null!
+ );
export const [TrackContextProvider, useTrackContext] = createContextProvider(
- (props: { ref: Accessor<Element | undefined> }) => {
- const { state } = useEditorContext();
-
- const [trackState, setTrackState] = createStore({
- draggingSegment: false,
- });
- const bounds = createElementBounds(() => props.ref());
-
- const secsPerPixel = () =>
- state.timelineTransform.zoom / (bounds.width ?? 1);
-
- return {
- secsPerPixel,
- trackBounds: bounds,
- trackState,
- setTrackState,
- };
- },
- null!
+ (props: { ref: Accessor<Element | undefined> }) => {
+ const { state } = useEditorContext();
+
+ const [trackState, setTrackState] = createStore({
+ draggingSegment: false,
+ });
+ const bounds = createElementBounds(() => props.ref());
+
+ const secsPerPixel = () =>
+ state.timelineTransform.zoom / (bounds.width ?? 1);
+
+ return {
+ secsPerPixel,
+ trackBounds: bounds,
+ trackState,
+ setTrackState,
+ };
+ },
+ null!
);
export const [SegmentContextProvider, useSegmentContext] =
- createContextProvider((props: { width: Accessor<number> }) => {
- return props;
- }, null!);
+ createContextProvider((props: { width: Accessor<number> }) => {
+ return props;
+ }, null!);
diff --git a/apps/desktop/src/utils/analytics.ts b/apps/desktop/src/utils/analytics.ts
index f7138067e..7b8b8092a 100644
--- a/apps/desktop/src/utils/analytics.ts
+++ b/apps/desktop/src/utils/analytics.ts
@@ -8,12 +8,12 @@ let isPostHogInitialized = false;
if (key && host) {
try {
- posthog.init(key, {
+ posthog.init(key, {
api_host: host,
capture_pageview: false,
loaded: (posthogInstance) => {
isPostHogInitialized = true;
- }
+ },
});
console.log("PostHog initialization started");
} catch (error) {
@@ -26,7 +26,7 @@ export function initAnonymousUser() {
console.warn("Cannot initialize anonymous user - missing key or host");
return;
}
-
+
try {
const anonymousId = localStorage.getItem("anonymous_id") ?? uuid();
localStorage.setItem("anonymous_id", anonymousId);
@@ -42,7 +42,7 @@ export function identifyUser(userId: string, properties?: Record<string, any>) {
console.warn("Cannot identify user - missing key or host");
return;
}
-
+
try {
const currentId = posthog.get_distinct_id();
const anonymousId = localStorage.getItem("anonymous_id");
@@ -71,10 +71,13 @@ export function trackEvent(
properties?: Record<string, any>
) {
if (!key || !host) {
- console.warn("PostHog event not captured - missing key or host:", eventName);
+ console.warn(
+ "PostHog event not captured - missing key or host:",
+ eventName
+ );
return;
}
-
+
try {
if (!isPostHogInitialized) {
console.warn(`PostHog not initialized yet, queuing event: ${eventName}`);
@@ -85,7 +88,7 @@ export function trackEvent(
}, 1000);
return;
}
-
+
const eventProperties = { ...properties, platform: "desktop" };
console.log(`Capturing event ${eventName}:`, eventProperties);
posthog.capture(eventName, eventProperties);
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 66c060958..758d06ae5 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -1,393 +1,654 @@
-
// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.
/** user-defined commands **/
-
export const commands = {
-async getRecordingOptions() : Promise<RecordingOptions> {
+ async getRecordingOptions(): Promise<RecordingOptions> {
return await TAURI_INVOKE("get_recording_options");
-},
-async setRecordingOptions(options: RecordingOptions) : Promise<null> {
+ },
+ async setRecordingOptions(options: RecordingOptions): Promise<null> {
return await TAURI_INVOKE("set_recording_options", { options });
-},
-async startRecording(recordingOptions: RecordingOptions | null) : Promise<null> {
+ },
+ async startRecording(
+ recordingOptions: RecordingOptions | null
+ ): Promise<null> {
return await TAURI_INVOKE("start_recording", { recordingOptions });
-},
-async stopRecording() : Promise<null> {
+ },
+ async stopRecording(): Promise<null> {
return await TAURI_INVOKE("stop_recording");
-},
-async pauseRecording() : Promise<null> {
+ },
+ async pauseRecording(): Promise<null> {
return await TAURI_INVOKE("pause_recording");
-},
-async resumeRecording() : Promise<null> {
+ },
+ async resumeRecording(): Promise<null> {
return await TAURI_INVOKE("resume_recording");
-},
-async listCameras() : Promise<string[]> {
+ },
+ async listCameras(): Promise<string[]> {
return await TAURI_INVOKE("list_cameras");
-},
-async listCaptureWindows() : Promise<CaptureWindow[]> {
+ },
+ async listCaptureWindows(): Promise<CaptureWindow[]> {
return await TAURI_INVOKE("list_capture_windows");
-},
-async listCaptureScreens() : Promise<CaptureScreen[]> {
+ },
+ async listCaptureScreens(): Promise<CaptureScreen[]> {
return await TAURI_INVOKE("list_capture_screens");
-},
-async takeScreenshot() : Promise<null> {
+ },
+ async takeScreenshot(): Promise<null> {
return await TAURI_INVOKE("take_screenshot");
-},
-async listAudioDevices() : Promise<string[]> {
+ },
+ async listAudioDevices(): Promise<string[]> {
return await TAURI_INVOKE("list_audio_devices");
-},
-async closeRecordingsOverlayWindow() : Promise<void> {
+ },
+ async closeRecordingsOverlayWindow(): Promise<void> {
await TAURI_INVOKE("close_recordings_overlay_window");
-},
-async setFakeWindowBounds(name: string, bounds: Bounds) : Promise<null> {
+ },
+ async setFakeWindowBounds(name: string, bounds: Bounds): Promise<null> {
return await TAURI_INVOKE("set_fake_window_bounds", { name, bounds });
-},
-async removeFakeWindow(name: string) : Promise<null> {
+ },
+ async removeFakeWindow(name: string): Promise<null> {
return await TAURI_INVOKE("remove_fake_window", { name });
-},
-async focusCapturesPanel() : Promise<void> {
+ },
+ async focusCapturesPanel(): Promise<void> {
await TAURI_INVOKE("focus_captures_panel");
-},
-async getCurrentRecording() : Promise<JsonValue<CurrentRecording | null>> {
+ },
+ async getCurrentRecording(): Promise<JsonValue<CurrentRecording | null>> {
return await TAURI_INVOKE("get_current_recording");
-},
-async exportVideo(videoId: string, progress: TAURI_CHANNEL<RenderProgress>, force: boolean, fps: number, resolutionBase: XY<number>) : Promise<string> {
- return await TAURI_INVOKE("export_video", { videoId, progress, force, fps, resolutionBase });
-},
-async getExportEstimates(videoId: string, resolution: XY<number>, fps: number) : Promise<ExportEstimates> {
- return await TAURI_INVOKE("get_export_estimates", { videoId, resolution, fps });
-},
-async copyFileToPath(src: string, dst: string) : Promise<null> {
+ },
+ async exportVideo(
+ videoId: string,
+ progress: TAURI_CHANNEL<RenderProgress>,
+ force: boolean,
+ fps: number,
+ resolutionBase: XY<number>
+ ): Promise<string> {
+ return await TAURI_INVOKE("export_video", {
+ videoId,
+ progress,
+ force,
+ fps,
+ resolutionBase,
+ });
+ },
+ async getExportEstimates(
+ videoId: string,
+ resolution: XY<number>,
+ fps: number
+ ): Promise<ExportEstimates> {
+ return await TAURI_INVOKE("get_export_estimates", {
+ videoId,
+ resolution,
+ fps,
+ });
+ },
+ async copyFileToPath(src: string, dst: string): Promise<null> {
return await TAURI_INVOKE("copy_file_to_path", { src, dst });
-},
-async copyVideoToClipboard(path: string) : Promise<null> {
+ },
+ async copyVideoToClipboard(path: string): Promise<null> {
return await TAURI_INVOKE("copy_video_to_clipboard", { path });
-},
-async copyScreenshotToClipboard(path: string) : Promise<null> {
+ },
+ async copyScreenshotToClipboard(path: string): Promise<null> {
return await TAURI_INVOKE("copy_screenshot_to_clipboard", { path });
-},
-async openFilePath(path: string) : Promise<null> {
+ },
+ async openFilePath(path: string): Promise<null> {
return await TAURI_INVOKE("open_file_path", { path });
-},
-async getVideoMetadata(videoId: string, videoType: VideoType | null) : Promise<VideoRecordingMetadata> {
+ },
+ async getVideoMetadata(
+ videoId: string,
+ videoType: VideoType | null
+ ): Promise<VideoRecordingMetadata> {
return await TAURI_INVOKE("get_video_metadata", { videoId, videoType });
-},
-async createEditorInstance(videoId: string) : Promise<SerializedEditorInstance> {
+ },
+ async createEditorInstance(
+ videoId: string
+ ): Promise<SerializedEditorInstance> {
return await TAURI_INVOKE("create_editor_instance", { videoId });
-},
-async startPlayback(fps: number, resolutionBase: XY<number>) : Promise<null> {
+ },
+ async startPlayback(fps: number, resolutionBase: XY<number>): Promise<null> {
return await TAURI_INVOKE("start_playback", { fps, resolutionBase });
-},
-async stopPlayback() : Promise<null> {
+ },
+ async stopPlayback(): Promise<null> {
return await TAURI_INVOKE("stop_playback");
-},
-async setPlayheadPosition(frameNumber: number) : Promise<null> {
+ },
+ async setPlayheadPosition(frameNumber: number): Promise<null> {
return await TAURI_INVOKE("set_playhead_position", { frameNumber });
-},
-async setProjectConfig(config: ProjectConfiguration) : Promise<null> {
+ },
+ async setProjectConfig(config: ProjectConfiguration): Promise<null> {
return await TAURI_INVOKE("set_project_config", { config });
-},
-async openEditor(id: string) : Promise<null> {
+ },
+ async openEditor(id: string): Promise<null> {
return await TAURI_INVOKE("open_editor", { id });
-},
-async openPermissionSettings(permission: OSPermission) : Promise<void> {
+ },
+ async openPermissionSettings(permission: OSPermission): Promise<void> {
await TAURI_INVOKE("open_permission_settings", { permission });
-},
-async doPermissionsCheck(initialCheck: boolean) : Promise<OSPermissionsCheck> {
+ },
+ async doPermissionsCheck(initialCheck: boolean): Promise<OSPermissionsCheck> {
return await TAURI_INVOKE("do_permissions_check", { initialCheck });
-},
-async requestPermission(permission: OSPermission) : Promise<void> {
+ },
+ async requestPermission(permission: OSPermission): Promise<void> {
await TAURI_INVOKE("request_permission", { permission });
-},
-async uploadExportedVideo(videoId: string, mode: UploadMode) : Promise<UploadResult> {
+ },
+ async uploadExportedVideo(
+ videoId: string,
+ mode: UploadMode
+ ): Promise<UploadResult> {
return await TAURI_INVOKE("upload_exported_video", { videoId, mode });
-},
-async uploadScreenshot(screenshotPath: string) : Promise<UploadResult> {
+ },
+ async uploadScreenshot(screenshotPath: string): Promise<UploadResult> {
return await TAURI_INVOKE("upload_screenshot", { screenshotPath });
-},
-async getRecordingMeta(id: string, fileType: string) : Promise<RecordingMetaWithType> {
+ },
+ async getRecordingMeta(
+ id: string,
+ fileType: string
+ ): Promise<RecordingMetaWithType> {
return await TAURI_INVOKE("get_recording_meta", { id, fileType });
-},
-async saveFileDialog(fileName: string, fileType: string) : Promise<string | null> {
+ },
+ async saveFileDialog(
+ fileName: string,
+ fileType: string
+ ): Promise<string | null> {
return await TAURI_INVOKE("save_file_dialog", { fileName, fileType });
-},
-async listRecordings() : Promise<([string, string, RecordingMetaWithType])[]> {
+ },
+ async listRecordings(): Promise<[string, string, RecordingMetaWithType][]> {
return await TAURI_INVOKE("list_recordings");
-},
-async listScreenshots() : Promise<([string, string, RecordingMeta])[]> {
+ },
+ async listScreenshots(): Promise<[string, string, RecordingMeta][]> {
return await TAURI_INVOKE("list_screenshots");
-},
-async checkUpgradedAndUpdate() : Promise<boolean> {
+ },
+ async checkUpgradedAndUpdate(): Promise<boolean> {
return await TAURI_INVOKE("check_upgraded_and_update");
-},
-async openExternalLink(url: string) : Promise<null> {
+ },
+ async openExternalLink(url: string): Promise<null> {
return await TAURI_INVOKE("open_external_link", { url });
-},
-async setHotkey(action: HotkeyAction, hotkey: Hotkey | null) : Promise<null> {
+ },
+ async setHotkey(action: HotkeyAction, hotkey: Hotkey | null): Promise<null> {
return await TAURI_INVOKE("set_hotkey", { action, hotkey });
-},
-async resetCameraPermissions() : Promise<null> {
+ },
+ async resetCameraPermissions(): Promise<null> {
return await TAURI_INVOKE("reset_camera_permissions");
-},
-async resetMicrophonePermissions() : Promise<null> {
+ },
+ async resetMicrophonePermissions(): Promise<null> {
return await TAURI_INVOKE("reset_microphone_permissions");
-},
-async isCameraWindowOpen() : Promise<boolean> {
+ },
+ async isCameraWindowOpen(): Promise<boolean> {
return await TAURI_INVOKE("is_camera_window_open");
-},
-async seekTo(frameNumber: number) : Promise<null> {
+ },
+ async seekTo(frameNumber: number): Promise<null> {
return await TAURI_INVOKE("seek_to", { frameNumber });
-},
-async positionTrafficLights(controlsInset: [number, number] | null) : Promise<void> {
+ },
+ async positionTrafficLights(
+ controlsInset: [number, number] | null
+ ): Promise<void> {
await TAURI_INVOKE("position_traffic_lights", { controlsInset });
-},
-async setTheme(theme: AppTheme) : Promise<void> {
+ },
+ async setTheme(theme: AppTheme): Promise<void> {
await TAURI_INVOKE("set_theme", { theme });
-},
-async globalMessageDialog(message: string) : Promise<void> {
+ },
+ async globalMessageDialog(message: string): Promise<void> {
await TAURI_INVOKE("global_message_dialog", { message });
-},
-async showWindow(window: ShowCapWindow) : Promise<null> {
+ },
+ async showWindow(window: ShowCapWindow): Promise<null> {
return await TAURI_INVOKE("show_window", { window });
-},
-async writeClipboardString(text: string) : Promise<null> {
+ },
+ async writeClipboardString(text: string): Promise<null> {
return await TAURI_INVOKE("write_clipboard_string", { text });
-},
-async performHapticFeedback(pattern: HapticPattern | null, time: HapticPerformanceTime | null) : Promise<null> {
+ },
+ async performHapticFeedback(
+ pattern: HapticPattern | null,
+ time: HapticPerformanceTime | null
+ ): Promise<null> {
return await TAURI_INVOKE("perform_haptic_feedback", { pattern, time });
-},
-async getWallpaperPath(filename: string) : Promise<string> {
+ },
+ async getWallpaperPath(filename: string): Promise<string> {
return await TAURI_INVOKE("get_wallpaper_path", { filename });
-},
-async listFails() : Promise<{ [key in string]: boolean }> {
+ },
+ async listFails(): Promise<{ [key in string]: boolean }> {
return await TAURI_INVOKE("list_fails");
-},
-async setFail(name: string, value: boolean) : Promise<void> {
+ },
+ async setFail(name: string, value: boolean): Promise<void> {
await TAURI_INVOKE("set_fail", { name, value });
-},
-async updateAuthPlan() : Promise<void> {
+ },
+ async updateAuthPlan(): Promise<void> {
await TAURI_INVOKE("update_auth_plan");
-},
-async reuploadInstantVideo(videoId: string) : Promise<null> {
+ },
+ async reuploadInstantVideo(videoId: string): Promise<null> {
return await TAURI_INVOKE("reupload_instant_video", { videoId });
-},
-async setWindowTransparent(value: boolean) : Promise<void> {
+ },
+ async setWindowTransparent(value: boolean): Promise<void> {
await TAURI_INVOKE("set_window_transparent", { value });
-}
-}
+ },
+};
/** user-defined events **/
-
export const events = __makeEvents__<{
-audioInputLevelChange: AudioInputLevelChange,
-authenticationInvalid: AuthenticationInvalid,
-currentRecordingChanged: CurrentRecordingChanged,
-editorStateChanged: EditorStateChanged,
-newNotification: NewNotification,
-newScreenshotAdded: NewScreenshotAdded,
-newStudioRecordingAdded: NewStudioRecordingAdded,
-recordingMetaChanged: RecordingMetaChanged,
-recordingOptionsChanged: RecordingOptionsChanged,
-recordingStarted: RecordingStarted,
-recordingStopped: RecordingStopped,
-renderFrameEvent: RenderFrameEvent,
-requestNewScreenshot: RequestNewScreenshot,
-requestOpenSettings: RequestOpenSettings,
-requestRestartRecording: RequestRestartRecording,
-requestStartRecording: RequestStartRecording,
-requestStopRecording: RequestStopRecording,
-uploadProgress: UploadProgress
+ audioInputLevelChange: AudioInputLevelChange;
+ authenticationInvalid: AuthenticationInvalid;
+ currentRecordingChanged: CurrentRecordingChanged;
+ editorStateChanged: EditorStateChanged;
+ newNotification: NewNotification;
+ newScreenshotAdded: NewScreenshotAdded;
+ newStudioRecordingAdded: NewStudioRecordingAdded;
+ recordingMetaChanged: RecordingMetaChanged;
+ recordingOptionsChanged: RecordingOptionsChanged;
+ recordingStarted: RecordingStarted;
+ recordingStopped: RecordingStopped;
+ renderFrameEvent: RenderFrameEvent;
+ requestNewScreenshot: RequestNewScreenshot;
+ requestOpenSettings: RequestOpenSettings;
+ requestRestartRecording: RequestRestartRecording;
+ requestStartRecording: RequestStartRecording;
+ requestStopRecording: RequestStopRecording;
+ uploadProgress: UploadProgress;
}>({
-audioInputLevelChange: "audio-input-level-change",
-authenticationInvalid: "authentication-invalid",
-currentRecordingChanged: "current-recording-changed",
-editorStateChanged: "editor-state-changed",
-newNotification: "new-notification",
-newScreenshotAdded: "new-screenshot-added",
-newStudioRecordingAdded: "new-studio-recording-added",
-recordingMetaChanged: "recording-meta-changed",
-recordingOptionsChanged: "recording-options-changed",
-recordingStarted: "recording-started",
-recordingStopped: "recording-stopped",
-renderFrameEvent: "render-frame-event",
-requestNewScreenshot: "request-new-screenshot",
-requestOpenSettings: "request-open-settings",
-requestRestartRecording: "request-restart-recording",
-requestStartRecording: "request-start-recording",
-requestStopRecording: "request-stop-recording",
-uploadProgress: "upload-progress"
-})
+ audioInputLevelChange: "audio-input-level-change",
+ authenticationInvalid: "authentication-invalid",
+ currentRecordingChanged: "current-recording-changed",
+ editorStateChanged: "editor-state-changed",
+ newNotification: "new-notification",
+ newScreenshotAdded: "new-screenshot-added",
+ newStudioRecordingAdded: "new-studio-recording-added",
+ recordingMetaChanged: "recording-meta-changed",
+ recordingOptionsChanged: "recording-options-changed",
+ recordingStarted: "recording-started",
+ recordingStopped: "recording-stopped",
+ renderFrameEvent: "render-frame-event",
+ requestNewScreenshot: "request-new-screenshot",
+ requestOpenSettings: "request-open-settings",
+ requestRestartRecording: "request-restart-recording",
+ requestStartRecording: "request-start-recording",
+ requestStopRecording: "request-stop-recording",
+ uploadProgress: "upload-progress",
+});
/** user-defined constants **/
-
-
/** user-defined types **/
-export type AppTheme = "system" | "light" | "dark"
-export type AspectRatio = "wide" | "vertical" | "square" | "classic" | "tall"
-export type Audio = { duration: number; sample_rate: number; channels: number }
-export type AudioConfiguration = { mute: boolean; improve: boolean }
-export type AudioInputLevelChange = number
-export type AudioMeta = { path: string;
-/**
- * unix time of the first frame
- */
-start_time?: number | null }
-export type AuthStore = { token: string; user_id: string | null; expires: number; plan: Plan | null; intercom_hash: string | null }
-export type AuthenticationInvalid = null
-export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; inset: number; crop: Crop | null; shadow?: number; advancedShadow?: ShadowConfiguration | null }
-export type BackgroundSource = { type: "wallpaper"; path: string | null } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number] } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number }
-export type Bounds = { x: number; y: number; width: number; height: number }
-export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition; size: number; zoom_size: number | null; rounding?: number; shadow?: number; advanced_shadow?: ShadowConfiguration | null }
-export type CameraPosition = { x: CameraXPosition; y: CameraYPosition }
-export type CameraXPosition = "left" | "center" | "right"
-export type CameraYPosition = "top" | "bottom"
-export type CaptureScreen = { id: number; name: string; refresh_rate: number }
-export type CaptureWindow = { id: number; owner_name: string; name: string; bounds: Bounds; refresh_rate: number }
-export type CommercialLicense = { licenseKey: string; expiryDate: number | null; refresh: number; activatedOn: number }
-export type Crop = { position: XY<number>; size: XY<number> }
-export type CurrentRecording = { target: CurrentRecordingTarget; type: RecordingType }
-export type CurrentRecordingChanged = null
-export type CurrentRecordingTarget = { window: { id: number; bounds: Bounds } } | { screen: { id: number } } | { area: { screen: number; bounds: Bounds } }
-export type CursorAnimationStyle = "regular" | "slow" | "fast"
-export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: CursorType; animationStyle: CursorAnimationStyle; tension: number; mass: number; friction: number; raw?: boolean; motionBlur?: number }
-export type CursorMeta = { imagePath: string; hotspot: XY<number> }
-export type CursorType = "pointer" | "circle"
-export type Cursors = { [key in string]: string } | { [key in string]: CursorMeta }
-export type EditorStateChanged = { playhead_position: number }
-export type ExportEstimates = { duration_seconds: number; estimated_time_seconds: number; estimated_size_mb: number }
-export type Flags = { recordMouseState: boolean; systemAudioRecording: boolean; split: boolean }
-export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour;
-/**
- * @deprecated
- */
-openEditorAfterRecording?: boolean }
-export type HapticPattern = "Alignment" | "LevelChange" | "Generic"
-export type HapticPerformanceTime = "Default" | "Now" | "DrawCompleted"
-export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }
-export type HotkeyAction = "startRecording" | "stopRecording" | "restartRecording"
-export type HotkeysConfiguration = { show: boolean }
-export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }
-export type InstantRecordingMeta = { fps: number; sample_rate: number | null }
-export type JsonValue<T> = [T]
-export type MainWindowRecordingStartBehaviour = "close" | "minimise"
-export type MultipleSegment = { display: VideoMeta; camera?: VideoMeta | null; audio?: AudioMeta | null; system_audio?: AudioMeta | null; cursor?: string | null }
-export type MultipleSegments = { segments: MultipleSegment[]; cursors: Cursors }
-export type NewNotification = { title: string; body: string; is_error: boolean }
-export type NewScreenshotAdded = { path: string }
-export type NewStudioRecordingAdded = { path: string }
-export type OSPermission = "screenRecording" | "camera" | "microphone" | "accessibility"
-export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"
-export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; camera: OSPermissionStatus; accessibility: OSPermissionStatus }
-export type Plan = { upgraded: boolean; manual: boolean; last_checked: number }
-export type PostStudioRecordingBehaviour = "openEditor" | "showOverlay"
-export type Preset = { name: string; config: ProjectConfiguration }
-export type PresetsStore = { presets: Preset[]; default: number | null }
-export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null }
-export type ProjectRecordings = { segments: SegmentRecordings[] }
-export type RecordingMeta = (StudioRecordingMeta | InstantRecordingMeta) & { pretty_name: string; sharing?: SharingMeta | null }
-export type RecordingMetaChanged = { id: string }
-export type RecordingMetaWithType = ((StudioRecordingMeta | InstantRecordingMeta) & { pretty_name: string; sharing?: SharingMeta | null }) & { type: RecordingType }
-export type RecordingMode = "studio" | "instant"
-export type RecordingOptions = { captureTarget: ScreenCaptureTarget; micName: string | null; cameraLabel: string | null; captureSystemAudio?: boolean; mode: RecordingMode }
-export type RecordingOptionsChanged = null
-export type RecordingStarted = null
-export type RecordingStopped = { path: string }
-export type RecordingType = "studio" | "instant"
-export type RenderFrameEvent = { frame_number: number; fps: number; resolution_base: XY<number> }
-export type RenderProgress = { type: "Starting"; total_frames: number } | { type: "EstimatedTotalFrames"; total_frames: number } | { type: "FrameRendered"; current_frame: number }
-export type RequestNewScreenshot = null
-export type RequestOpenSettings = { page: string }
-export type RequestRestartRecording = null
-export type RequestStartRecording = null
-export type RequestStopRecording = null
-export type S3UploadMeta = { id: string; user_id: string; aws_region?: string; aws_bucket?: string; aws_endpoint?: string }
-export type ScreenCaptureTarget = { variant: "window"; id: number } | { variant: "screen"; id: number } | { variant: "area"; screen: number; bounds: Bounds }
-export type SegmentRecordings = { display: Video; camera: Video | null; audio: Audio | null; system_audio: Audio | null }
-export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordings; path: string; prettyName: string }
-export type ShadowConfiguration = { size: number; opacity: number; blur: number }
-export type SharingMeta = { id: string; link: string }
-export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_id: string } } | "RecordingsOverlay" | "WindowCaptureOccluder" | { CaptureArea: { screen_id: number } } | { Camera: { ws_port: number } } | { InProgressRecording: { position: [number, number] | null } } | "Upgrade" | "SignIn" | "ModeSelect"
-export type SingleSegment = { display: VideoMeta; camera?: VideoMeta | null; audio?: AudioMeta | null; cursor?: string | null }
-export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }
-export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[] }
-export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number }
-export type UploadMode = { Initial: { pre_created_video: VideoUploadInfo | null } } | "Reupload"
-export type UploadProgress = { progress: number; message: string }
-export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"
-export type Video = { duration: number; width: number; height: number; fps: number }
-export type VideoMeta = { path: string; fps?: number;
-/**
- * unix time of the first frame
- */
-start_time?: number | null }
-export type VideoRecordingMetadata = { duration: number; size: number }
-export type VideoType = "screen" | "output" | "camera"
-export type VideoUploadInfo = { id: string; link: string; config: S3UploadMeta }
-export type XY<T> = { x: T; y: T }
-export type ZoomMode = "auto" | { manual: { x: number; y: number } }
-export type ZoomSegment = { start: number; end: number; amount: number; mode: ZoomMode }
+export type AppTheme = "system" | "light" | "dark";
+export type AspectRatio = "wide" | "vertical" | "square" | "classic" | "tall";
+export type Audio = {
+ duration: number;
+ sample_rate: number;
+ channels: number;
+ start_time: number;
+};
+export type AudioConfiguration = { mute: boolean; improve: boolean };
+export type AudioInputLevelChange = number;
+export type AudioMeta = {
+ path: string;
+ /**
+ * unix time of the first frame
+ */
+ start_time?: number | null;
+};
+export type AuthStore = {
+ token: string;
+ user_id: string | null;
+ expires: number;
+ plan: Plan | null;
+ intercom_hash: string | null;
+};
+export type AuthenticationInvalid = null;
+export type BackgroundConfiguration = {
+ source: BackgroundSource;
+ blur: number;
+ padding: number;
+ rounding: number;
+ inset: number;
+ crop: Crop | null;
+ shadow?: number;
+ advancedShadow?: ShadowConfiguration | null;
+};
+export type BackgroundSource =
+ | { type: "wallpaper"; path: string | null }
+ | { type: "image"; path: string | null }
+ | { type: "color"; value: [number, number, number] }
+ | {
+ type: "gradient";
+ from: [number, number, number];
+ to: [number, number, number];
+ angle?: number;
+ };
+export type Bounds = { x: number; y: number; width: number; height: number };
+export type Camera = {
+ hide: boolean;
+ mirror: boolean;
+ position: CameraPosition;
+ size: number;
+ zoom_size: number | null;
+ rounding?: number;
+ shadow?: number;
+ advanced_shadow?: ShadowConfiguration | null;
+};
+export type CameraPosition = { x: CameraXPosition; y: CameraYPosition };
+export type CameraXPosition = "left" | "center" | "right";
+export type CameraYPosition = "top" | "bottom";
+export type CaptureScreen = { id: number; name: string; refresh_rate: number };
+export type CaptureWindow = {
+ id: number;
+ owner_name: string;
+ name: string;
+ bounds: Bounds;
+ refresh_rate: number;
+};
+export type CommercialLicense = {
+ licenseKey: string;
+ expiryDate: number | null;
+ refresh: number;
+ activatedOn: number;
+};
+export type Crop = { position: XY<number>; size: XY<number> };
+export type CurrentRecording = {
+ target: CurrentRecordingTarget;
+ type: RecordingType;
+};
+export type CurrentRecordingChanged = null;
+export type CurrentRecordingTarget =
+ | { window: { id: number; bounds: Bounds } }
+ | { screen: { id: number } }
+ | { area: { screen: number; bounds: Bounds } };
+export type CursorAnimationStyle = "regular" | "slow" | "fast";
+export type CursorConfiguration = {
+ hideWhenIdle: boolean;
+ size: number;
+ type: CursorType;
+ animationStyle: CursorAnimationStyle;
+ tension: number;
+ mass: number;
+ friction: number;
+ raw?: boolean;
+ motionBlur?: number;
+};
+export type CursorMeta = { imagePath: string; hotspot: XY<number> };
+export type CursorType = "pointer" | "circle";
+export type Cursors =
+ | { [key in string]: string }
+ | { [key in string]: CursorMeta };
+export type EditorStateChanged = { playhead_position: number };
+export type ExportEstimates = {
+ duration_seconds: number;
+ estimated_time_seconds: number;
+ estimated_size_mb: number;
+};
+export type Flags = { systemAudioRecording: boolean; split: boolean };
+export type GeneralSettingsStore = {
+ instanceId?: string;
+ uploadIndividualFiles?: boolean;
+ hideDockIcon?: boolean;
+ hapticsEnabled?: boolean;
+ autoCreateShareableLink?: boolean;
+ enableNotifications?: boolean;
+ disableAutoOpenLinks?: boolean;
+ hasCompletedStartup?: boolean;
+ theme?: AppTheme;
+ commercialLicense?: CommercialLicense | null;
+ lastVersion?: string | null;
+ windowTransparency?: boolean;
+ postStudioRecordingBehaviour?: PostStudioRecordingBehaviour;
+ mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour;
+ customCursorCapture?: boolean;
+ /**
+ * @deprecated
+ */
+ openEditorAfterRecording?: boolean;
+};
+export type HapticPattern = "Alignment" | "LevelChange" | "Generic";
+export type HapticPerformanceTime = "Default" | "Now" | "DrawCompleted";
+export type Hotkey = {
+ code: string;
+ meta: boolean;
+ ctrl: boolean;
+ alt: boolean;
+ shift: boolean;
+};
+export type HotkeyAction =
+ | "startRecording"
+ | "stopRecording"
+ | "restartRecording";
+export type HotkeysConfiguration = { show: boolean };
+export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } };
+export type InstantRecordingMeta = { fps: number; sample_rate: number | null };
+export type JsonValue<T> = [T];
+export type MainWindowRecordingStartBehaviour = "close" | "minimise";
+export type MultipleSegment = {
+ display: VideoMeta;
+ camera?: VideoMeta | null;
+ mic?: AudioMeta | null;
+ system_audio?: AudioMeta | null;
+ cursor?: string | null;
+};
+export type MultipleSegments = {
+ segments: MultipleSegment[];
+ cursors: Cursors;
+};
+export type NewNotification = {
+ title: string;
+ body: string;
+ is_error: boolean;
+};
+export type NewScreenshotAdded = { path: string };
+export type NewStudioRecordingAdded = { path: string };
+export type OSPermission =
+ | "screenRecording"
+ | "camera"
+ | "microphone"
+ | "accessibility";
+export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied";
+export type OSPermissionsCheck = {
+ screenRecording: OSPermissionStatus;
+ microphone: OSPermissionStatus;
+ camera: OSPermissionStatus;
+ accessibility: OSPermissionStatus;
+};
+export type Plan = { upgraded: boolean; manual: boolean; last_checked: number };
+export type PostStudioRecordingBehaviour = "openEditor" | "showOverlay";
+export type Preset = { name: string; config: ProjectConfiguration };
+export type PresetsStore = { presets: Preset[]; default: number | null };
+export type ProjectConfiguration = {
+ aspectRatio: AspectRatio | null;
+ background: BackgroundConfiguration;
+ camera: Camera;
+ audio: AudioConfiguration;
+ cursor: CursorConfiguration;
+ hotkeys: HotkeysConfiguration;
+ timeline?: TimelineConfiguration | null;
+};
+export type ProjectRecordings = { segments: SegmentRecordings[] };
+export type RecordingMeta = (StudioRecordingMeta | InstantRecordingMeta) & {
+ pretty_name: string;
+ sharing?: SharingMeta | null;
+};
+export type RecordingMetaChanged = { id: string };
+export type RecordingMetaWithType = ((
+ | StudioRecordingMeta
+ | InstantRecordingMeta
+) & { pretty_name: string; sharing?: SharingMeta | null }) & {
+ type: RecordingType;
+};
+export type RecordingMode = "studio" | "instant";
+export type RecordingOptions = {
+ captureTarget: ScreenCaptureTarget;
+ micName: string | null;
+ cameraLabel: string | null;
+ captureSystemAudio?: boolean;
+ mode: RecordingMode;
+};
+export type RecordingOptionsChanged = null;
+export type RecordingStarted = null;
+export type RecordingStopped = { path: string };
+export type RecordingType = "studio" | "instant";
+export type RenderFrameEvent = {
+ frame_number: number;
+ fps: number;
+ resolution_base: XY<number>;
+};
+export type RenderProgress =
+ | { type: "Starting"; total_frames: number }
+ | { type: "EstimatedTotalFrames"; total_frames: number }
+ | { type: "FrameRendered"; current_frame: number };
+export type RequestNewScreenshot = null;
+export type RequestOpenSettings = { page: string };
+export type RequestRestartRecording = null;
+export type RequestStartRecording = null;
+export type RequestStopRecording = null;
+export type S3UploadMeta = {
+ id: string;
+ user_id: string;
+ aws_region?: string;
+ aws_bucket?: string;
+ aws_endpoint?: string;
+};
+export type ScreenCaptureTarget =
+ | { variant: "window"; id: number }
+ | { variant: "screen"; id: number }
+ | { variant: "area"; screen: number; bounds: Bounds };
+export type SegmentRecordings = {
+ display: Video;
+ camera: Video | null;
+ mic: Audio | null;
+ system_audio: Audio | null;
+};
+export type SerializedEditorInstance = {
+ framesSocketUrl: string;
+ recordingDuration: number;
+ savedProjectConfig: ProjectConfiguration;
+ recordings: ProjectRecordings;
+ path: string;
+ meta: RecordingMeta;
+};
+export type ShadowConfiguration = {
+ size: number;
+ opacity: number;
+ blur: number;
+};
+export type SharingMeta = { id: string; link: string };
+export type ShowCapWindow =
+ | "Setup"
+ | "Main"
+ | { Settings: { page: string | null } }
+ | { Editor: { project_id: string } }
+ | "RecordingsOverlay"
+ | "WindowCaptureOccluder"
+ | { CaptureArea: { screen_id: number } }
+ | { Camera: { ws_port: number } }
+ | { InProgressRecording: { position: [number, number] | null } }
+ | "Upgrade"
+ | "SignIn"
+ | "ModeSelect";
+export type SingleSegment = {
+ display: VideoMeta;
+ camera?: VideoMeta | null;
+ audio?: AudioMeta | null;
+ cursor?: string | null;
+};
+export type StudioRecordingMeta =
+ | { segment: SingleSegment }
+ | { inner: MultipleSegments };
+export type TimelineConfiguration = {
+ segments: TimelineSegment[];
+ zoomSegments: ZoomSegment[];
+};
+export type TimelineSegment = {
+ recordingSegment?: number;
+ timescale: number;
+ start: number;
+ end: number;
+};
+export type UploadMode =
+ | { Initial: { pre_created_video: VideoUploadInfo | null } }
+ | "Reupload";
+export type UploadProgress = { progress: number; message: string };
+export type UploadResult =
+ | { Success: string }
+ | "NotAuthenticated"
+ | "PlanCheckFailed"
+ | "UpgradeRequired";
+export type Video = {
+ duration: number;
+ width: number;
+ height: number;
+ fps: number;
+ start_time: number;
+};
+export type VideoMeta = {
+ path: string;
+ fps?: number;
+ /**
+ * unix time of the first frame
+ */
+ start_time?: number | null;
+};
+export type VideoRecordingMetadata = { duration: number; size: number };
+export type VideoType = "screen" | "output" | "camera";
+export type VideoUploadInfo = {
+ id: string;
+ link: string;
+ config: S3UploadMeta;
+};
+export type XY<T> = { x: T; y: T };
+export type ZoomMode = "auto" | { manual: { x: number; y: number } };
+export type ZoomSegment = {
+ start: number;
+ end: number;
+ amount: number;
+ mode: ZoomMode;
+};
/** tauri-specta globals **/
import {
- invoke as TAURI_INVOKE,
- Channel as TAURI_CHANNEL,
+ invoke as TAURI_INVOKE,
+ Channel as TAURI_CHANNEL,
} from "@tauri-apps/api/core";
import * as TAURI_API_EVENT from "@tauri-apps/api/event";
import { type WebviewWindow as __WebviewWindow__ } from "@tauri-apps/api/webviewWindow";
type __EventObj__<T> = {
- listen: (
- cb: TAURI_API_EVENT.EventCallback<T>,
- ) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
- once: (
- cb: TAURI_API_EVENT.EventCallback<T>,
- ) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
- emit: null extends T
- ? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
- : (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
+ listen: (
+ cb: TAURI_API_EVENT.EventCallback<T>
+ ) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
+ once: (
+ cb: TAURI_API_EVENT.EventCallback<T>
+ ) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
+ emit: null extends T
+ ? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
+ : (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
};
export type Result<T, E> =
- | { status: "ok"; data: T }
- | { status: "error"; error: E };
+ | { status: "ok"; data: T }
+ | { status: "error"; error: E };
function __makeEvents__<T extends Record<string, any>>(
- mappings: Record<keyof T, string>,
+ mappings: Record<keyof T, string>
) {
- return new Proxy(
- {} as unknown as {
- [K in keyof T]: __EventObj__<T[K]> & {
- (handle: __WebviewWindow__): __EventObj__<T[K]>;
- };
- },
- {
- get: (_, event) => {
- const name = mappings[event as keyof T];
+ return new Proxy(
+ {} as unknown as {
+ [K in keyof T]: __EventObj__<T[K]> & {
+ (handle: __WebviewWindow__): __EventObj__<T[K]>;
+ };
+ },
+ {
+ get: (_, event) => {
+ const name = mappings[event as keyof T];
- return new Proxy((() => {}) as any, {
- apply: (_, __, [window]: [__WebviewWindow__]) => ({
- listen: (arg: any) => window.listen(name, arg),
- once: (arg: any) => window.once(name, arg),
- emit: (arg: any) => window.emit(name, arg),
- }),
- get: (_, command: keyof __EventObj__<any>) => {
- switch (command) {
- case "listen":
- return (arg: any) => TAURI_API_EVENT.listen(name, arg);
- case "once":
- return (arg: any) => TAURI_API_EVENT.once(name, arg);
- case "emit":
- return (arg: any) => TAURI_API_EVENT.emit(name, arg);
- }
- },
- });
- },
- },
- );
+ return new Proxy((() => {}) as any, {
+ apply: (_, __, [window]: [__WebviewWindow__]) => ({
+ listen: (arg: any) => window.listen(name, arg),
+ once: (arg: any) => window.once(name, arg),
+ emit: (arg: any) => window.emit(name, arg),
+ }),
+ get: (_, command: keyof __EventObj__<any>) => {
+ switch (command) {
+ case "listen":
+ return (arg: any) => TAURI_API_EVENT.listen(name, arg);
+ case "once":
+ return (arg: any) => TAURI_API_EVENT.once(name, arg);
+ case "emit":
+ return (arg: any) => TAURI_API_EVENT.emit(name, arg);
+ }
+ },
+ });
+ },
+ }
+ );
}
diff --git a/apps/discord-bot/src/index.ts b/apps/discord-bot/src/index.ts
index d0cf8537f..ad8ec0a8b 100644
--- a/apps/discord-bot/src/index.ts
+++ b/apps/discord-bot/src/index.ts
@@ -37,14 +37,14 @@ type InteractionBody = {
type MessageComponent =
| {
- type: 1;
- components: Array<Exclude<MessageComponent, { type: 1 }>>;
- }
+ type: 1;
+ components: Array<Exclude<MessageComponent, { type: 1 }>>;
+ }
| ({
- type: 2;
- label?: string;
- disabled?: boolean;
- } & ({ style: 1 | 2 | 3 | 4; custom_id: string } | { style: 5; url: string } | { style: 6; sku_id: string }));
+ type: 2;
+ label?: string;
+ disabled?: boolean;
+ } & ({ style: 1 | 2 | 3 | 4; custom_id: string } | { style: 5; url: string } | { style: 6; sku_id: string }));
type Message = {
content?: string;
diff --git a/apps/web/.gitignore b/apps/web/.gitignore
index 90f1072a5..9fc69c18a 100644
--- a/apps/web/.gitignore
+++ b/apps/web/.gitignore
@@ -33,4 +33,4 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
-pnpm-lock.yaml
\ No newline at end of file
+pnpm-lock.yaml
diff --git a/apps/web/app/api/settings/billing/subscribe/route.ts b/apps/web/app/api/settings/billing/subscribe/route.ts
index 0def5ef7c..ef98c6faa 100644
--- a/apps/web/app/api/settings/billing/subscribe/route.ts
+++ b/apps/web/app/api/settings/billing/subscribe/route.ts
@@ -37,11 +37,11 @@ export async function POST(request: NextRequest) {
try {
// Track subscription initiated event
- if (typeof window !== 'undefined') {
+ if (typeof window !== "undefined") {
posthog.capture("subscription_initiated", {
price_id: priceId,
quantity: quantity,
- platform: "web"
+ platform: "web",
});
}
diff --git a/apps/web/app/api/video/og/route.tsx b/apps/web/app/api/video/og/route.tsx
index 6e3958249..d233f1ff7 100644
--- a/apps/web/app/api/video/og/route.tsx
+++ b/apps/web/app/api/video/og/route.tsx
@@ -11,9 +11,9 @@ import { eq } from "drizzle-orm";
export async function GET(req: NextRequest) {
const videoId = req.nextUrl.searchParams.get("videoId") as string;
- const response = await getData(videoId);
+ const videoData = await getData(videoId);
- if (!response) {
+ if (!videoData) {
return new ImageResponse(
(
<div
@@ -41,7 +41,7 @@ export async function GET(req: NextRequest) {
);
}
- const { video, bucket } = response;
+ const { video, bucket } = videoData;
if (!video || !bucket || video.public === false) {
return new ImageResponse(
diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.ts
index 73a9af076..cb998f08f 100644
--- a/apps/web/app/api/webhooks/stripe/route.ts
+++ b/apps/web/app/api/webhooks/stripe/route.ts
@@ -5,7 +5,7 @@ import { eq } from "drizzle-orm";
import { NextResponse } from "next/server";
import Stripe from "stripe";
import { serverEnv } from "@cap/env";
-import { PostHog } from 'posthog-node';
+import { PostHog } from "posthog-node";
const relevantEvents = new Set([
"checkout.session.completed",
@@ -198,25 +198,25 @@ export const POST = async (req: Request) => {
try {
// Initialize server-side PostHog
const serverPostHog = new PostHog(
- process.env.NEXT_PUBLIC_POSTHOG_KEY || '',
- { host: process.env.NEXT_PUBLIC_POSTHOG_HOST || '' }
+ process.env.NEXT_PUBLIC_POSTHOG_KEY || "",
+ { host: process.env.NEXT_PUBLIC_POSTHOG_HOST || "" }
);
-
+
// Track subscription completed event
serverPostHog.capture({
distinctId: dbUser.id,
- event: 'subscription_completed',
+ event: "subscription_completed",
properties: {
subscription_id: subscription.id,
subscription_status: subscription.status,
invite_quota: inviteQuota,
price_id: subscription.items.data[0]?.price.id,
quantity: inviteQuota,
- platform: 'web',
- is_first_subscription: true
- }
+ platform: "web",
+ is_first_subscription: true,
+ },
});
-
+
// Shutdown the client
await serverPostHog.shutdown();
console.log("Successfully tracked subscription event in PostHog");
diff --git a/apps/web/app/utils/analytics.ts b/apps/web/app/utils/analytics.ts
index ddef1b6e8..f6db8de1b 100644
--- a/apps/web/app/utils/analytics.ts
+++ b/apps/web/app/utils/analytics.ts
@@ -3,11 +3,11 @@ import posthog from "posthog-js";
export function initAnonymousUser() {
try {
- if (!posthog || typeof posthog.identify !== 'function') {
+ if (!posthog || typeof posthog.identify !== "function") {
console.warn("PostHog not available for anonymous user");
return;
}
-
+
const anonymousId = localStorage.getItem("anonymous_id") ?? uuid.v4();
localStorage.setItem("anonymous_id", anonymousId);
posthog.identify(anonymousId);
@@ -18,11 +18,11 @@ export function initAnonymousUser() {
export function identifyUser(userId: string, properties?: Record<string, any>) {
try {
- if (!posthog || typeof posthog.identify !== 'function') {
+ if (!posthog || typeof posthog.identify !== "function") {
console.warn("PostHog not available for user identification");
return;
}
-
+
const currentId = posthog.get_distinct_id();
const anonymousId = localStorage.getItem("anonymous_id");
@@ -46,11 +46,11 @@ export function trackEvent(
properties?: Record<string, any>
) {
try {
- if (!posthog || typeof posthog.capture !== 'function') {
+ if (!posthog || typeof posthog.capture !== "function") {
console.warn(`PostHog not available for event: ${eventName}`);
return;
}
-
+
posthog.capture(eventName, { ...properties, platform: "web" });
} catch (error) {
console.error(`Error tracking event ${eventName}:`, error);
diff --git a/crates/audio/src/audio_data.rs b/crates/audio/src/audio_data.rs
index e8fb91b75..b2c3bc98b 100644
--- a/crates/audio/src/audio_data.rs
+++ b/crates/audio/src/audio_data.rs
@@ -1,6 +1,7 @@
use ffmpeg::{
codec as avcodec,
format::{self as avformat},
+ ChannelLayout,
};
use std::path::Path;
@@ -31,6 +32,9 @@ impl AudioData {
.audio()
.map_err(|e| format!("Set Parameters / {e}"))?;
+ if decoder.channel_layout().is_empty() {
+ decoder.set_channel_layout(ChannelLayout::default(decoder.channels() as i32));
+ }
decoder.set_packet_time_base(input_stream.time_base());
let mut resampler = ffmpeg::software::resampler(
@@ -63,7 +67,7 @@ impl AudioData {
while let Ok(_) = decoder.receive_frame(&mut decoded_frame) {
let resample_delay = resampler
.run(&decoded_frame, &mut resampled_frame)
- .map_err(|e| format!("Run Resampler / {e}"))?;
+ .map_err(|e| format!("Run Resampler / {e:?}"))?;
let slice = &resampled_frame.data(0)
[0..resampled_frame.samples() * 4 * resampled_frame.channels() as usize];
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 2575ae0fc..6393be77d 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -40,8 +40,8 @@ impl Renderer {
frame_tx: flume::Sender<WSFrame>,
recording_meta: &RecordingMeta,
meta: &StudioRecordingMeta,
- ) -> RendererHandle {
- let recordings = ProjectRecordings::new(&recording_meta.project_path, meta);
+ ) -> Result<RendererHandle, String> {
+ let recordings = Arc::new(ProjectRecordings::new(&recording_meta.project_path, meta)?);
let mut max_duration = recordings.duration();
// Check camera duration if it exists
@@ -66,7 +66,7 @@ impl Renderer {
tokio::spawn(this.run());
- RendererHandle { tx }
+ Ok(RendererHandle { tx })
}
async fn run(mut self) {
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index 95cab8004..314f95d4f 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -20,7 +20,7 @@ pub struct EditorInstance {
pub project_path: PathBuf,
pub id: String,
pub ws_port: u16,
- pub recordings: ProjectRecordings,
+ pub recordings: Arc<ProjectRecordings>,
pub renderer: Arc<editor::RendererHandle>,
pub render_constants: Arc<RenderVideoConstants>,
pub state: Arc<Mutex<EditorState>>,
@@ -52,7 +52,6 @@ impl EditorInstance {
projects_path: PathBuf,
video_id: &str,
on_state_change: impl Fn(&EditorState) + Send + Sync + 'static,
- get_is_upgraded: impl Fn() -> bool + Send + 'static,
) -> Result<Arc<Self>, String> {
sentry::configure_scope(|scope| {
scope.set_tag("crate", "editor");
@@ -78,7 +77,7 @@ impl EditorInstance {
return Err("Cannot edit non-studio recordings".to_string());
};
let project = recording_meta.project_config();
- let recordings = ProjectRecordings::new(&recording_meta.project_path, meta);
+ let recordings = Arc::new(ProjectRecordings::new(&recording_meta.project_path, meta)?);
let render_options = RenderOptions {
screen_size: XY::new(
@@ -108,7 +107,7 @@ impl EditorInstance {
frame_tx,
&recording_meta,
meta,
- ));
+ )?);
let (preview_tx, preview_rx) = watch::channel(None);
@@ -132,10 +131,8 @@ impl EditorInstance {
meta: recording_meta,
});
- this.state.lock().await.preview_task = Some(
- this.clone()
- .spawn_preview_renderer(preview_rx, get_is_upgraded),
- );
+ this.state.lock().await.preview_task =
+ Some(this.clone().spawn_preview_renderer(preview_rx));
Ok(this)
}
@@ -244,7 +241,6 @@ impl EditorInstance {
fn spawn_preview_renderer(
self: Arc<Self>,
mut preview_rx: watch::Receiver<Option<(u32, u32, XY<u32>)>>,
- get_is_upgraded: impl Fn() -> bool + Send + 'static,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
loop {
@@ -353,6 +349,7 @@ pub async fn create_segments(
display: recording_meta.path(&s.display.path),
camera: s.camera.as_ref().map(|c| recording_meta.path(&c.path)),
},
+ 0,
)
.await
.map_err(|e| format!("SingleSegment / {e}"))?;
@@ -364,12 +361,12 @@ pub async fn create_segments(
decoders,
}])
}
- cap_project::StudioRecordingMeta::MultipleSegments { inner } => {
+ cap_project::StudioRecordingMeta::MultipleSegments { inner, .. } => {
let mut segments = vec![];
for (i, s) in inner.segments.iter().enumerate() {
let audio = s
- .audio
+ .mic
.as_ref()
.map(|audio| {
AudioData::from_file(recording_meta.path(&audio.path))
@@ -397,6 +394,7 @@ pub async fn create_segments(
display: recording_meta.path(&s.display.path),
camera: s.camera.as_ref().map(|c| recording_meta.path(&c.path)),
},
+ i,
)
.await
.map_err(|e| format!("MultipleSegments {i} / {e}"))?;
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index 82d6815d3..148d57406 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -9,7 +9,6 @@ use cpal::{
BufferSize, SampleFormat,
};
use tokio::{sync::watch, time::Instant};
-use tracing::debug;
use crate::editor;
use crate::editor_instance::Segment;
@@ -89,14 +88,12 @@ impl Playback {
if let Some((segment_time, segment_i)) = project.get_segment_time(time) {
let segment = &self.segments[segment_i as usize];
- let now = Instant::now();
let data = tokio::select! {
_ = stop_rx.changed() => { break; },
data = segment.decoders.get_frames(segment_time as f32, !project.camera.hide) => { data }
};
if let Some(segment_frames) = data {
- let now = Instant::now();
let uniforms = ProjectUniforms::new(
&self.render_constants,
&project,
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 601a99fed..d615707aa 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -11,8 +11,8 @@ use cap_project::{
ProjectConfiguration, RecordingMeta, RecordingMetaInner, StudioRecordingMeta, XY,
};
use cap_rendering::{
- ProjectUniforms, RecordingSegmentDecoders, RenderSegment, RenderVideoConstants, RenderedFrame,
- SegmentVideoPaths,
+ ProjectRecordings, ProjectUniforms, RecordingSegmentDecoders, RenderSegment,
+ RenderVideoConstants, RenderedFrame, SegmentVideoPaths,
};
use futures::FutureExt;
use image::{ImageBuffer, Rgba};
@@ -55,11 +55,12 @@ pub struct Exporter<TOnProgress> {
render_constants: Arc<RenderVideoConstants>,
fps: u32,
resolution_base: XY<u32>,
+ recordings: Arc<ProjectRecordings>,
}
impl<TOnProgress> Exporter<TOnProgress>
where
- TOnProgress: Fn(u32) + Send + 'static,
+ TOnProgress: FnMut(u32) + Send + 'static,
{
pub async fn new(
project: ProjectConfiguration,
@@ -71,6 +72,7 @@ where
segments: &[Segment],
fps: u32,
resolution_base: XY<u32>,
+ recordings: Arc<ProjectRecordings>,
) -> Result<Self, ExportError> {
let RecordingMetaInner::Studio(meta) = &recording_meta.inner else {
return Err(ExportError::Other(
@@ -95,7 +97,7 @@ where
camera: s.camera.as_ref().map(|c| recording_meta.path(&c.path)),
}
}
- cap_project::StudioRecordingMeta::MultipleSegments { inner } => {
+ cap_project::StudioRecordingMeta::MultipleSegments { inner, .. } => {
let s = &inner.segments[i];
SegmentVideoPaths {
@@ -106,7 +108,7 @@ where
};
render_segments.push(RenderSegment {
cursor: s.cursor.clone(),
- decoders: RecordingSegmentDecoders::new(&recording_meta, meta, segment_paths)
+ decoders: RecordingSegmentDecoders::new(&recording_meta, meta, segment_paths, i)
.await
.map_err(ExportError::Other)?,
});
@@ -130,10 +132,11 @@ where
output_size,
fps,
resolution_base,
+ recordings: recordings.clone(),
})
}
- pub async fn export_with_custom_muxer(self) -> Result<PathBuf, ExportError> {
+ pub async fn export_with_custom_muxer(mut self) -> Result<PathBuf, ExportError> {
let meta = match &self.recording_meta.inner {
RecordingMetaInner::Studio(meta) => meta,
_ => panic!("Not a studio recording"),
@@ -281,6 +284,7 @@ where
self.render_segments,
self.fps,
self.resolution_base,
+ &self.recordings,
)
.then(|f| async { f.map_err(Into::into) });
diff --git a/crates/flags/src/lib.rs b/crates/flags/src/lib.rs
index b5e8b67c5..42de42172 100644
--- a/crates/flags/src/lib.rs
+++ b/crates/flags/src/lib.rs
@@ -1,13 +1,11 @@
#[derive(serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct Flags {
- pub record_mouse_state: bool,
pub system_audio_recording: bool,
pub split: bool,
}
pub const FLAGS: Flags = Flags {
- record_mouse_state: cfg!(debug_assertions),
system_audio_recording: cfg!(debug_assertions),
split: false,
};
diff --git a/crates/media/src/encoders/h264.rs b/crates/media/src/encoders/h264.rs
index d728775e5..5e6318abf 100644
--- a/crates/media/src/encoders/h264.rs
+++ b/crates/media/src/encoders/h264.rs
@@ -31,8 +31,6 @@ impl H264Encoder {
config: VideoInfo,
output: &mut format::context::Output,
) -> Result<Self, MediaError> {
- dbg!(config);
-
let (codec, options) = get_codec_and_options(&config)?;
let (format, converter) = if !codec
diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rs
index d1cc2b066..ad00c9297 100644
--- a/crates/media/src/feeds/camera.rs
+++ b/crates/media/src/feeds/camera.rs
@@ -5,7 +5,7 @@ use flume::{Receiver, Sender, TryRecvError, TrySendError};
use nokhwa::{pixel_format::RgbAFormat, utils::*, Camera};
use std::{
thread::{self, JoinHandle},
- time::Instant,
+ time::{Instant, SystemTime},
};
use tracing::{debug, error, info, trace, warn};
@@ -26,7 +26,7 @@ enum CameraControl {
#[derive(Clone)]
pub struct RawCameraFrame {
pub frame: FFVideo,
- pub captured_at: Instant,
+ pub captured_at: SystemTime,
}
pub struct CameraConnection {
@@ -323,7 +323,7 @@ fn run_camera_feed(
match camera.frame() {
Ok(raw_buffer) => {
- let captured_at = Instant::now();
+ let captured_at = SystemTime::now();
let frame = RawCameraFrame {
frame: buffer_to_ffvideo(raw_buffer),
diff --git a/crates/media/src/platform/win.rs b/crates/media/src/platform/win.rs
index 36f0b5a5b..8b4e58b09 100644
--- a/crates/media/src/platform/win.rs
+++ b/crates/media/src/platform/win.rs
@@ -266,7 +266,7 @@ pub fn monitor_bounds(id: u32) -> Bounds {
return TRUE;
}
- let id = display_device.StateFlags as u32;
+ let id = hmonitor.0 as u32;
if id == *target_id {
let rect = minfo.monitorInfo.rcMonitor;
diff --git a/crates/media/src/sources/audio_input.rs b/crates/media/src/sources/audio_input.rs
index 6c5d4479f..365b1eb49 100644
--- a/crates/media/src/sources/audio_input.rs
+++ b/crates/media/src/sources/audio_input.rs
@@ -1,3 +1,5 @@
+use std::time::SystemTime;
+
use cap_fail::fail;
use cpal::{Device, StreamInstant, SupportedStreamConfig};
use flume::{Receiver, Sender};
@@ -27,14 +29,21 @@ pub struct AudioInputSource {
feed_connection: AudioInputConnection,
audio_info: AudioInfo,
tx: Sender<(FFAudio, f64)>,
+ start_timestamp: Option<(StreamInstant, SystemTime)>,
+ start_time: f64,
}
impl AudioInputSource {
- pub fn init(feed: &AudioInputFeed, tx: Sender<(FFAudio, f64)>) -> Self {
+ pub fn init(feed: &AudioInputFeed, tx: Sender<(FFAudio, f64)>, start_time: SystemTime) -> Self {
Self {
feed_connection: feed.create_connection(),
audio_info: feed.audio_info(),
tx,
+ start_timestamp: None,
+ start_time: start_time
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64(),
}
}
@@ -42,35 +51,43 @@ impl AudioInputSource {
self.audio_info
}
- fn process_frame(
- &self,
- clock: &mut RealTimeClock<StreamInstant>,
- samples: AudioInputSamples,
- ) -> Result<(), MediaError> {
- match clock.timestamp_for(samples.info.timestamp().capture) {
- None => {
- eprintln!("Clock is currently stopped. Dropping frames.");
- }
- Some(timestamp) => {
- let frame = self.audio_info.wrap_frame(&samples.data, timestamp);
- if let Err(_) = self.tx.send((frame, 0.0 /* TODO: correct this */)) {
- return Err(MediaError::Any("Pipeline is unreachable! Stopping capture"));
- }
- }
+ fn process_frame(&mut self, samples: AudioInputSamples) -> Result<(), MediaError> {
+ let start_timestamp = match self.start_timestamp {
+ None => *self
+ .start_timestamp
+ .insert((samples.info.timestamp().capture, SystemTime::now())),
+ Some(v) => v,
+ };
+
+ let elapsed = samples
+ .info
+ .timestamp()
+ .capture
+ .duration_since(&start_timestamp.0)
+ .unwrap();
+
+ let timestamp = start_timestamp
+ .1
+ .checked_add(elapsed)
+ .unwrap()
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64()
+ - self.start_time;
+
+ let frame = self.audio_info.wrap_frame(&samples.data, 0);
+ if let Err(_) = self.tx.send((frame, timestamp)) {
+ return Err(MediaError::Any("Pipeline is unreachable! Stopping capture"));
}
Ok(())
}
- fn pause_and_drain_frames(
- &self,
- clock: &mut RealTimeClock<StreamInstant>,
- frames_rx: Receiver<AudioInputSamples>,
- ) {
+ fn pause_and_drain_frames(&mut self, frames_rx: Receiver<AudioInputSamples>) {
let frames: Vec<AudioInputSamples> = frames_rx.drain().collect();
for frame in frames {
- if let Err(error) = self.process_frame(clock, frame) {
+ if let Err(error) = self.process_frame(frame) {
eprintln!("{error}");
break;
}
@@ -83,7 +100,7 @@ impl PipelineSourceTask for AudioInputSource {
fn run(
&mut self,
- mut clock: Self::Clock,
+ _: Self::Clock,
ready_signal: crate::pipeline::task::PipelineReadySignal,
mut control_signal: crate::pipeline::control::PipelineControlSignal,
) {
@@ -101,7 +118,7 @@ impl PipelineSourceTask for AudioInputSource {
match samples.recv() {
Ok(samples) => {
- if let Err(error) = self.process_frame(&mut clock, samples) {
+ if let Err(error) = self.process_frame(samples) {
error!("{error}");
break;
}
@@ -114,7 +131,7 @@ impl PipelineSourceTask for AudioInputSource {
}
Some(Control::Shutdown) | None => {
if let Some(rx) = samples_rx.take() {
- self.pause_and_drain_frames(&mut clock, rx);
+ self.pause_and_drain_frames(rx);
}
break;
}
diff --git a/crates/media/src/sources/camera.rs b/crates/media/src/sources/camera.rs
index d71751fe0..e0b40ff6c 100644
--- a/crates/media/src/sources/camera.rs
+++ b/crates/media/src/sources/camera.rs
@@ -1,5 +1,5 @@
use flume::{Receiver, Sender};
-use std::time::Instant;
+use std::time::{Instant, SystemTime};
use tracing::{error, info};
use crate::{
@@ -12,15 +12,17 @@ use crate::{
pub struct CameraSource {
feed_connection: CameraConnection,
video_info: VideoInfo,
- output: Sender<FFVideo>,
+ output: Sender<(FFVideo, f64)>,
+ start_time: SystemTime,
}
impl CameraSource {
- pub fn init(feed: &CameraFeed, output: Sender<FFVideo>) -> Self {
+ pub fn init(feed: &CameraFeed, output: Sender<(FFVideo, f64)>, start_time: SystemTime) -> Self {
Self {
feed_connection: feed.create_connection(),
video_info: feed.video_info(),
output,
+ start_time,
}
}
@@ -37,17 +39,23 @@ impl CameraSource {
mut frame,
captured_at,
} = camera_frame;
- match clock.timestamp_for(captured_at) {
- None => {
- eprintln!("Clock is currently stopped. Dropping frames.");
- }
- Some(timestamp) => {
- frame.set_pts(Some(timestamp));
- if let Err(_) = self.output.send(frame) {
- return Err(MediaError::Any("Pipeline is unreachable! Stopping capture"));
- }
- }
+ // match clock.timestamp_for(captured_at) {
+ // None => {
+ // eprintln!("Clock is currently stopped. Dropping frames.");
+ // }
+ // Some(timestamp) => {
+ // frame.set_pts(Some(timestamp));
+ if let Err(_) = self.output.send((
+ frame,
+ captured_at
+ .duration_since(self.start_time)
+ .unwrap()
+ .as_secs_f64(),
+ )) {
+ return Err(MediaError::Any("Pipeline is unreachable! Stopping capture"));
}
+ // }
+ // }
Ok(())
}
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 4ed43e21e..0e44bb078 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -13,7 +13,7 @@ use scap::{
use serde::{Deserialize, Serialize};
use specta::Type;
-use std::{collections::HashMap, ops::ControlFlow, sync::Arc};
+use std::{collections::HashMap, ops::ControlFlow, sync::Arc, time::SystemTime};
use tracing::{debug, error, info, trace, warn};
use crate::{
@@ -133,6 +133,7 @@ pub struct ScreenCaptureSource<TCaptureFormat: ScreenCaptureFormat> {
video_tx: Sender<(TCaptureFormat::VideoFormat, f64)>,
audio_tx: Option<Sender<(ffmpeg::frame::Audio, f64)>>,
_phantom: std::marker::PhantomData<TCaptureFormat>,
+ start_time: SystemTime,
}
impl<T: ScreenCaptureFormat> std::fmt::Debug for ScreenCaptureSource<T> {
@@ -192,6 +193,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> Clone for ScreenCaptureSource<TCapture
video_tx: self.video_tx.clone(),
audio_tx: self.audio_tx.clone(),
_phantom: std::marker::PhantomData,
+ start_time: self.start_time.clone(),
}
}
}
@@ -207,6 +209,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
max_fps: u32,
video_tx: Sender<(TCaptureFormat::VideoFormat, f64)>,
audio_tx: Option<Sender<(ffmpeg::frame::Audio, f64)>>,
+ start_time: SystemTime,
) -> Result<Self, String> {
cap_fail::fail!("media::screen_capture::init");
@@ -231,6 +234,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
video_tx,
audio_tx,
_phantom: std::marker::PhantomData,
+ start_time,
};
let options = this.create_options(scap_target, crop_area, captures_audio)?;
@@ -340,7 +344,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
Ok(Options {
fps: self.fps,
- show_cursor: self.force_show_cursor || !FLAGS.record_mouse_state,
+ show_cursor: self.force_show_cursor,
show_highlight: false,
target: Some(target.clone()),
crop_area,
@@ -378,6 +382,12 @@ impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {
let video_tx = self.video_tx.clone();
let audio_tx = self.audio_tx.clone();
+ let start_time_nanos = self
+ .start_time
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos() as u64;
+
inner(
self,
ready_signal,
@@ -388,6 +398,8 @@ impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {
return Some(ControlFlow::Continue(()));
}
+ let elapsed_nanos = frame.display_time - start_time_nanos;
+
let raw_timestamp = RawNanoseconds(frame.display_time);
match clock.timestamp_for(raw_timestamp) {
None => {
@@ -439,7 +451,8 @@ impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {
}
}
- if let Err(_) = video_tx.send((buffer, 0.0)) {
+ let time_f = elapsed_nanos as f64 / 1_000_000_000.0;
+ if let Err(_) = video_tx.send((buffer, time_f)) {
error!("Pipeline is unreachable. Shutting down recording.");
return Some(ControlFlow::Break(()));
}
@@ -574,6 +587,12 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
let start_cmtime = cidre::cm::Clock::host_time_clock().time();
let start_cmtime = start_cmtime.value as f64 / start_cmtime.scale as f64;
+ let start_time_f64 = self
+ .start_time
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64();
+
inner(
self,
ready_signal,
@@ -587,6 +606,7 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
let frame_time =
sample_buffer.pts().value as f64 / sample_buffer.pts().scale as f64;
let unix_timestamp = start_time_unix + frame_time - start_cmtime;
+ let relative_time = unix_timestamp - start_time_f64;
match typ {
SCStreamOutputType::Screen => {
@@ -598,13 +618,13 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
return Some(ControlFlow::Continue(()));
}
- if let Err(_) = video_tx.send((sample_buffer, frame_time)) {
+ if let Err(_) = video_tx.send((sample_buffer, relative_time)) {
eprintln!("Pipeline is unreachable. Shutting down recording.");
return Some(ControlFlow::Continue(()));
}
}
SCStreamOutputType::Audio => {
- println!("audio: {frame_time}");
+ // println!("audio: {frame_time}");
let Some(audio_tx) = &audio_tx else {
return Some(ControlFlow::Continue(()));
};
@@ -626,10 +646,9 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
);
}
- let timestamp = frame_time - start_cmtime;
frame.set_pts(Some((frame_time * AV_TIME_BASE_Q.den as f64) as i64));
- let _ = audio_tx.send((frame, timestamp));
+ let _ = audio_tx.send((frame, relative_time));
}
}
diff --git a/crates/project/src/cursor.rs b/crates/project/src/cursor.rs
index e86c2a46d..8763dc949 100644
--- a/crates/project/src/cursor.rs
+++ b/crates/project/src/cursor.rs
@@ -6,28 +6,38 @@ use std::path::{Path, PathBuf};
use crate::XY;
-#[derive(Serialize, Deserialize, Clone, Type, Debug)]
+#[derive(Serialize, Deserialize, Clone, Type, Debug, PartialEq)]
pub struct CursorMoveEvent {
pub active_modifiers: Vec<String>,
pub cursor_id: String,
- pub process_time_ms: f64,
- pub unix_time_ms: f64,
+ pub time_ms: f64,
pub x: f64,
pub y: f64,
}
-#[derive(Serialize, Deserialize, Clone, Type, Debug)]
+impl PartialOrd for CursorMoveEvent {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ self.time_ms.partial_cmp(&other.time_ms)
+ }
+}
+
+#[derive(Serialize, Deserialize, Clone, Type, Debug, PartialEq)]
pub struct CursorClickEvent {
pub active_modifiers: Vec<String>,
pub cursor_num: u8,
pub cursor_id: String,
- pub process_time_ms: f64,
- pub unix_time_ms: f64,
+ pub time_ms: f64,
pub down: bool,
pub x: f64,
pub y: f64,
}
+impl PartialOrd for CursorClickEvent {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ self.time_ms.partial_cmp(&other.time_ms)
+ }
+}
+
#[derive(Default, Serialize, Deserialize, Debug, Clone)]
#[serde(transparent)]
pub struct CursorImages(pub HashMap<String, CursorImage>);
diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rs
index d0c76556f..c3d55f6c3 100644
--- a/crates/project/src/meta.rs
+++ b/crates/project/src/meta.rs
@@ -111,10 +111,12 @@ impl RecordingMeta {
pub enum StudioRecordingMeta {
SingleSegment {
#[serde(flatten)]
+ #[specta(flatten)]
segment: SingleSegment,
},
MultipleSegments {
#[serde(flatten)]
+ #[specta(flatten)]
inner: MultipleSegments,
},
}
@@ -125,7 +127,7 @@ impl StudioRecordingMeta {
StudioRecordingMeta::SingleSegment { segment } => {
segment.camera.as_ref().map(|c| c.path.clone())
}
- StudioRecordingMeta::MultipleSegments { inner } => inner
+ StudioRecordingMeta::MultipleSegments { inner, .. } => inner
.segments
.first()
.and_then(|s| s.camera.as_ref().map(|c| c.path.clone())),
@@ -135,7 +137,7 @@ impl StudioRecordingMeta {
pub fn min_fps(&self) -> u32 {
match self {
StudioRecordingMeta::SingleSegment { segment } => segment.display.fps,
- StudioRecordingMeta::MultipleSegments { inner } => {
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
inner.segments.iter().map(|s| s.display.fps).min().unwrap()
}
}
@@ -144,7 +146,7 @@ impl StudioRecordingMeta {
pub fn max_fps(&self) -> u32 {
match self {
StudioRecordingMeta::SingleSegment { segment } => segment.display.fps,
- StudioRecordingMeta::MultipleSegments { inner } => {
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
inner.segments.iter().map(|s| s.display.fps).max().unwrap()
}
}
@@ -232,8 +234,8 @@ pub struct MultipleSegment {
pub display: VideoMeta,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub camera: Option<VideoMeta>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub audio: Option<AudioMeta>,
+ #[serde(default, skip_serializing_if = "Option::is_none", alias = "audio")]
+ pub mic: Option<AudioMeta>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub system_audio: Option<AudioMeta>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -263,6 +265,24 @@ impl MultipleSegment {
}
}
}
+
+ pub fn latest_start_time(&self) -> Option<f64> {
+ let mut value = self.display.start_time?;
+
+ if let Some(camera) = &self.camera {
+ value = value.max(camera.start_time?);
+ }
+
+ if let Some(mic) = &self.mic {
+ value = value.max(mic.start_time?);
+ }
+
+ if let Some(system_audio) = &self.system_audio {
+ value = value.max(system_audio.start_time?);
+ }
+
+ Some(value)
+ }
}
#[cfg(test)]
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs
index 8f7b1287c..ef133411f 100644
--- a/crates/recording/src/capture_pipeline.rs
+++ b/crates/recording/src/capture_pipeline.rs
@@ -2,6 +2,7 @@ use std::{
future::Future,
path::PathBuf,
sync::{atomic::AtomicBool, Arc},
+ time::SystemTime,
};
use cap_media::{
@@ -110,7 +111,7 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {
if let Some(audio) = audio {
let sink = audio_mixer.sink(audio.audio_info());
- let source = AudioInputSource::init(audio, sink.tx);
+ let source = AudioInputSource::init(audio, sink.tx, SystemTime::now());
builder.spawn_source("microphone_capture", source);
}
@@ -231,7 +232,7 @@ impl MakeCapturePipeline for AVFrameCapture {
if let Some(audio) = audio {
let sink = audio_mixer.sink(audio.audio_info());
- let source = AudioInputSource::init(audio, sink.tx);
+ let source = AudioInputSource::init(audio, sink.tx, SystemTime::now());
builder.spawn_source("microphone_capture", source);
}
@@ -301,6 +302,7 @@ pub fn create_screen_capture(
force_show_cursor: bool,
max_fps: u32,
audio_tx: Option<Sender<(ffmpeg::frame::Audio, f64)>>,
+ start_time: SystemTime,
) -> Result<ScreenCaptureReturn<ScreenCaptureMethod>, RecordingError> {
let (video_tx, video_rx) = flume::bounded(16);
@@ -312,6 +314,7 @@ pub fn create_screen_capture(
max_fps,
video_tx,
audio_tx,
+ start_time,
)
.map(|v| (v, video_rx))
.map_err(|e| RecordingError::Media(MediaError::TaskLaunch(e)))
diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs
index 4a1296f09..74c985d61 100644
--- a/crates/recording/src/cursor.rs
+++ b/crates/recording/src/cursor.rs
@@ -3,7 +3,7 @@ use std::{
hash::{DefaultHasher, Hash, Hasher},
path::PathBuf,
sync::{atomic::AtomicBool, Arc},
- time::{Duration, Instant},
+ time::{Duration, Instant, SystemTime},
};
use cap_media::platform::Bounds;
@@ -48,6 +48,7 @@ pub fn spawn_cursor_recorder(
cursors_dir: PathBuf,
prev_cursors: Cursors,
next_cursor_id: u32,
+ start_time: SystemTime,
) -> CursorActor {
let stop_signal = Arc::new(AtomicBool::new(false));
let (tx, rx) = oneshot::channel();
@@ -68,12 +69,12 @@ pub fn spawn_cursor_recorder(
clicks: vec![],
};
- let start_time = Instant::now();
-
while !stop_signal.load(std::sync::atomic::Ordering::Relaxed) {
- let elapsed = start_time.elapsed().as_secs_f64() * 1000.0;
+ let Ok(elapsed) = start_time.elapsed() else {
+ continue;
+ };
+ let elapsed = elapsed.as_secs_f64() * 1000.0;
let mouse_state = device_state.get_mouse();
- let unix_time = chrono::Utc::now().timestamp_millis() as f64;
let cursor_data = get_cursor_image_data();
let cursor_id = if let Some(data) = cursor_data {
@@ -121,47 +122,6 @@ pub fn spawn_cursor_recorder(
// Get the actual mouse coordinates
let (mouse_x, mouse_y) = mouse_state.coords;
- #[cfg(windows)]
- let (mouse_x, mouse_y) = {
- // On Windows, ensure we're using the correct coordinate system
- // by getting the virtual screen metrics
- use windows::Win32::UI::WindowsAndMessaging::GetSystemMetrics;
- use windows::Win32::UI::WindowsAndMessaging::{
- SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN,
- SM_YVIRTUALSCREEN,
- };
-
- let virtual_screen_x = unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) };
- let virtual_screen_y = unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) };
- let virtual_screen_width = unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) };
- let virtual_screen_height = unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) };
-
- // If screen_bounds doesn't match the virtual screen, adjust the coordinates
- if (screen_bounds.x as i32 != virtual_screen_x
- || screen_bounds.y as i32 != virtual_screen_y
- || screen_bounds.width as i32 != virtual_screen_width
- || screen_bounds.height as i32 != virtual_screen_height)
- && screen_bounds.width > 0.0
- && screen_bounds.height > 0.0
- {
- // Convert to normalized coordinates in the virtual screen space first
- let norm_x = (mouse_x as f64 - virtual_screen_x as f64)
- / virtual_screen_width as f64;
- let norm_y = (mouse_y as f64 - virtual_screen_y as f64)
- / virtual_screen_height as f64;
-
- // Then convert to the target screen coordinates
- let adjusted_x =
- (norm_x * screen_bounds.width + screen_bounds.x) as i32;
- let adjusted_y =
- (norm_y * screen_bounds.height + screen_bounds.y) as i32;
-
- (adjusted_x, adjusted_y)
- } else {
- (mouse_x, mouse_y)
- }
- };
-
#[cfg(target_os = "macos")]
let (mouse_x, mouse_y) = {
let primary_bounds = cap_media::platform::primary_monitor_bounds();
@@ -174,7 +134,7 @@ pub fn spawn_cursor_recorder(
(mouse_x, mouse_y)
};
- #[cfg(not(any(windows, target_os = "macos")))]
+ #[cfg(not(target_os = "macos"))]
let (mouse_x, mouse_y) = {
(
mouse_x - screen_bounds.x as i32,
@@ -214,8 +174,7 @@ pub fn spawn_cursor_recorder(
let mouse_event = CursorMoveEvent {
active_modifiers: vec![],
cursor_id: cursor_id.clone(),
- process_time_ms: elapsed,
- unix_time_ms: unix_time,
+ time_ms: elapsed,
x,
y,
};
@@ -306,8 +265,7 @@ pub fn spawn_cursor_recorder(
active_modifiers: vec![],
cursor_num: num as u8,
cursor_id: cursor_id.clone(),
- process_time_ms: elapsed,
- unix_time_ms: unix_time,
+ time_ms: elapsed,
x,
y,
};
diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rs
index 165feb32f..a3566281f 100644
--- a/crates/recording/src/instant_recording.rs
+++ b/crates/recording/src/instant_recording.rs
@@ -162,6 +162,8 @@ pub async fn spawn_instant_recording_actor(
) -> Result<(InstantRecordingHandle, tokio::sync::oneshot::Receiver<()>), RecordingError> {
ensure_dir(&recording_dir)?;
+ let start_time = SystemTime::now();
+
let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
trace!("creating recording actor");
@@ -175,8 +177,14 @@ pub async fn spawn_instant_recording_actor(
(None, None)
};
- let (screen_source, screen_rx) =
- create_screen_capture(&options.capture_target, true, true, 30, system_audio.0)?;
+ let (screen_source, screen_rx) = create_screen_capture(
+ &options.capture_target,
+ true,
+ true,
+ 30,
+ system_audio.0,
+ start_time,
+ )?;
debug!("screen capture: {screen_source:#?}");
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index 33ee3fb8d..f49349212 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -1,7 +1,7 @@
use std::{
path::PathBuf,
sync::Arc,
- time::{SystemTime, UNIX_EPOCH},
+ time::{Instant, SystemTime, UNIX_EPOCH},
};
use cap_flags::FLAGS;
@@ -60,6 +60,7 @@ pub struct StudioRecordingActor {
fps: u32,
options: RecordingOptions,
segments: Vec<StudioRecordingSegment>,
+ start_time: SystemTime,
}
pub struct StudioRecordingSegment {
@@ -135,9 +136,12 @@ pub async fn spawn_studio_recording_actor(
options: RecordingOptions,
camera_feed: Option<Arc<Mutex<CameraFeed>>>,
mic_feed: &Option<AudioInputFeed>,
+ custom_cursor_capture: bool,
) -> Result<(StudioRecordingHandle, tokio::sync::oneshot::Receiver<()>), RecordingError> {
ensure_dir(&recording_dir)?;
+ let start_time = SystemTime::now();
+
let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
trace!("creating recording actor");
@@ -147,6 +151,8 @@ pub async fn spawn_studio_recording_actor(
let segments_dir = ensure_dir(&content_dir.join("segments"))?;
let cursors_dir = ensure_dir(&content_dir.join("cursors"))?;
+ let start_time = SystemTime::now();
+
// let bounds = screen_source.get_bounds().clone();
// debug!("screen capture: {screen_source:#?}");
@@ -172,6 +178,8 @@ pub async fn spawn_studio_recording_actor(
camera_feed.as_deref(),
Default::default(),
index,
+ custom_cursor_capture,
+ start_time,
)
.await?;
@@ -193,6 +201,7 @@ pub async fn spawn_studio_recording_actor(
options: options.clone(),
fps,
segments: Vec::new(),
+ start_time,
};
let mut state = StudioRecordingActorState::Recording {
@@ -338,6 +347,8 @@ pub async fn spawn_studio_recording_actor(
camera_feed.as_deref(),
cursors,
next_cursor_id,
+ custom_cursor_capture,
+ start_time,
)
.await
{
@@ -407,6 +418,13 @@ async fn stop_recording(
) -> Result<CompletedStudioRecording, RecordingError> {
use cap_project::*;
+ let make_relative = |path: &PathBuf| {
+ RelativePathBuf::from_path(path.strip_prefix(&actor.recording_dir).unwrap().to_owned())
+ .unwrap()
+ };
+
+ let recv_timestamp = |pipeline: &PipelineOutput| pipeline.first_timestamp_rx.try_recv().ok();
+
let meta = StudioRecordingMeta::MultipleSegments {
inner: MultipleSegments {
segments: {
@@ -415,72 +433,27 @@ async fn stop_recording(
.iter()
.map(|s| MultipleSegment {
display: VideoMeta {
- path: RelativePathBuf::from_path(
- s.pipeline
- .screen
- .inner
- .path
- .strip_prefix(&actor.recording_dir)
- .unwrap(),
- )
- .unwrap(),
+ path: make_relative(&s.pipeline.screen.inner.path),
fps: actor.fps,
- start_time: None,
- // Some(
- // s.pipeline
- // .screen
- // .inner
- // .first_timestamp_rx
- // .try_recv()
- // .unwrap(),
- // ),
+ start_time: recv_timestamp(&s.pipeline.screen.inner),
},
camera: s.pipeline.camera.as_ref().map(|camera| VideoMeta {
- path: RelativePathBuf::from_path(
- camera
- .inner
- .path
- .strip_prefix(&actor.recording_dir)
- .unwrap()
- .to_owned(),
- )
- .unwrap(),
+ path: make_relative(&camera.inner.path),
fps: camera.fps,
- start_time: None,
- // Some(camera.inner.first_timestamp_rx.try_recv().unwrap()),
- }),
- audio: s.pipeline.microphone.as_ref().map(|mic| AudioMeta {
- path: RelativePathBuf::from_path(
- mic.path
- .strip_prefix(&actor.recording_dir)
- .unwrap()
- .to_owned(),
- )
- .unwrap(),
- start_time: None,
- // Some(mic.first_timestamp_rx.try_recv().unwrap()),
+ start_time: recv_timestamp(&camera.inner),
}),
- cursor: s.pipeline.cursor.as_ref().map(|cursor| {
- RelativePathBuf::from_path(
- cursor
- .output_path
- .strip_prefix(&actor.recording_dir)
- .unwrap()
- .to_owned(),
- )
- .unwrap()
+ mic: s.pipeline.microphone.as_ref().map(|mic| AudioMeta {
+ path: make_relative(&mic.path),
+ start_time: recv_timestamp(&mic),
}),
+ cursor: s
+ .pipeline
+ .cursor
+ .as_ref()
+ .map(|cursor| make_relative(&cursor.output_path)),
system_audio: s.pipeline.system_audio.as_ref().map(|audio| AudioMeta {
- path: RelativePathBuf::from_path(
- audio
- .path
- .strip_prefix(&actor.recording_dir)
- .unwrap()
- .to_owned(),
- )
- .unwrap(),
- start_time: None,
- // Some(audio.first_timestamp_rx.try_recv().unwrap()),
+ path: make_relative(&audio.path),
+ start_time: recv_timestamp(audio),
}),
})
.collect()
@@ -528,6 +501,8 @@ async fn create_segment_pipeline(
camera_feed: Option<&Mutex<CameraFeed>>,
prev_cursors: Cursors,
next_cursors_id: u32,
+ custom_cursor_capture: bool,
+ start_time: SystemTime,
) -> Result<(StudioRecordingPipeline, oneshot::Receiver<()>), RecordingError> {
let system_audio = if options.capture_system_audio {
let (tx, rx) = flume::bounded(64);
@@ -536,8 +511,14 @@ async fn create_segment_pipeline(
(None, None)
};
- let (screen_source, screen_rx) =
- create_screen_capture(&options.capture_target, false, false, 120, system_audio.0)?;
+ let (screen_source, screen_rx) = create_screen_capture(
+ &options.capture_target,
+ false,
+ !custom_cursor_capture,
+ 120,
+ system_audio.0,
+ start_time,
+ )?;
let camera_feed = match camera_feed.as_ref() {
Some(camera_feed) => Some(camera_feed.lock().await),
@@ -587,7 +568,7 @@ async fn create_segment_pipeline(
let microphone = if let Some(mic_source) = mic_feed {
let (tx, rx) = flume::bounded(8);
- let mic_source = AudioInputSource::init(mic_source, tx);
+ let mic_source = AudioInputSource::init(mic_source, tx, start_time);
let mic_config = mic_source.info();
let output_path = dir.join("audio-input.ogg");
@@ -607,9 +588,7 @@ async fn create_segment_pipeline(
while let Ok(frame) = rx.recv() {
if let Some(timestamp_tx) = timestamp_tx.take() {
- // timestamp_tx
- // .send(frame.timestamp().unwrap_or(0) as f64 / AV_TIME_BASE_Q.den as f64)
- // .unwrap();
+ timestamp_tx.send(frame.1).unwrap();
}
mic_encoder.queue_frame(frame.0);
@@ -667,7 +646,7 @@ async fn create_segment_pipeline(
let camera = if let Some(camera_feed) = camera_feed {
let (tx, rx) = flume::bounded(8);
- let camera_source = CameraSource::init(camera_feed, tx);
+ let camera_source = CameraSource::init(camera_feed, tx, start_time);
let camera_config = camera_source.info();
let output_path = dir.join("camera.mp4");
@@ -686,14 +665,24 @@ async fn create_segment_pipeline(
let mut timestamp_tx = Some(timestamp_tx);
let _ = ready.send(Ok(()));
- while let Ok(frame) = rx.recv() {
+ let mut start = None;
+ while let Ok(mut frame) = rx.recv() {
if let Some(timestamp_tx) = timestamp_tx.take() {
- timestamp_tx
- .send(frame.timestamp().unwrap_or(0) as f64 / AV_TIME_BASE_Q.den as f64)
- .unwrap();
+ timestamp_tx.send(frame.1).unwrap();
+ }
+
+ if let Some(start) = start {
+ frame.0.set_pts(Some(
+ ((camera_config.time_base.denominator() as f64
+ / camera_config.time_base.numerator() as f64)
+ * (frame.1 - start)) as i64,
+ ));
+ } else {
+ start = Some(frame.1);
+ frame.0.set_pts(Some(0));
}
- camera_encoder.queue_video_frame(frame);
+ camera_encoder.queue_video_frame(frame.0);
}
camera_encoder.finish();
});
@@ -716,12 +705,13 @@ async fn create_segment_pipeline(
let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;
- let cursor = FLAGS.record_mouse_state.then(|| {
+ let cursor = custom_cursor_capture.then(|| {
let cursor = spawn_cursor_recorder(
screen.bounds.clone(),
cursors_dir.clone(),
prev_cursors,
next_cursors_id,
+ start_time,
);
CursorPipeline {
diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs
index e97e94e73..1ff92d5f5 100644
--- a/crates/rendering/src/decoder/mod.rs
+++ b/crates/rendering/src/decoder/mod.rs
@@ -25,33 +25,40 @@ pub const FRAME_CACHE_SIZE: usize = 100;
#[derive(Clone)]
pub struct AsyncVideoDecoderHandle {
sender: mpsc::Sender<VideoDecoderMessage>,
+ offset: f64,
}
impl AsyncVideoDecoderHandle {
pub async fn get_frame(&self, time: f32) -> Option<DecodedFrame> {
let (tx, rx) = tokio::sync::oneshot::channel();
self.sender
- .send(VideoDecoderMessage::GetFrame(time, tx))
+ .send(VideoDecoderMessage::GetFrame(self.get_time(time), tx))
.unwrap();
rx.await.ok()
}
+
+ pub fn get_time(&self, time: f32) -> f32 {
+ time + self.offset as f32
+ }
}
pub async fn spawn_decoder(
name: &'static str,
path: PathBuf,
fps: u32,
+ offset: f64,
) -> Result<AsyncVideoDecoderHandle, String> {
let (ready_tx, ready_rx) = oneshot::channel::<Result<(), String>>();
let (tx, rx) = mpsc::channel();
- let handle = AsyncVideoDecoderHandle { sender: tx };
+ let handle = AsyncVideoDecoderHandle { sender: tx, offset };
if cfg!(target_os = "macos") {
#[cfg(target_os = "macos")]
avassetreader::AVAssetReaderDecoder::spawn(name, path, fps, rx, ready_tx);
} else {
- ffmpeg::FfmpegDecoder::spawn(name, path, fps, rx, ready_tx);
+ ffmpeg::FfmpegDecoder::spawn(name, path, fps, rx, ready_tx)
+ .map_err(|e| format!("'{name}' decoder / {e}"))?;
}
ready_rx.await.map_err(|e| e.to_string())?.map(|()| handle)
diff --git a/crates/rendering/src/frame_pipeline.rs b/crates/rendering/src/frame_pipeline.rs
index 182477b43..72da7f64e 100644
--- a/crates/rendering/src/frame_pipeline.rs
+++ b/crates/rendering/src/frame_pipeline.rs
@@ -1,5 +1,7 @@
+use std::time::Instant;
+
use futures_intrusive::channel::shared::oneshot_channel;
-use wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
+use wgpu::{hal::Device, COPY_BYTES_PER_ROW_ALIGNMENT};
use crate::{get_either, ProjectUniforms, RenderVideoConstants, RenderingError};
diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rs
index fd181591b..88d3e2f02 100644
--- a/crates/rendering/src/layers/cursor.rs
+++ b/crates/rendering/src/layers/cursor.rs
@@ -6,11 +6,15 @@ use wgpu::{include_wgsl, util::DeviceExt, FilterMode};
use crate::{
frame_pipeline::{FramePipeline, FramePipelineState},
- spring_mass_damper::SpringMassDamperSimulation,
+ spring_mass_damper::{SpringMassDamperSimulation, SpringMassDamperSimulationConfig},
zoom::InterpolatedZoom,
Coord, DecodedSegmentFrames, ProjectUniforms, RawDisplayUVSpace, STANDARD_CURSOR_HEIGHT,
};
+const CURSOR_CLICK_DURATION: f64 = 0.25;
+const CURSOR_CLICK_DURATION_MS: f64 = CURSOR_CLICK_DURATION * 1000.0;
+const CLICK_SHRINK_SIZE: f32 = 0.7;
+
pub struct CursorLayer {
uniform_buffer: wgpu::Buffer,
texture_sampler: wgpu::Sampler,
@@ -29,7 +33,7 @@ impl CursorLayer {
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
- min_binding_size: Some(std::num::NonZeroU64::new(112).unwrap()),
+ min_binding_size: None, // Some(std::num::NonZeroU64::new(80).unwrap()),
},
count: None,
},
@@ -146,15 +150,17 @@ impl CursorLayer {
constants,
..
} = &pipeline.state;
- let segment_time = segment_frames.segment_time;
+ let time_s = segment_frames.recording_time;
+ let cursor_settings = &uniforms.project.cursor;
let Some(interpolated_cursor) = interpolate_cursor(
cursor,
- segment_time,
- uniforms.project.cursor.tension,
- uniforms.project.cursor.mass,
- uniforms.project.cursor.friction,
- uniforms.project.cursor.raw,
+ time_s,
+ (!cursor_settings.raw).then(|| SpringMassDamperSimulationConfig {
+ tension: cursor_settings.tension,
+ mass: cursor_settings.mass,
+ friction: cursor_settings.friction,
+ }),
) else {
return;
};
@@ -167,80 +173,60 @@ impl CursorLayer {
let speed = (velocity[0] * velocity[0] + velocity[1] * velocity[1]).sqrt();
let motion_blur_amount = (speed * 0.3).min(1.0) * 0.0; // uniforms.project.cursor.motion_blur;
- let cursor_event = find_cursor_event(&cursor, segment_time);
-
- let last_click_time = cursor
- .clicks
- .iter()
- .filter(|click| click.down && click.process_time_ms <= (segment_time as f64) * 1000.0)
- .max_by_key(|click| click.process_time_ms as i64)
- .map(|click| ((segment_time as f64) * 1000.0 - click.process_time_ms) as f32 / 1000.0)
- .unwrap_or(1.0);
+ let last_move_event = find_cursor_move(&cursor, time_s);
- let Some(cursor_texture) = constants.cursor_textures.get(&cursor_event.cursor_id) else {
+ let Some(cursor_texture) = constants.cursor_textures.get(&last_move_event.cursor_id) else {
return;
};
- let cursor_size = cursor_texture.inner.size();
- let aspect_ratio = cursor_size.width as f32 / cursor_size.height as f32;
+ let cursor_base_size_px = {
+ let cursor_texture_size = cursor_texture.inner.size();
+ let cursor_texture_size_aspect =
+ cursor_texture_size.width as f32 / cursor_texture_size.height as f32;
+
+ let cursor_size_percentage = if uniforms.cursor_size <= 0.0 {
+ 100.0
+ } else {
+ uniforms.cursor_size / 100.0
+ };
- let cursor_size_percentage = if uniforms.cursor_size <= 0.0 {
- 100.0
- } else {
- uniforms.cursor_size / 100.0
+ XY::new(
+ STANDARD_CURSOR_HEIGHT * cursor_texture_size_aspect * cursor_size_percentage,
+ STANDARD_CURSOR_HEIGHT * cursor_size_percentage,
+ )
};
- let normalized_size = [
- STANDARD_CURSOR_HEIGHT * aspect_ratio * cursor_size_percentage,
- STANDARD_CURSOR_HEIGHT * cursor_size_percentage,
- ];
+ let click_scale_factor = get_click_t(&cursor.clicks, (time_s as f64) * 1000.0)
+ * (1.0 - CLICK_SHRINK_SIZE)
+ + CLICK_SHRINK_SIZE;
- let position = interpolated_cursor
- .position
- .to_frame_space(&constants.options, &uniforms.project, resolution_base)
- .to_zoomed_frame_space(&constants.options, &uniforms.project, resolution_base, zoom);
- let relative_position = [position.x as f32, position.y as f32];
+ let cursor_size_px =
+ cursor_base_size_px * click_scale_factor * zoom.display_amount() as f32;
- fn smoothstep(low: f32, high: f32, v: f32) -> f32 {
- let t = f32::clamp((v - low) / (high - low), 0.0, 1.0);
- t * t * (3.0 - 2.0 * t)
- }
+ let hotspot_px = cursor_texture.hotspot * cursor_size_px;
- let click_scale = 1.0
- - (0.2
- * smoothstep(0.0, 0.25, last_click_time)
- * (1.0 - smoothstep(0.25, 0.5, last_click_time)));
+ let position = {
+ let mut frame_position = interpolated_cursor.position.to_frame_space(
+ &constants.options,
+ &uniforms.project,
+ resolution_base,
+ );
- let output_size = ProjectUniforms::get_output_size(
- &constants.options,
- &uniforms.project,
- resolution_base,
- );
- let display_size =
- ProjectUniforms::display_size(&constants.options, &uniforms.project, resolution_base);
+ frame_position.coord = frame_position.coord - hotspot_px.map(|v| v as f64);
+
+ frame_position
+ .to_zoomed_frame_space(&constants.options, &uniforms.project, resolution_base, zoom)
+ .coord
+ };
let uniforms = CursorUniforms {
- position: [relative_position[0], relative_position[1], 0.0, 0.0],
- size: [normalized_size[0], normalized_size[1], 0.0, 0.0],
- output_size: [
- uniforms.output_size.0 as f32,
- uniforms.output_size.1 as f32,
- 0.0,
- 0.0,
- ],
+ position: [position.x as f32, position.y as f32],
+ size: [cursor_size_px.x, cursor_size_px.y],
+ output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],
screen_bounds: uniforms.display.target_bounds,
- cursor_size: cursor_size_percentage
- * click_scale
- * zoom.display_amount() as f32
- * (display_size.coord.x as f32 / output_size.0 as f32),
- last_click_time,
velocity,
motion_blur_amount,
- hotspot: [
- cursor_texture.hotspot.x as f32,
- cursor_texture.hotspot.y as f32,
- ],
- _alignment: [0.0; 5],
+ _alignment: [0.0; 3],
};
constants
@@ -284,22 +270,19 @@ impl CursorLayer {
#[repr(C, align(16))]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
pub struct CursorUniforms {
- position: [f32; 4],
- size: [f32; 4],
- output_size: [f32; 4],
+ position: [f32; 2],
+ size: [f32; 2],
+ output_size: [f32; 2],
screen_bounds: [f32; 4],
- cursor_size: f32,
- last_click_time: f32,
velocity: [f32; 2],
motion_blur_amount: f32,
- hotspot: [f32; 2],
- _alignment: [f32; 5],
+ _alignment: [f32; 3],
}
-pub fn find_cursor_event(cursor: &CursorEvents, time: f32) -> &CursorMoveEvent {
+pub fn find_cursor_move(cursor: &CursorEvents, time: f32) -> &CursorMoveEvent {
let time_ms = time * 1000.0;
- if cursor.moves[0].process_time_ms > time_ms.into() {
+ if cursor.moves[0].time_ms > time_ms.into() {
return &cursor.moves[0];
}
@@ -309,7 +292,7 @@ pub fn find_cursor_event(cursor: &CursorEvents, time: f32) -> &CursorMoveEvent {
.rev()
.find(|event| {
// println!("Checking event at time: {}ms", event.process_time_ms);
- event.process_time_ms <= time_ms.into()
+ event.time_ms <= time_ms.into()
})
.unwrap_or(&cursor.moves[0]);
@@ -324,10 +307,7 @@ struct InterpolatedCursorPosition {
fn interpolate_cursor(
cursor: &CursorEvents,
time_secs: f32,
- tension: f32,
- mass: f32,
- friction: f32,
- raw: bool,
+ smoothing: Option<SpringMassDamperSimulationConfig>,
) -> Option<InterpolatedCursorPosition> {
let time_ms = (time_secs * 1000.0) as f64;
@@ -335,7 +315,7 @@ fn interpolate_cursor(
return None;
}
- if cursor.moves[0].process_time_ms > time_ms.into() {
+ if cursor.moves[0].time_ms > time_ms.into() {
let event = &cursor.moves[0];
return Some(InterpolatedCursorPosition {
@@ -348,7 +328,7 @@ fn interpolate_cursor(
}
if let Some(event) = cursor.moves.last() {
- if event.process_time_ms < time_ms.into() {
+ if event.time_ms < time_ms.into() {
return Some(InterpolatedCursorPosition {
position: Coord::new(XY {
x: event.x,
@@ -359,9 +339,12 @@ fn interpolate_cursor(
}
}
- if raw {
+ if let Some(smoothing_config) = smoothing {
+ let events = get_smoothed_cursor_events(&cursor.moves, smoothing_config);
+ interpolate_smoothed_position(&events, time_secs as f64, smoothing_config)
+ } else {
let pos = cursor.moves.windows(2).enumerate().find_map(|(i, chunk)| {
- if time_ms >= chunk[0].process_time_ms && time_ms < chunk[1].process_time_ms {
+ if time_ms >= chunk[0].time_ms && time_ms < chunk[1].time_ms {
let c = &chunk[0];
Some(XY::new(c.x as f32, c.y as f32))
} else {
@@ -376,24 +359,19 @@ fn interpolate_cursor(
}),
velocity: XY::new(0.0, 0.0),
})
- } else {
- let events = get_smoothed_cursor_events(&cursor.moves, tension, mass, friction);
- interpolate_smoothed_position(&events, time_secs as f64, tension, mass, friction)
}
}
fn interpolate_smoothed_position(
smoothed_events: &[SmoothedCursorEvent],
query_time: f64,
- tension: f32,
- mass: f32,
- friction: f32,
+ smoothing_config: SpringMassDamperSimulationConfig,
) -> Option<InterpolatedCursorPosition> {
if smoothed_events.is_empty() {
return None;
}
- let mut sim = SpringMassDamperSimulation::new(tension, mass, friction);
+ let mut sim = SpringMassDamperSimulation::new(smoothing_config);
let query_time_ms = (query_time * 1000.0) as f32;
@@ -432,20 +410,18 @@ struct SmoothedCursorEvent {
fn get_smoothed_cursor_events(
moves: &[CursorMoveEvent],
- tension: f32,
- mass: f32,
- friction: f32,
+ smoothing_config: SpringMassDamperSimulationConfig,
) -> Vec<SmoothedCursorEvent> {
let mut last_time = 0.0;
let mut events = vec![];
- let mut sim = SpringMassDamperSimulation::new(tension, mass, friction);
+ let mut sim = SpringMassDamperSimulation::new(smoothing_config);
sim.set_position(XY::new(moves[0].x, moves[0].y).map(|v| v as f32));
sim.set_velocity(XY::new(0.0, 0.0));
- if moves[0].process_time_ms > 0.0 {
+ if moves[0].time_ms > 0.0 {
events.push(SmoothedCursorEvent {
time: 0.0,
target_position: sim.position,
@@ -461,12 +437,12 @@ fn get_smoothed_cursor_events(
.unwrap_or(sim.target_position);
sim.set_target_position(target_position);
- sim.run(m.process_time_ms as f32 - last_time);
+ sim.run(m.time_ms as f32 - last_time);
- last_time = m.process_time_ms as f32;
+ last_time = m.time_ms as f32;
events.push(SmoothedCursorEvent {
- time: m.process_time_ms as f32,
+ time: m.time_ms as f32,
target_position,
position: sim.position,
velocity: sim.velocity,
@@ -475,3 +451,52 @@ fn get_smoothed_cursor_events(
events
}
+
+fn get_click_t(clicks: &[CursorClickEvent], time_ms: f64) -> f32 {
+ fn smoothstep(low: f32, high: f32, v: f32) -> f32 {
+ let t = f32::clamp((v - low) / (high - low), 0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+ }
+
+ let mut prev_i = None;
+
+ for (i, clicks) in clicks.windows(2).enumerate() {
+ let left = &clicks[0];
+ let right = &clicks[1];
+
+ if left.time_ms <= time_ms && right.time_ms > time_ms {
+ prev_i = Some(i);
+ break;
+ }
+ }
+
+ let Some(prev_i) = prev_i else {
+ return 1.0;
+ };
+
+ let prev = &clicks[prev_i];
+
+ if prev.down {
+ return 0.0;
+ }
+
+ if !prev.down && time_ms - prev.time_ms <= CURSOR_CLICK_DURATION_MS {
+ return smoothstep(
+ 0.0,
+ CURSOR_CLICK_DURATION_MS as f32,
+ (time_ms - prev.time_ms) as f32,
+ );
+ }
+
+ if let Some(next) = clicks.get(prev_i + 1) {
+ if !prev.down && next.down && next.time_ms - time_ms <= CURSOR_CLICK_DURATION_MS {
+ return smoothstep(
+ 0.0,
+ CURSOR_CLICK_DURATION_MS as f32,
+ (time_ms - next.time_ms).abs() as f32,
+ );
+ }
+ }
+
+ 1.0
+}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 1593c5be1..676b22e12 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -47,6 +47,7 @@ pub struct RenderOptions {
pub struct RecordingSegmentDecoders {
screen: AsyncVideoDecoderHandle,
camera: Option<AsyncVideoDecoderHandle>,
+ pub segment_offset: f64,
}
pub struct SegmentVideoPaths {
@@ -59,13 +60,34 @@ impl RecordingSegmentDecoders {
recording_meta: &RecordingMeta,
meta: &StudioRecordingMeta,
segment: SegmentVideoPaths,
+ segment_i: usize,
) -> Result<Self, String> {
+ let latest_start_time = match &meta {
+ StudioRecordingMeta::SingleSegment { .. } => None,
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
+ inner.segments[segment_i].latest_start_time()
+ }
+ };
+
let screen = spawn_decoder(
"screen",
recording_meta.project_path.join(segment.display),
match &meta {
StudioRecordingMeta::SingleSegment { segment } => segment.display.fps,
- StudioRecordingMeta::MultipleSegments { inner } => inner.segments[0].display.fps,
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
+ inner.segments[segment_i].display.fps
+ }
+ },
+ match &meta {
+ StudioRecordingMeta::SingleSegment { .. } => 0.0,
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
+ let segment = &inner.segments[segment_i];
+
+ latest_start_time
+ .zip(segment.display.start_time)
+ .map(|(latest_start_time, display_time)| latest_start_time - display_time)
+ .unwrap_or(0.0)
+ }
},
)
.await
@@ -78,17 +100,32 @@ impl RecordingSegmentDecoders {
StudioRecordingMeta::SingleSegment { segment } => {
segment.camera.as_ref().unwrap().fps
}
- StudioRecordingMeta::MultipleSegments { inner } => {
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
inner.segments[0].camera.as_ref().unwrap().fps
}
},
+ match &meta {
+ StudioRecordingMeta::SingleSegment { .. } => 0.0,
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
+ let segment = &inner.segments[segment_i];
+
+ latest_start_time
+ .zip(segment.camera.as_ref().and_then(|c| c.start_time))
+ .map(|(latest_start_time, start_time)| latest_start_time - start_time)
+ .unwrap_or(0.0)
+ }
+ },
)
.then(|r| async { r.map_err(|e| format!("Camera:{e}")) })
}))
.await
.transpose()?;
- Ok(Self { screen, camera })
+ Ok(Self {
+ screen,
+ camera,
+ segment_offset: latest_start_time.unwrap_or(0.0),
+ })
}
pub async fn get_frames(
@@ -109,6 +146,7 @@ impl RecordingSegmentDecoders {
screen_frame: screen?,
camera_frame: camera.flatten(),
segment_time,
+ recording_time: segment_time + self.segment_offset as f32,
})
}
}
@@ -143,16 +181,17 @@ pub async fn render_video_to_channel(
segments: Vec<RenderSegment>,
fps: u32,
resolution_base: XY<u32>,
+ recordings: &ProjectRecordings,
) -> Result<(), RenderingError> {
let constants = RenderVideoConstants::new(options, recording_meta, meta).await?;
- let recordings = ProjectRecordings::new(&recording_meta.project_path, meta);
+ // let recordings = ProjectRecordings::new(&recording_meta.project_path, meta);
ffmpeg::init().unwrap();
let start_time = Instant::now();
// Get the duration from the timeline if it exists, otherwise use the longest source duration
- let duration = get_duration(&recordings, recording_meta, meta, &project);
+ let duration = get_duration(recordings, recording_meta, meta, &project);
let total_frames = (fps as f64 * duration).ceil() as u32;
println!(
@@ -184,17 +223,22 @@ pub async fn render_video_to_channel(
std::mem::replace(&mut frame_number, prev + 1)
};
+ let now = Instant::now();
if let Some(segment_frames) = segment
.decoders
.get_frames(segment_time as f32, !project.camera.hide)
.await
{
+ println!("decoded frames in {:?}", now.elapsed());
let uniforms =
ProjectUniforms::new(&constants, &project, frame_number, fps, resolution_base);
+ let now = Instant::now();
+
let frame = frame_renderer
.render(segment_frames, uniforms, &segment.cursor)
.await?;
+ println!("rendered frame in {:?}", now.elapsed());
if frame.width == 0 || frame.height == 0 {
continue;
}
@@ -259,7 +303,7 @@ pub fn get_duration(
pub struct CursorTexture {
inner: wgpu::Texture,
- hotspot: XY<f64>,
+ hotspot: XY<f32>,
}
pub struct RenderVideoConstants {
@@ -396,7 +440,7 @@ impl RenderVideoConstants {
let cursor_images = match &meta {
StudioRecordingMeta::SingleSegment { .. } => Default::default(),
- StudioRecordingMeta::MultipleSegments { inner } => {
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
inner.cursor_images(recording_meta).unwrap_or_default()
}
};
@@ -465,7 +509,7 @@ impl RenderVideoConstants {
cursor_id.clone(),
CursorTexture {
inner: texture,
- hotspot: cursor.hotspot,
+ hotspot: cursor.hotspot.map(|v| v as f32),
},
);
println!("Successfully loaded cursor texture: {}", cursor_id);
@@ -882,6 +926,7 @@ pub struct DecodedSegmentFrames {
pub screen_frame: DecodedFrame,
pub camera_frame: Option<DecodedFrame>,
pub segment_time: f32,
+ pub recording_time: f32,
}
pub struct FrameRenderer<'a> {
diff --git a/crates/rendering/src/project_recordings.rs b/crates/rendering/src/project_recordings.rs
index 1556115fc..ce5a8d5ed 100644
--- a/crates/rendering/src/project_recordings.rs
+++ b/crates/rendering/src/project_recordings.rs
@@ -1,7 +1,9 @@
-use std::path::{Path, PathBuf};
+use std::{
+ cell::RefCell,
+ path::{Path, PathBuf},
+};
-use crate::RecordingMeta;
-use cap_project::StudioRecordingMeta;
+use cap_project::{AudioMeta, StudioRecordingMeta, VideoMeta};
use serde::Serialize;
use specta::Type;
@@ -11,11 +13,12 @@ pub struct Video {
pub width: u32,
pub height: u32,
pub fps: u32,
+ pub start_time: f64,
}
impl Video {
- pub fn new(path: impl AsRef<Path>) -> Result<Self, String> {
- fn inner(path: &Path) -> Result<Video, String> {
+ pub fn new(path: impl AsRef<Path>, start_time: f64) -> Result<Self, String> {
+ fn inner(path: &Path, start_time: f64) -> Result<Video, String> {
let input =
ffmpeg::format::input(path).map_err(|e| format!("Failed to open video: {}", e))?;
let stream = input
@@ -37,10 +40,11 @@ impl Video {
height: video_decoder.height(),
duration: input.duration() as f64 / 1_000_000.0,
fps: fps.round() as u32,
+ start_time,
})
}
- inner(path.as_ref())
+ inner(path.as_ref(), start_time)
}
pub fn fps(&self) -> u32 {
@@ -53,11 +57,12 @@ pub struct Audio {
pub duration: f64,
pub sample_rate: u32,
pub channels: u16,
+ pub start_time: f64,
}
impl Audio {
- pub fn new(path: impl AsRef<Path>) -> Result<Self, String> {
- fn inner(path: &Path) -> Result<Audio, String> {
+ pub fn new(path: impl AsRef<Path>, start_time: f64) -> Result<Self, String> {
+ fn inner(path: &Path, start_time: f64) -> Result<Audio, String> {
let input =
ffmpeg::format::input(path).map_err(|e| format!("Failed to open audio: {}", e))?;
let stream = input
@@ -75,10 +80,11 @@ impl Audio {
duration: input.duration() as f64 / 1_000_000.0,
sample_rate: audio_decoder.rate(),
channels: audio_decoder.channels(),
+ start_time,
})
}
- inner(path.as_ref())
+ inner(path.as_ref(), start_time)
}
}
@@ -88,64 +94,87 @@ pub struct ProjectRecordings {
}
impl ProjectRecordings {
- pub fn new(recording_path: &PathBuf, meta: &StudioRecordingMeta) -> Self {
+ pub fn new(recording_path: &PathBuf, meta: &StudioRecordingMeta) -> Result<Self, String> {
let segments = match &meta {
- StudioRecordingMeta::SingleSegment { segment } => {
- let display = Video::new(segment.display.path.to_path(recording_path))
+ StudioRecordingMeta::SingleSegment { segment: s } => {
+ let display = Video::new(s.display.path.to_path(recording_path), 0.0)
.expect("Failed to read display video");
- let camera = segment.camera.as_ref().map(|camera| {
- Video::new(&camera.path.to_path(recording_path))
+ let camera = s.camera.as_ref().map(|camera| {
+ Video::new(camera.path.to_path(recording_path), 0.0)
.expect("Failed to read camera video")
});
- let audio = segment
+ let mic = s
.audio
.as_ref()
- .map(|audio| Audio::new(audio.path.to_path(recording_path)))
+ .map(|audio| Audio::new(audio.path.to_path(recording_path), 0.0))
.transpose()
.expect("Failed to read audio");
vec![SegmentRecordings {
display,
camera,
- audio,
+ mic,
system_audio: None,
}]
}
- StudioRecordingMeta::MultipleSegments { inner } => inner
+ StudioRecordingMeta::MultipleSegments { inner, .. } => inner
.segments
.iter()
.map(|s| {
- let display = Video::new(s.display.path.to_path(recording_path))
- .expect("Failed to read display video");
- let camera = s.camera.as_ref().map(|camera| {
- Video::new(&camera.path.to_path(recording_path))
- .expect("Failed to read camera video")
- });
- let audio = s
- .audio
- .as_ref()
- .map(|audio| Audio::new(audio.path.to_path(recording_path)))
- .transpose()
- .expect("Failed to read audio");
-
- let system_audio = s
- .system_audio
- .as_ref()
- .map(|audio| Audio::new(audio.path.to_path(recording_path)))
- .transpose()
- .expect("Failed to read audio");
-
- SegmentRecordings {
- display,
- camera,
- audio,
- system_audio,
- }
+ let has_start_times = RefCell::new(None);
+
+ let ensure_start_time = |time: Option<f64>| {
+ let Some(has_start_times) = has_start_times.borrow_mut().clone() else {
+ *has_start_times.borrow_mut() = Some(time.is_some());
+ return Ok(time.unwrap_or_default());
+ };
+
+ Ok(if has_start_times {
+ if let Some(time) = time {
+ time
+ } else {
+ return Err("Missing start time".to_string());
+ }
+ } else {
+ if time.is_some() {
+ return Err("Start time mismatch".to_string());
+ } else {
+ 0.0
+ }
+ })
+ };
+
+ let load_video = |meta: &VideoMeta| {
+ ensure_start_time(meta.start_time).and_then(|start_time| {
+ Video::new(meta.path.to_path(recording_path), start_time)
+ })
+ };
+
+ let load_audio = |meta: &AudioMeta| {
+ ensure_start_time(meta.start_time).and_then(|start_time| {
+ Audio::new(meta.path.to_path(recording_path), start_time)
+ })
+ };
+
+ Ok::<_, String>(SegmentRecordings {
+ display: load_video(&s.display).map_err(|e| format!("video / {e}"))?,
+ camera: Option::map(s.camera.as_ref(), load_video)
+ .transpose()
+ .map_err(|e| format!("camera / {e}"))?,
+ mic: Option::map(s.mic.as_ref(), load_audio)
+ .transpose()
+ .map_err(|e| format!("mic / {e}"))?,
+ system_audio: Option::map(s.system_audio.as_ref(), load_audio)
+ .transpose()
+ .map_err(|e| format!("system audio / {e}"))?,
+ })
})
- .collect(),
+ .enumerate()
+ .map(|(i, v)| v.map_err(|e| format!("segment {i} / {e}")))
+ .collect::<Result<_, String>>()?,
};
- Self { segments }
+ Ok(Self { segments })
}
pub fn duration(&self) -> f64 {
@@ -153,7 +182,7 @@ impl ProjectRecordings {
}
pub fn get_source_duration(&self, path: &PathBuf) -> Result<f64, String> {
- Video::new(path).map(|v| v.duration)
+ Video::new(path, 0.0).map(|v| v.duration)
}
}
@@ -161,7 +190,7 @@ impl ProjectRecordings {
pub struct SegmentRecordings {
pub display: Video,
pub camera: Option<Video>,
- pub audio: Option<Audio>,
+ pub mic: Option<Audio>,
pub system_audio: Option<Audio>,
}
@@ -170,7 +199,7 @@ impl SegmentRecordings {
let mut duration_ns = [
Some(self.display.duration),
self.camera.as_ref().map(|s| s.duration),
- self.audio.as_ref().map(|s| s.duration),
+ self.mic.as_ref().map(|s| s.duration),
]
.into_iter()
.flatten()
diff --git a/crates/rendering/src/shaders/cursor.wgsl b/crates/rendering/src/shaders/cursor.wgsl
index cd11ae38c..dbffc5b87 100644
--- a/crates/rendering/src/shaders/cursor.wgsl
+++ b/crates/rendering/src/shaders/cursor.wgsl
@@ -4,16 +4,12 @@ struct VertexOutput {
};
struct Uniforms {
- position: vec4<f32>,
- size: vec4<f32>,
+ position: vec2<f32>,
+ size: vec2<f32>,
output_size: vec4<f32>,
screen_bounds: vec4<f32>,
- cursor_size: f32,
- last_click_time: f32,
velocity: vec2<f32>,
motion_blur_amount: f32,
- hotspot: vec2<f32>,
- _alignment: vec4<f32>,
};
@group(0) @binding(0)
@@ -41,18 +37,15 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
vec2<f32>(1.0, 1.0)
);
- let pos = positions[vertex_index] - uniforms.hotspot;
- let size = uniforms.size.xy;
+ let pos = positions[vertex_index];
let screen_pos = uniforms.position.xy;
- let scaled_size = size * uniforms.cursor_size;
-
// Calculate final position - centered around cursor position
// Flip the Y coordinate by subtracting from output height
var adjusted_pos = screen_pos;
adjusted_pos.y = uniforms.output_size.y - adjusted_pos.y; // Flip Y coordinate
- let final_pos = ((pos * scaled_size) + adjusted_pos) / uniforms.output_size.xy * 2.0 - 1.0;
+ let final_pos = ((pos * uniforms.size) + adjusted_pos) / uniforms.output_size.xy * 2.0 - 1.0;
var output: VertexOutput;
output.position = vec4<f32>(final_pos, 0.0, 1.0);
diff --git a/crates/rendering/src/spring_mass_damper.rs b/crates/rendering/src/spring_mass_damper.rs
index cdc53318e..a5be0567a 100644
--- a/crates/rendering/src/spring_mass_damper.rs
+++ b/crates/rendering/src/spring_mass_damper.rs
@@ -1,5 +1,12 @@
use cap_project::XY;
+#[derive(Clone, Copy)]
+pub struct SpringMassDamperSimulationConfig {
+ pub tension: f32,
+ pub mass: f32,
+ pub friction: f32,
+}
+
pub struct SpringMassDamperSimulation {
tension: f32,
mass: f32,
@@ -12,11 +19,11 @@ pub struct SpringMassDamperSimulation {
const SIMULATION_TICK: f32 = 1000.0 / 60.0;
impl SpringMassDamperSimulation {
- pub fn new(tension: f32, mass: f32, friction: f32) -> Self {
+ pub fn new(config: SpringMassDamperSimulationConfig) -> Self {
Self {
- tension,
- mass,
- friction,
+ tension: config.tension,
+ mass: config.mass,
+ friction: config.friction,
position: XY::new(0.0, 0.0),
velocity: XY::new(0.0, 0.0),
target_position: XY::new(0.0, 0.0),
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index 16786c720..9bab10ffa 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -6,7 +6,7 @@
// biome-ignore lint: disable
export {}
declare global {
- const IconCapArrows: typeof import('~icons/cap/arrows.jsx')['default']
+ const IconCapArrows: typeof import("~icons/cap/arrows.jsx")["default"]
const IconCapAudioOn: typeof import('~icons/cap/audio-on.jsx')['default']
const IconCapAuto: typeof import("~icons/cap/auto.jsx")["default"]
const IconCapBgBlur: typeof import('~icons/cap/bg-blur.jsx')['default']
@@ -23,7 +23,7 @@ declare global {
const IconCapCorners: typeof import('~icons/cap/corners.jsx')['default']
const IconCapCrop: typeof import('~icons/cap/crop.jsx')['default']
const IconCapCursor: typeof import('~icons/cap/cursor.jsx')['default']
- const IconCapEditor: typeof import('~icons/cap/editor.jsx')['default']
+ const IconCapEditor: typeof import("~icons/cap/editor.jsx")["default"]
const IconCapEnlarge: typeof import('~icons/cap/enlarge.jsx')['default']
const IconCapFile: typeof import('~icons/cap/file.jsx')['default']
const IconCapFilmCut: typeof import('~icons/cap/film-cut.jsx')['default']
@@ -42,29 +42,29 @@ declare global {
const IconCapLogoFullDark: typeof import('~icons/cap/logo-full-dark.jsx')['default']
const IconCapMessageBubble: typeof import('~icons/cap/message-bubble.jsx')['default']
const IconCapMicrophone: typeof import('~icons/cap/microphone.jsx')['default']
- const IconCapMoreVertical: typeof import('~icons/cap/more-vertical.jsx')['default']
+ const IconCapMoreVertical: typeof import("~icons/cap/more-vertical.jsx")["default"]
const IconCapMoveLeft: typeof import("~icons/cap/move-left.jsx")["default"]
const IconCapMoveRight: typeof import("~icons/cap/move-right.jsx")["default"]
const IconCapNext: typeof import('~icons/cap/next.jsx')['default']
const IconCapPadding: typeof import('~icons/cap/padding.jsx')['default']
const IconCapPause: typeof import('~icons/cap/pause.jsx')['default']
- const IconCapPauseCircle: typeof import('~icons/cap/pause-circle.jsx')['default']
+ const IconCapPauseCircle: typeof import("~icons/cap/pause-circle.jsx")["default"]
const IconCapPlay: typeof import('~icons/cap/play.jsx')['default']
- const IconCapPlayCircle: typeof import('~icons/cap/play-circle.jsx')['default']
+ const IconCapPlayCircle: typeof import("~icons/cap/play-circle.jsx")["default"]
const IconCapPresets: typeof import('~icons/cap/presets.jsx')['default']
const IconCapPrev: typeof import('~icons/cap/prev.jsx')['default']
const IconCapRedo: typeof import('~icons/cap/redo.jsx')['default']
- const IconCapRestart: typeof import('~icons/cap/restart.jsx')['default']
+ const IconCapRestart: typeof import("~icons/cap/restart.jsx")["default"]
const IconCapScissors: typeof import('~icons/cap/scissors.jsx')['default']
const IconCapSettings: typeof import('~icons/cap/settings.jsx')['default']
const IconCapShadow: typeof import('~icons/cap/shadow.jsx')['default']
const IconCapSize: typeof import("~icons/cap/size.jsx")["default"]
- const IconCapSquare: typeof import('~icons/cap/square.jsx')['default']
+ const IconCapSquare: typeof import("~icons/cap/square.jsx")["default"]
const IconCapStop: typeof import("~icons/cap/stop.jsx")["default"]
- const IconCapStopCircle: typeof import('~icons/cap/stop-circle.jsx')['default']
+ const IconCapStopCircle: typeof import("~icons/cap/stop-circle.jsx")["default"]
const IconCapTrash: typeof import('~icons/cap/trash.jsx')['default']
const IconCapUndo: typeof import('~icons/cap/undo.jsx')['default']
- const IconCapUpload: typeof import('~icons/cap/upload.jsx')['default']
+ const IconCapUpload: typeof import("~icons/cap/upload.jsx")["default"]
const IconCapZoomIn: typeof import('~icons/cap/zoom-in.jsx')['default']
const IconCapZoomOut: typeof import('~icons/cap/zoom-out.jsx')['default']
const IconHugeiconsEaseCurveControlPoints: typeof import('~icons/hugeicons/ease-curve-control-points.jsx')['default']
@@ -72,13 +72,13 @@ declare global {
const IconIcRoundSearch: typeof import("~icons/ic/round-search.jsx")["default"]
const IconLucideBell: typeof import('~icons/lucide/bell.jsx')['default']
const IconLucideBug: typeof import('~icons/lucide/bug.jsx')['default']
- const IconLucideCamera: typeof import('~icons/lucide/camera.jsx')['default']
+ const IconLucideCamera: typeof import("~icons/lucide/camera.jsx")["default"]
const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default']
const IconLucideChevronDown: typeof import("~icons/lucide/chevron-down.jsx")["default"]
const IconLucideClock: typeof import('~icons/lucide/clock.jsx')['default']
- const IconLucideDatabase: typeof import('~icons/lucide/database.jsx')['default']
+ const IconLucideDatabase: typeof import("~icons/lucide/database.jsx")["default"]
const IconLucideEdit: typeof import('~icons/lucide/edit.jsx')['default']
- const IconLucideEye: typeof import('~icons/lucide/eye.jsx')['default']
+ const IconLucideEye: typeof import("~icons/lucide/eye.jsx")["default"]
const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default']
const IconLucideGift: typeof import('~icons/lucide/gift.jsx')['default']
const IconLucideHardDrive: typeof import('~icons/lucide/hard-drive.jsx')['default']
@@ -87,7 +87,7 @@ declare global {
const IconLucideMessageCircle: typeof import("~icons/lucide/message-circle.jsx")["default"]
const IconLucideMessageSquare: typeof import("~icons/lucide/message-square.jsx")["default"]
const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default']
- const IconLucideMicOff: typeof import('~icons/lucide/mic-off.jsx')['default']
+ const IconLucideMicOff: typeof import("~icons/lucide/mic-off.jsx")["default"]
const IconLucideMonitor: typeof import("~icons/lucide/monitor.jsx")["default"]
const IconLucideRabbit: typeof import("~icons/lucide/rabbit.jsx")["default"]
const IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw.jsx')['default']
@@ -95,8 +95,8 @@ declare global {
const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default']
const IconLucideUnplug: typeof import('~icons/lucide/unplug.jsx')['default']
const IconLucideVideo: typeof import("~icons/lucide/video.jsx")["default"]
- const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default']
- const IconLucideVolumeX: typeof import('~icons/lucide/volume-x.jsx')['default']
+ const IconLucideVolume2: typeof import("~icons/lucide/volume2.jsx")["default"]
+ const IconLucideVolumeX: typeof import("~icons/lucide/volume-x.jsx")["default"]
const IconMdiMonitor: typeof import("~icons/mdi/monitor.jsx")["default"]
const IconPhMonitorBold: typeof import('~icons/ph/monitor-bold.jsx')['default']
}