@tvpipe/sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +231 -2
  3. package/bin/tvpipe.js +29 -0
  4. package/dist/api.d.ts +189 -0
  5. package/dist/api.d.ts.map +1 -0
  6. package/dist/api.js +348 -0
  7. package/dist/api.js.map +1 -0
  8. package/dist/binary.d.ts +21 -0
  9. package/dist/binary.d.ts.map +1 -0
  10. package/dist/binary.js +73 -0
  11. package/dist/binary.js.map +1 -0
  12. package/dist/canvas.d.ts +21 -0
  13. package/dist/canvas.d.ts.map +1 -0
  14. package/dist/canvas.js +14 -0
  15. package/dist/canvas.js.map +1 -0
  16. package/dist/errors.d.ts +33 -0
  17. package/dist/errors.d.ts.map +1 -0
  18. package/dist/errors.js +23 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/events.d.ts +172 -0
  21. package/dist/events.d.ts.map +1 -0
  22. package/dist/events.js +55 -0
  23. package/dist/events.js.map +1 -0
  24. package/dist/index.d.ts +15 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +13 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/process.d.ts +78 -0
  29. package/dist/process.d.ts.map +1 -0
  30. package/dist/process.js +248 -0
  31. package/dist/process.js.map +1 -0
  32. package/dist/session.d.ts +93 -0
  33. package/dist/session.d.ts.map +1 -0
  34. package/dist/session.js +192 -0
  35. package/dist/session.js.map +1 -0
  36. package/dist/slrw.d.ts +40 -0
  37. package/dist/slrw.d.ts.map +1 -0
  38. package/dist/slrw.js +86 -0
  39. package/dist/slrw.js.map +1 -0
  40. package/dist/stream.d.ts +109 -0
  41. package/dist/stream.d.ts.map +1 -0
  42. package/dist/stream.js +230 -0
  43. package/dist/stream.js.map +1 -0
  44. package/package.json +52 -4
  45. package/src/api.ts +540 -0
  46. package/src/binary.ts +92 -0
  47. package/src/canvas.ts +30 -0
  48. package/src/errors.ts +77 -0
  49. package/src/events.ts +258 -0
  50. package/src/index.ts +50 -0
  51. package/src/process.ts +283 -0
  52. package/src/session.ts +262 -0
  53. package/src/slrw.ts +99 -0
  54. package/src/stream.ts +297 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,232 @@
1
- # Temporary Holding Version
1
+ # @tvpipe/sdk: tvpipe for Node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Stream video and audio from Node to **Apple TV / AirPlay**, **Chromecast /
4
+ Google Cast** and **browser tabs**, with low latency: files, URLs, web
5
+ pages, a test pattern, or frames your program draws (a canvas, raw RGBA,
6
+ H.264 from WebCodecs) with sound.
7
+
8
+ ```sh
9
+ npm install @tvpipe/sdk
10
+ ```
11
+
12
+ It drives the [tvpipe](https://github.com/mitsuhiko/tvpipe) binary,
13
+ which npm installs for your platform: macOS, Linux and Windows on x64 and
14
+ ARM64. You don't need to set anything up. Node 22 or newer. No runtime
15
+ dependencies.
16
+
17
+ ```js
18
+ import { play } from "@tvpipe/sdk";
19
+
20
+ const session = await play("movie.mp4"); // the only TV on the network
21
+ await session.done; // until the end of the movie
22
+ ```
23
+
24
+ ## Receivers
25
+
26
+ ```js
27
+ import { discover } from "@tvpipe/sdk";
28
+
29
+ for (const d of await discover({ timeout: 3000 })) {
30
+ console.log(d.name, d.protocols, d.model, d.paired);
31
+ }
32
+ ```
33
+
34
+ `to` accepts:
35
+
36
+ - a name (`"Living Room"`, or a unique prefix of one, any case);
37
+ - `"airplay:NAME"` or `"cast:NAME"` to pick the protocol of a TV that
38
+ speaks both;
39
+ - an address (`"192.168.1.20"` is Cast, `"192.168.1.20:7000"` is
40
+ AirPlay);
41
+ - `"browser"`, a player page on this computer (`session.playerUrl`);
42
+ - a `Device` from `discover()`;
43
+ - a list of any of these, to play on all of them at once, in sync.
44
+
45
+ Without `to`, tvpipe uses the only receiver with video on the network.
46
+ If there are several, the error lists them.
47
+
48
+ ## Files, URLs, the test pattern, web pages
49
+
50
+ ```js
51
+ import { play, testPattern, preview, share } from "@tvpipe/sdk";
52
+
53
+ await play("movie.mkv", { to: "Living Room", loop: true });
54
+ await play("https://example.com/live.m3u8", { to: ["Kitchen", "Office"] });
55
+ await play({ ffmpeg: ["-f", "avfoundation", "-i", "1:0"] }, { to: "TV" }); // capture
56
+
57
+ await testPattern({ to: "TV" }); // clock, frame counter, beep
58
+ const p = await preview("movie.mp4"); // a browser tab
59
+ console.log(p.playerUrl);
60
+
61
+ await share("https://status.example.com", { to: "TV", reload: 30 }); // headless Chromium
62
+ ```
63
+
64
+ The test pattern, frames from code, and MP4/MKV files with H.264 that
65
+ tvpipe can send unchanged need no ffmpeg. Other files, URLs and capture
66
+ devices need [ffmpeg](https://ffmpeg.org) in `PATH` (or `ffmpeg:
67
+ "/path"`). If ffmpeg is missing, the error has the code `ffmpeg-missing`.
68
+ `share(url)` needs Chrome, Edge, Chromium or Brave.
69
+
70
+ ## Frames from code
71
+
72
+ ```js
73
+ import { stream } from "@tvpipe/sdk";
74
+
75
+ const s = await stream({
76
+ to: "Living Room",
77
+ video: { width: 1280, height: 720, fps: 30, format: "rgba" },
78
+ audio: { sampleRate: 48000, channels: 2 },
79
+ });
80
+
81
+ s.writeVideo(rgbaBytes); // timestamps default to "now"
82
+ s.writeAudio(float32Samples); // interleaved; Int16Array works too
83
+ // ...
84
+ await s.end(); // play out what was written, then stop
85
+ ```
86
+
87
+ - **Canvases**: `s.writeCanvas(canvas)` sends one picture.
88
+ `s.drawLoop(canvas, (ctx, timeMs) => draw(ctx, timeMs))` draws and sends
89
+ at the frame rate. Any canvas with `getContext("2d").getImageData`
90
+ works: [canvas](https://www.npmjs.com/package/canvas),
91
+ [skia-canvas](https://www.npmjs.com/package/skia-canvas),
92
+ [@napi-rs/canvas](https://www.npmjs.com/package/@napi-rs/canvas),
93
+ OffscreenCanvas.
94
+ - **Backpressure**: when tvpipe falls behind, `writeVideo` drops the frame
95
+ and returns `false` (`s.dropped.video` counts them). A live source stays
96
+ real time and memory stays bounded. To send every frame, `await
97
+ s.drain()` instead. Audio is never dropped.
98
+ - **Encoder**: the built-in H.264 encoder by default. It needs no ffmpeg
99
+ and gives keyframes on demand. `encoder: "auto"` (or `x264`,
100
+ `videotoolbox`, `nvenc`, …) uses ffmpeg instead.
101
+ - **H.264 you encode yourself**: create the stream with `video: { width,
102
+ height, fps, codec: "h264" }`, then pass WebCodecs output to
103
+ `s.writeChunk(chunk, metadata)`, or access units to `s.writeH264(au, {
104
+ keyframe })`. Answer the `keyframe` event with an IDR frame:
105
+
106
+ ```js
107
+ s.on("keyframe", () => (forceKey = true));
108
+ encoder.encode(frame, { keyFrame: forceKey });
109
+ ```
110
+
111
+ An example with a moving picture and a tone:
112
+ [`examples/canvas-tone.ts`](https://github.com/mitsuhiko/tvpipe/blob/main/npm/tvpipe/examples/canvas-tone.ts).
113
+
114
+ ## Sessions
115
+
116
+ `play`, `testPattern`, `preview` and `share` resolve once streaming has
117
+ started. `stream` resolves once the receivers are connected. All of them
118
+ return a `Session`:
119
+
120
+ ```js
121
+ session.on("receiver", (r) => console.log(r.name, r.state)); // connected, lost, reconnected, ended, …
122
+ session.on("stats", (s) => console.log(s.videoFrames)); // every second
123
+ session.on("log", (l) => console.log(l.level, l.message));
124
+ session.receivers; // Map: name → { protocol, state, error }
125
+ session.info; // video size, frame rate, audio, latency
126
+ await session.stop(); // the TV leaves mirroring
127
+ await session.done; // resolves when the session ends, rejects if it fails
128
+ ```
129
+
130
+ `await using session = await play(...)` stops it at the end of the scope.
131
+ `signal: abortController.signal` stops it on abort. If a TV drops out
132
+ (Wi-Fi, a new address), it is reconnected for up to `reconnect` seconds
133
+ (120 by default) while the others keep playing.
134
+
135
+ If your program exits or crashes, tvpipe notices that its stdin closed.
136
+ It stops the TVs cleanly and exits.
137
+
138
+ ## Public links
139
+
140
+ ```js
141
+ const p = await preview("movie.mp4", { player: { tunnel: true } });
142
+ console.log(p.publicUrl); // https://….trycloudflare.com/?t=…: anyone with it can watch
143
+
144
+ const s = await share({ to: "TV", tunnel: "opentunnel", yes: true });
145
+ console.log(s.publicUrl); // someone elsewhere opens it and shares their screen to the TV
146
+ ```
147
+
148
+ `tunnel: true` uses a Cloudflare quick tunnel, `"opentunnel"` OpenTunnel
149
+ (TLS ends in tvpipe). The link is new every session; `tunnelTtl` limits
150
+ how long it lets people in (minutes). The command line asks on the
151
+ terminal before a remote share reaches the TV; a session has no terminal,
152
+ so pass `yes: true` or remote shares are refused. The `tunnel` event and
153
+ `viewer` events (`public: true`) tell you what happens. Details:
154
+ [docs/tunnels.md](https://github.com/mitsuhiko/tvpipe/blob/main/docs/tunnels.md).
155
+
156
+ ## Apple TV pairing
157
+
158
+ Some AirPlay receivers show a PIN the first time:
159
+
160
+ ```js
161
+ import { pair } from "@tvpipe/sdk";
162
+
163
+ await pair("Living Room", { onPin: async ({ name }) => await ask(`PIN shown on ${name}?`) });
164
+ // or let a session pair when it needs to:
165
+ await play("movie.mp4", { to: "Living Room", onPin: ({ name }) => ask(name) });
166
+ ```
167
+
168
+ Pairings are stored in tvpipe's config directory (`credentials.txt`), the
169
+ same one the `tvpipe` command line tool uses:
170
+
171
+ | | |
172
+ |---|---|
173
+ | macOS | `~/Library/Application Support/tvpipe` |
174
+ | Linux | `$XDG_CONFIG_HOME/tvpipe` (`~/.config/tvpipe`) |
175
+ | Windows | `%APPDATA%\tvpipe` |
176
+
177
+ Pass `configDir` to keep them somewhere else, e.g. in your app's data
178
+ directory. The file holds a private key.
179
+
180
+ ## Errors
181
+
182
+ Every failure is a `TvpipeError` with a readable `message` and a stable
183
+ `code`:
184
+
185
+ | `code` | |
186
+ |---|---|
187
+ | `no-receivers`, `ambiguous-receiver` | `to` was omitted and there is no single TV (`details.devices` lists them) |
188
+ | `no-receiver` | no receiver with that name was found |
189
+ | `pairing-required` | an Apple TV needs `pair()` (or `onPin`); `device` names it |
190
+ | `input-not-found`, `ffmpeg-missing` | the input |
191
+ | `binary-missing`, `unsupported-platform` | the binary is not installed (see below) |
192
+ | `aborted`, `usage`, `invalid-argument`, `exited`, … | |
193
+
194
+ `error.log` holds tvpipe's last log lines.
195
+
196
+ ## Options
197
+
198
+ All options are optional.
199
+
200
+ | Option | |
201
+ |---|---|
202
+ | `to` | receivers (above) |
203
+ | `latency` | playout delay in ms, the same on every receiver (default: Cast 300, AirPlay automatic, browser 100) |
204
+ | `size`, `fps`, `bitrate` | output limits (`"1280x720"`, frames per second, kbit/s) |
205
+ | `audio: false` | video only |
206
+ | `reconnect` | seconds to reconnect a lost receiver (0: off) |
207
+ | `player` | the browser page: `{ port, open, waitForViewer, newToken, tunnel, tunnelTtl }`; the port defaults to any free one |
208
+ | `tunnel`, `tunnelTtl`, `yes` | `share()` without URL: the share page on a public link (above) |
209
+ | `onPin` | pair receivers that need it |
210
+ | `signal`, `stopTimeout` | stop on abort; how long `stop()` waits before killing tvpipe |
211
+ | `logs` | mirror tvpipe's log to stderr (`true` or a level) or a function |
212
+ | `verbose` | debug logs (`"trace"`: protocol traces) |
213
+ | `configDir`, `env`, `binary` | where pairings live, the environment, a tvpipe binary to use |
214
+
215
+ ## The binary
216
+
217
+ npm installs the binary as an optional dependency for your platform:
218
+ `@tvpipe/darwin-arm64`, `@tvpipe/darwin-x64`, `@tvpipe/linux-x64`,
219
+ `@tvpipe/linux-arm64`, `@tvpipe/win32-x64` or `@tvpipe/win32-arm64`. The
220
+ Linux binaries are static, so they also work on Alpine. If you install
221
+ with `--omit=optional`, or copy a lockfile made on another platform, the
222
+ binary is missing and you get a `binary-missing` error. To use a binary
223
+ you built or installed yourself, set `TVPIPE_BINARY=/path/to/tvpipe` (or
224
+ pass the `binary` option). The package also installs the command line tool:
225
+ `npx tvpipe ...` in a project that depends on it, or `npx -p @tvpipe/sdk
226
+ tvpipe ...` anywhere.
227
+
228
+ ## License
229
+
230
+ Apache-2.0. The binary packages are Apache-2.0 AND LGPL-3.0-or-later,
231
+ because the binary includes an LGPL module (see the
232
+ [repository](https://github.com/mitsuhiko/tvpipe)).
package/bin/tvpipe.js ADDED
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ // `npx -p @tvpipe/sdk tvpipe …` (or `npx tvpipe` where it is installed): runs the platform binary with this process's stdio.
3
+ import { spawn } from "node:child_process";
4
+
5
+ import { resolveBinary } from "../dist/binary.js";
6
+
7
+ let binary;
8
+ try {
9
+ binary = resolveBinary();
10
+ } catch (err) {
11
+ console.error(`tvpipe: ${err.message}`);
12
+ process.exit(1);
13
+ }
14
+ const child = spawn(binary, process.argv.slice(2), { stdio: "inherit" });
15
+ // Ctrl-C reaches tvpipe too (same process group / console); it tears the
16
+ // receivers down and exits, then so do we.
17
+ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
18
+ process.on(sig, () => {
19
+ if (sig !== "SIGINT") child.kill(sig);
20
+ });
21
+ }
22
+ child.on("error", (err) => {
23
+ console.error(`tvpipe: cannot run ${binary}: ${err.message}`);
24
+ process.exit(1);
25
+ });
26
+ child.on("exit", (code, signal) => {
27
+ if (signal) process.kill(process.pid, signal);
28
+ else process.exit(code ?? 1);
29
+ });
package/dist/api.d.ts ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The functions: discover, pair, unpair, play, testPattern, preview,
3
+ * share, stream, version.
4
+ */
5
+ import { type BinaryOptions } from "./binary.ts";
6
+ import type { StartedEvent, TunnelProvider } from "./events.ts";
7
+ import { type ProcessOptions } from "./process.ts";
8
+ import { Session, type SessionOptions } from "./session.ts";
9
+ import { StreamSession, type AudioSpec, type VideoSpec } from "./stream.ts";
10
+ /** A receiver on the network. */
11
+ export interface Device {
12
+ name: string;
13
+ /** e.g. `AppleTV14,1`, `Chromecast`. */
14
+ model: string | undefined;
15
+ addresses: string[];
16
+ protocols: ("airplay" | "cast")[];
17
+ /** Whether it can show video (Cast video or AirPlay mirroring). */
18
+ video: boolean;
19
+ /** AirPlay: whether tvpipe has a pairing for it (`undefined`: not AirPlay). */
20
+ paired: boolean | undefined;
21
+ /** AirPlay: whether it asks for a PIN (pair it first). */
22
+ pin: boolean | undefined;
23
+ /** What `discover --json` says, camelCased. */
24
+ airplay: Record<string, unknown> | undefined;
25
+ raop: Record<string, unknown> | undefined;
26
+ cast: Record<string, unknown> | undefined;
27
+ }
28
+ export interface DiscoverOptions extends ProcessOptions {
29
+ /** How long to browse (ms, default 3000). */
30
+ timeout?: number | undefined;
31
+ /** Also browse from these local IPv4 addresses. */
32
+ interfaces?: string[] | undefined;
33
+ signal?: AbortSignal | undefined;
34
+ }
35
+ /** Receivers on the local network (AirPlay and Cast, merged per device). */
36
+ export declare function discover(options?: DiscoverOptions): Promise<Device[]>;
37
+ /** What `onPin` gets: the receiver that shows the PIN. */
38
+ export interface PinRequest {
39
+ name: string;
40
+ address: string;
41
+ }
42
+ /** Asked for the PIN the TV shows; return it (or throw to cancel). */
43
+ export type PinCallback = (request: PinRequest) => string | Promise<string>;
44
+ export interface PairOptions extends ProcessOptions {
45
+ /** Asked for the PIN the TV shows. */
46
+ onPin?: PinCallback | undefined;
47
+ /** A receiver with a fixed PIN (no PIN on screen). */
48
+ pin?: string | undefined;
49
+ signal?: AbortSignal | undefined;
50
+ }
51
+ export interface PairResult {
52
+ name: string;
53
+ model: string | undefined;
54
+ /** The credentials file (the tvpipe command always has one). */
55
+ file: string | undefined;
56
+ }
57
+ /**
58
+ * Pairs with an AirPlay receiver (Apple TV): the TV shows a PIN, `onPin`
59
+ * returns it. The pairing is stored in tvpipe's config directory (shared
60
+ * with the CLI; see `configDir`).
61
+ */
62
+ export declare function pair(target: string | Device, options?: PairOptions): Promise<PairResult>;
63
+ /** Forgets the pairing with a receiver. Resolves with the names forgotten. */
64
+ export declare function unpair(target: string | Device, options?: ProcessOptions): Promise<string[]>;
65
+ /** A receiver: a name (`"Living Room"`, a unique prefix), `airplay:NAME`, `cast:NAME`, an address, `"browser"`, or a discovered device. */
66
+ export type Target = string | Device;
67
+ export interface PlayerOptions {
68
+ /** Port on 127.0.0.1 (default 0: any free port; the CLI's stable one is 8765). */
69
+ port?: number | undefined;
70
+ /** Open the page in the default browser. */
71
+ open?: boolean | undefined;
72
+ /** Start streaming once a tab watches. */
73
+ waitForViewer?: boolean | undefined;
74
+ /** A new URL token (old URLs stop working). */
75
+ newToken?: boolean | undefined;
76
+ /**
77
+ * Also on a public https link for people elsewhere (`session.publicUrl`):
78
+ * `true` is Cloudflare, or name the provider. `play`/`preview`/`testPattern` only.
79
+ */
80
+ tunnel?: boolean | TunnelProvider | undefined;
81
+ /** With `tunnel`: new viewers get in for this many minutes only. */
82
+ tunnelTtl?: number | undefined;
83
+ }
84
+ export interface CommonOptions extends ProcessOptions, SessionOptions {
85
+ /**
86
+ * Where to stream. Omitted: the only receiver with video on the
87
+ * network (an error lists them when there are several).
88
+ */
89
+ to?: Target | Target[] | undefined;
90
+ /** Playout delay in ms, the same on every receiver (5–2000). */
91
+ latency?: number | undefined;
92
+ /** Output size limit. */
93
+ size?: string | {
94
+ width: number;
95
+ height: number;
96
+ } | undefined;
97
+ fps?: number | undefined;
98
+ /** Video bitrate in kbit/s. */
99
+ bitrate?: number | undefined;
100
+ /** `false`: video only. */
101
+ audio?: boolean | undefined;
102
+ /** Seconds a receiver that dropped out is reconnected (default 120, 0: off). */
103
+ reconnect?: number | undefined;
104
+ /** The `browser` receiver's page. */
105
+ player?: PlayerOptions | undefined;
106
+ /** Asked for an AirPlay PIN when a receiver needs pairing; the session then starts again. */
107
+ onPin?: PinCallback | undefined;
108
+ /** How long to look for a receiver when `to` is omitted (ms, default 3000). */
109
+ discoverTimeout?: number | undefined;
110
+ }
111
+ export type Encoder = "auto" | "builtin" | "x264" | "videotoolbox" | "nvenc" | "qsv" | "vaapi" | "mf";
112
+ export interface PlayOptions extends CommonOptions {
113
+ loop?: boolean | undefined;
114
+ /** Pace the input in real time (default: files yes, live sources no). */
115
+ realtime?: boolean | undefined;
116
+ encoder?: Encoder | undefined;
117
+ /** Path to ffmpeg (default: `$TVPIPE_FFMPEG`, then `PATH`). */
118
+ ffmpeg?: string | undefined;
119
+ }
120
+ /** A file path, a URL, or ffmpeg input arguments (capture devices). */
121
+ export type Input = string | URL | {
122
+ ffmpeg: string[];
123
+ };
124
+ /**
125
+ * Plays a file, URL or capture device. Resolves once streaming started;
126
+ * the session ends at the end of the input (`done`) or with `stop()`.
127
+ */
128
+ export declare function play(input: Input, options?: PlayOptions): Promise<Session>;
129
+ /** The built-in test pattern (a clock, a frame counter, a beep and flash every second); no ffmpeg needed. */
130
+ export declare function testPattern(options?: PlayOptions): Promise<Session>;
131
+ /**
132
+ * Plays to a browser tab on this computer (`to: "browser"` plus whatever
133
+ * `to` adds); `session.playerUrl` is the page. Without input: the test pattern.
134
+ */
135
+ export declare function preview(input?: Input, options?: PlayOptions): Promise<Session>;
136
+ export interface ShareOptions extends CommonOptions {
137
+ /** Open the share page (without URL) or the `browser` player page. */
138
+ open?: boolean | undefined;
139
+ /** With URL: show the browser window (e.g. to log in). */
140
+ visible?: boolean | undefined;
141
+ /** With URL: keep the browser profile (logins) in this directory. */
142
+ profile?: string | undefined;
143
+ /** With URL: reload the page every this many minutes. */
144
+ reload?: number | undefined;
145
+ /** With URL: the Chromium-based browser to run (default: `$TVPIPE_BROWSER`, Chrome, Edge, …). */
146
+ browser?: string | undefined;
147
+ /**
148
+ * Without URL: also put the share page on a public https link
149
+ * (`session.publicUrl`; resolves once it works): someone elsewhere can
150
+ * share their screen. `true` is Cloudflare, or name the provider.
151
+ */
152
+ tunnel?: boolean | TunnelProvider | undefined;
153
+ /** With `tunnel`: the link lets people in for this many minutes (default 60, 0: no limit). */
154
+ tunnelTtl?: number | undefined;
155
+ /**
156
+ * With `tunnel`: show remote shares without asking. Required for them to
157
+ * show at all: tvpipe asks on a terminal, which an SDK session has not.
158
+ */
159
+ yes?: boolean | undefined;
160
+ }
161
+ /**
162
+ * Shares a web page (rendered by a headless Chromium of tvpipe's own) or,
163
+ * without URL, whatever a person picks on the share page
164
+ * (`session.shareUrl`; resolves once that page listens).
165
+ */
166
+ export declare function share(url: string | URL, options: ShareOptions): Promise<Session>;
167
+ export declare function share(options: ShareOptions): Promise<Session>;
168
+ export interface StreamOptions extends Omit<CommonOptions, "audio"> {
169
+ video: VideoSpec;
170
+ audio?: AudioSpec | undefined;
171
+ /**
172
+ * Raw frames: the encoder (default `builtin`: no ffmpeg, keyframes on
173
+ * demand; `auto` and the others use ffmpeg).
174
+ */
175
+ encoder?: Encoder | undefined;
176
+ ffmpeg?: string | undefined;
177
+ /** Raw frames: drop while this many frames wait in the pipe (default 2). */
178
+ maxQueuedFrames?: number | undefined;
179
+ }
180
+ /**
181
+ * Streams frames the program makes: raw pixels (`writeVideo`, a canvas),
182
+ * PCM (`writeAudio`), or H.264 (`writeH264`, WebCodecs `writeChunk`).
183
+ * Resolves once the receivers are connected; write from then on.
184
+ */
185
+ export declare function stream(options: StreamOptions): Promise<StreamSession>;
186
+ /** The binary's version (`tvpipe --version`). */
187
+ export declare function version(options?: BinaryOptions): Promise<string>;
188
+ export type { StartedEvent };
189
+ //# sourceMappingURL=api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAiB,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAEhE,OAAO,KAAK,EAA2B,YAAY,EAAE,cAAc,EAAe,MAAM,aAAa,CAAC;AACtG,OAAO,EAAiB,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAClE,OAAO,EAAE,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,KAAK,SAAS,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;AAK5E,iCAAiC;AACjC,MAAM,WAAW,MAAM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