diff --git a/docs/.vitepress/nav.ts b/docs/.vitepress/nav.ts index 11ef9b641..fbe4320c0 100644 --- a/docs/.vitepress/nav.ts +++ b/docs/.vitepress/nav.ts @@ -4,7 +4,7 @@ import { PROJECT_VARS } from './versions' export const navbar: DefaultTheme.NavItem[] = [ { - text: 'Guide', + text: 'Docs', link: '/guide/', }, { @@ -15,6 +15,10 @@ export const navbar: DefaultTheme.NavItem[] = [ text: 'Tools', link: '/tools', }, + { + text: 'Client API Design', + link: '/guide/client-api-design', + }, { text: IS_NEXT ? PROJECT_VARS.VERSION_SNAPSHOT : PROJECT_VARS.VERSION, items: [ @@ -38,4 +42,4 @@ export const navbar: DefaultTheme.NavItem[] = [ } ] } -] \ No newline at end of file +] diff --git a/docs/.vitepress/sidebar.ts b/docs/.vitepress/sidebar.ts index ed67587c6..9d7b3d913 100644 --- a/docs/.vitepress/sidebar.ts +++ b/docs/.vitepress/sidebar.ts @@ -14,6 +14,7 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] { { text: 'What is webrtc-java?', link: '/introduction' }, { text: 'Getting Started', link: '/get-started' }, { text: 'Client API', link: '/client-api' }, + { text: 'Client API Design', link: '/client-api-design' }, ], }, { diff --git a/docs/.vitepress/theme/DocsHome.vue b/docs/.vitepress/theme/DocsHome.vue new file mode 100644 index 000000000..bffd1c9a9 --- /dev/null +++ b/docs/.vitepress/theme/DocsHome.vue @@ -0,0 +1,130 @@ + + + diff --git a/docs/.vitepress/theme/DocsIcon.vue b/docs/.vitepress/theme/DocsIcon.vue new file mode 100644 index 000000000..df544d8d8 --- /dev/null +++ b/docs/.vitepress/theme/DocsIcon.vue @@ -0,0 +1,27 @@ + + + diff --git a/docs/.vitepress/theme/ThreadingDiagram.vue b/docs/.vitepress/theme/ThreadingDiagram.vue new file mode 100644 index 000000000..f63ae380d --- /dev/null +++ b/docs/.vitepress/theme/ThreadingDiagram.vue @@ -0,0 +1,212 @@ + + + + + diff --git a/docs/.vitepress/theme/index.ts b/docs/.vitepress/theme/index.ts index cd4f91d14..35b96fe48 100644 --- a/docs/.vitepress/theme/index.ts +++ b/docs/.vitepress/theme/index.ts @@ -3,6 +3,8 @@ import { h } from 'vue' import type { Theme } from 'vitepress' import DefaultTheme from 'vitepress/theme' import NextBanner from './NextBanner.vue' +import DocsHome from './DocsHome.vue' +import ThreadingDiagram from './ThreadingDiagram.vue' import './style.css' export default { @@ -15,6 +17,7 @@ export default { }) }, enhanceApp({ app, router, siteData }) { - // ... + app.component('DocsHome', DocsHome) + app.component('ThreadingDiagram', ThreadingDiagram) } } satisfies Theme diff --git a/docs/.vitepress/theme/style.css b/docs/.vitepress/theme/style.css index 0851fe3e3..ed324dfc8 100644 --- a/docs/.vitepress/theme/style.css +++ b/docs/.vitepress/theme/style.css @@ -1,167 +1,601 @@ -/** - * Customize default theme styling by overriding CSS variables: - * https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css - */ - -/** - * Colors - * - * Each colors have exact same color scale system with 3 levels of solid - * colors with different brightness, and 1 soft color. - * - * - `XXX-1`: The most solid color used mainly for colored text. It must - * satisfy the contrast ratio against when used on top of `XXX-soft`. - * - * - `XXX-2`: The color used mainly for hover state of the button. - * - * - `XXX-3`: The color for solid background, such as bg color of the button. - * It must satisfy the contrast ratio with pure white (#ffffff) text on - * top of it. - * - * - `XXX-soft`: The color used for subtle background such as custom container - * or badges. It must satisfy the contrast ratio when putting `XXX-1` colors - * on top of it. - * - * The soft color must be semi transparent alpha channel. This is crucial - * because it allows adding multiple "soft" colors on top of each other - * to create an accent, such as when having inline code block inside - * custom containers. - * - * - `default`: The color used purely for subtle indication without any - * special meanings attached to it such as bg color for menu hover state. - * - * - `brand`: Used for primary brand colors, such as link text, button with - * brand theme, etc. - * - * - `tip`: Used to indicate useful information. The default theme uses the - * brand color for this by default. - * - * - `warning`: Used to indicate warning to the users. Used in custom - * container, badges, etc. - * - * - `danger`: Used to show error, or dangerous message to the users. Used - * in custom container, badges, etc. - * -------------------------------------------------------------------------- */ - +/* Shared documentation palette and responsive landing page. */ :root { - --vp-c-default-1: var(--vp-c-gray-1); - --vp-c-default-2: var(--vp-c-gray-2); - --vp-c-default-3: var(--vp-c-gray-3); - --vp-c-default-soft: var(--vp-c-gray-soft); - - --vp-c-brand-1: var(--vp-c-indigo-1); - --vp-c-brand-2: var(--vp-c-indigo-2); - --vp-c-brand-3: var(--vp-c-indigo-3); - --vp-c-brand-soft: var(--vp-c-indigo-soft); - - --vp-c-tip-1: var(--vp-c-brand-1); - --vp-c-tip-2: var(--vp-c-brand-2); - --vp-c-tip-3: var(--vp-c-brand-3); - --vp-c-tip-soft: var(--vp-c-brand-soft); - - --vp-c-warning-1: var(--vp-c-yellow-1); - --vp-c-warning-2: var(--vp-c-yellow-2); - --vp-c-warning-3: var(--vp-c-yellow-3); - --vp-c-warning-soft: var(--vp-c-yellow-soft); - - --vp-c-danger-1: var(--vp-c-red-1); - --vp-c-danger-2: var(--vp-c-red-2); - --vp-c-danger-3: var(--vp-c-red-3); - --vp-c-danger-soft: var(--vp-c-red-soft); + --vp-c-brand-1:#2457d6; + --vp-c-brand-2:#1c49be; + --vp-c-brand-3:#2457d6; + --vp-c-brand-soft:#2457d612; + --vp-c-bg:#fcfcfd; + --vp-c-bg-alt:#f5f6f8; + --vp-c-bg-soft:#f1f3f6; + --vp-c-text-1:#192333; + --vp-c-text-2:#596577; + --vp-c-divider:#e4e7ed; + --vp-sidebar-width:270px; + --vp-layout-max-width:1440px } -/** - * Component: Button - * -------------------------------------------------------------------------- */ - -:root { - --vp-button-brand-border: transparent; - --vp-button-brand-text: var(--vp-c-white); - --vp-button-brand-bg: var(--vp-c-brand-3); - --vp-button-brand-hover-border: transparent; - --vp-button-brand-hover-text: var(--vp-c-white); - --vp-button-brand-hover-bg: var(--vp-c-brand-2); - --vp-button-brand-active-border: transparent; - --vp-button-brand-active-text: var(--vp-c-white); - --vp-button-brand-active-bg: var(--vp-c-brand-1); +.dark { + --vp-c-brand-1:#8cafff; + --vp-c-brand-2:#a9c3ff; + --vp-c-brand-3:#3568e2; + --vp-c-brand-soft:#6c96ff1f; + --vp-c-bg:#141820; + --vp-c-bg-alt:#181e28; + --vp-c-bg-soft:#1e2632; + --vp-c-text-1:#e6ebf3; + --vp-c-text-2:#a1adbf; + --vp-c-divider:#2c3544 } -/** - * Component: Home - * -------------------------------------------------------------------------- */ - -:root { - --vp-home-hero-name-color: transparent; - --vp-home-hero-name-background: -webkit-linear-gradient( - 120deg, - #1d4ed8 30%, - #1e3a8a - ); - - --vp-home-hero-image-background-image: linear-gradient( - -45deg, - #60a5fa 50%, - #1d4ed8 50% - ); - --vp-home-hero-image-filter: blur(44px); +.VPNavBarTitle .title { + font-weight:750; + letter-spacing:-.6px } - -@media (min-width: 640px) { - :root { - --vp-home-hero-image-filter: blur(56px); - } +.VPNavBarTitle .logo { + width:25px; + height:25px } - -@media (min-width: 960px) { - :root { - --vp-home-hero-image-filter: blur(68px); - } +.VPDoc h1 { + letter-spacing:-1.3px +} +.vp-doc h2 { + letter-spacing:-.6px +} +.VPSidebarItem.level-0 { + padding-bottom:17px +} +.VPDoc .content-container { + max-width:760px!important } -/** - * Component: Home features - * -------------------------------------------------------------------------- */ - -.VPFeature .icon { - color: var(--vp-c-brand-1); - background-color: var(--vp-c-brand-soft); +.docs-home { + max-width:1200px; + margin:auto; + padding:0 42px; + font-size:14px +} +.docs-home a { + text-decoration:none +} +.dh-hero { + display:grid; + grid-template-columns:1fr 1.07fr; + gap:58px; + padding:80px 0 57px; + align-items:center +} +.dh-dot { + display:inline-block; + width:6px; + height:6px; + background:#34b27b; + border-radius:50%; + flex-shrink:0 +} +.dh-intro h1 { + font-size:clamp(44px,5.2vw,68px); + font-weight:740; + line-height:1.06; + letter-spacing:-2px; + margin:23px 0 +} +.dh-intro h1>span { + color:var(--vp-c-brand-1) +} +.dh-lead { + font-size:16px; + line-height:1.8; + max-width:380px; + color:var(--vp-c-text-2) +} +.dh-actions { + display:flex; + gap:22px; + align-items:center; + margin:29px 0 33px +} +.dh-primary { + background:#2457d6; + color:white; + padding:12px 19px; + border-radius:6px; + font-weight:600; + display:inline-flex; + align-items:center; + gap:23px; + box-shadow:0 3px 5px #2457d61a +} +.dh-primary:hover { + background:#1c49be +} +.dh-secondary { + font-weight:600; + font-size:13px; + display:inline-flex; + align-items:center; + gap:10px +} +.dh-secondary:hover,.dh-section-heading>a:hover { + color:var(--vp-c-brand-1) +} +.dh-platforms>span { + font-size:9px; + letter-spacing:1.3px; + color:var(--vp-c-text-2); + font-weight:600 +} +.dh-platforms>div { + margin-top:5px; + font-size:12px +} +.dh-platforms i { + font-style:normal; + color:#aab2c0; + margin:0 9px } -.VPFeature .icon svg { - width: 24px; - height: 24px; +.dh-code-area { + min-width:0; + padding-top:17px +} +.dh-code-window { + background:#171e2b; + color:#c4cfdf; + border:1px solid #303b4e; + border-radius:10px; + overflow:hidden; + box-shadow:0 20px 40px -20px #13213e55 +} +.dh-code-title { + height:43px; + padding:0 17px; + display:flex; + justify-content:space-between; + align-items:center; + background:#1e2736; + border-bottom:1px solid #30394a; + font-family:var(--vp-font-family-mono); + font-size:11px +} +.dh-code-title>span:first-child { + display:flex; + gap:6px +} +.dh-code-title i { + width:7px; + height:7px; + border-radius:50%; + background:#566173 +} +.dh-code-title i:first-child { + background:#c97773 +} +.dh-code-title i:nth-child(2) { + background:#c3a36c +} +.dh-code-title i:nth-child(3) { + background:#70a98c +} +.dh-file-type { + font-size:9px; + letter-spacing:1px; + color:#8291a7 +} +.dh-code-tabs { + display:flex; + gap:23px; + padding:0 20px; + border-bottom:1px solid #2c3545 +} +.dh-code-tabs button { + color:#91a0b4; + font-size:11px; + padding:13px 0 10px; + border-bottom:2px solid transparent +} +.dh-code-tabs button.active { + color:#dbe6ff; + border-bottom-color:#80a7ff +} +.dh-code { + font-family:var(--vp-font-family-mono); + font-size:10.8px; + line-height:1.85; + padding:23px 21px; + overflow-x:auto; + min-height:406px; + margin:0; + tab-size:4 +} +/* Subtle horizontal scrollbars for the dark code examples. */ +.dh-code { + scrollbar-width: thin; + scrollbar-color: #46546b transparent; +} +.dh-code::-webkit-scrollbar { + height: 5px; +} +.dh-code::-webkit-scrollbar-track { + background: transparent; +} +.dh-code::-webkit-scrollbar-thumb { + background: #46546b; + border-radius: 999px; +} +.dh-code::-webkit-scrollbar-thumb:hover { + background: #677b99; +} +.dh-code::-webkit-scrollbar-button { + display: none; + width: 0; + height: 0; +} +.dh-code code { + font:inherit +} +.dh-code .comment { + color:#8291a8 +} +.dh-code .keyword { + color:#c3a3ef +} +.dh-code .type { + color:#8db5f4 +} +.dh-code-footer { + padding:12px 16px; + border-top:1px solid #30394a; + font-size:9px; + display:flex; + justify-content:space-between; + gap:10px; + color:#a4b2c7 +} +.dh-code-footer .dh-dot { + height:5px; + width:5px; + margin-right:5px +} +.dh-code-footer a { + color:#a6c2ff +} +.dh-code-caption { + text-align:center; + color:var(--vp-c-text-2); + font-size:11px; + margin-top:16px +} +.dh-code-caption>span { + font-weight:600; + color:var(--vp-c-text-1); + margin-right:4px +} +.dh-maven { + display: flex; + flex-direction: column; +} +.dh-platform-select { + max-width: 100%; + padding: 5px 10px; + border: 1px solid #57667e; + border-radius: 4px; + background: #1e2736; + color: #dbe6ff; + font: inherit; + color-scheme: dark; +} +.dh-maven .dh-code { + min-height: 0; + padding-top: 16px; + padding-bottom: 16px; +} +.dh-copy-row { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 10px; + padding: 0 20px 18px; + font-size: 11px; +} +.dh-copy-row [role="status"] { + flex-basis: 100%; +} +.dh-copy { + border:1px solid #57667e; + padding:5px 12px; + border-radius:4px; + font:inherit } -.VPFeature.link { - transition: border-color 0.25s, transform 0.25s; +.dh-capabilities { + display:flex; + align-items:center; + justify-content:space-between; + gap:18px; + border-top:1px solid var(--vp-c-divider); + border-bottom:1px solid var(--vp-c-divider); + padding:22px 0; + font-size:11px; + color:var(--vp-c-text-2) +} +.dh-capabilities b { + font-size:11px; + margin-right:7px; + color:var(--vp-c-text-1) +} +.dh-capabilities>a { + color:var(--vp-c-brand-1); + font-weight:600 +} +.dh-capabilities>a>span { + margin-left:13px +} +.dh-section { + padding-top:61px +} +.dh-section-heading { + display:flex; + align-items:flex-end; + justify-content:space-between; + gap:20px; + margin-bottom:25px +} +.dh-eyebrow { + font-size:9px; + font-weight:650; + color:var(--vp-c-text-2); + letter-spacing:1.5px; + line-height:1.6 +} +.dh-section h2 { + font-weight:650; + font-size:27px; + line-height:1.3; + letter-spacing:-.9px; + margin-top:9px +} +.dh-section-heading>a,.dh-section-heading>span { + font-size:11px; + margin-bottom:4px +} +.dh-paths { + display:grid; + grid-template-columns:repeat(3,1fr); + gap:17px +} +.dh-path { + border:1px solid var(--vp-c-divider); + border-radius:8px; + padding:25px; + transition:border-color .15s,background .15s +} +.dh-path:hover { + border-color:var(--vp-c-brand-1); + background:var(--vp-c-brand-soft) +} +.dh-path-top { + display:flex; + justify-content:space-between; + align-items:center; + margin-bottom:25px +} +.dh-path-icon { + width:33px; + height:33px; + display:grid; + place-items:center; + color:var(--vp-c-brand-1); + background:var(--vp-c-brand-soft); + border:1px solid #7192df26; + border-radius:7px; + font-size:20px +} +.dh-path h3 { + font-size:18px; + font-weight:650; + letter-spacing:-.4px; + margin:8px 0 10px +} +.dh-path p { + font-size:14px; + line-height:1.8; + color:var(--vp-c-text-2) +} +.dh-path-action { + margin-top:26px; + color:var(--vp-c-brand-1); + font-size:14px; + font-weight:600; + display:flex; + justify-content:space-between +} +.dh-muted { + color:var(--vp-c-text-2) } -.VPFeature.link:hover { - transform: translateY(-2px); +.dh-topic-grid { + display:grid; + grid-template-columns:1fr 1fr; + border-top:1px solid var(--vp-c-divider) +} +.dh-topic-grid>a { + display:flex; + align-items:center; + gap:16px; + padding:22px 12px 22px 0; + border-bottom:1px solid var(--vp-c-divider) +} +.dh-topic-grid>a:nth-child(even) { + padding-left:26px +} +.dh-topic-grid>a:hover h3, +.dh-topic-grid>a:hover p, +.dh-topic-grid>a:hover .dh-topic-icon, +.dh-topic-grid>a:hover .dh-topic-arrow, +.dh-topic-grid>a:focus-visible h3, +.dh-topic-grid>a:focus-visible p, +.dh-topic-grid>a:focus-visible .dh-topic-icon, +.dh-topic-grid>a:focus-visible .dh-topic-arrow { + color:var(--vp-c-brand-1) +} +.dh-topic-icon { + font-size:23px; + color:var(--vp-c-text-2); + width:27px; + text-align:center +} +.dh-topic-grid h3 { + font-size:13px; + font-weight:600 +} +.dh-topic-grid p { + font-size:11px; + color:var(--vp-c-text-2); + margin-top:3px +} +.dh-topic-arrow { + margin-left:auto; + color:var(--vp-c-text-1) +} +.dh-footer { + margin-top:50px; + padding:22px 0 26px; + display:flex; + justify-content:space-between; + font-size:13px; + font-weight:600; + gap:20px +} +.dh-footer>div { + display:flex; + gap:22px +} +.docs-home a:focus-visible,.docs-home button:focus-visible { + outline:2px solid var(--vp-c-brand-1); + outline-offset:5px } -@media (prefers-reduced-motion: reduce) { - .VPFeature.link:hover { - transform: none; +@media(max-width:960px) { + .docs-home { + padding:0 28px + } + .dh-hero { + gap:30px; + padding-top:50px + } + .dh-intro h1 { + font-size:51px; + letter-spacing:-2.5px + } + .dh-code { + font-size:9px; + min-height:355px; + padding:20px 14px + } + .dh-actions { + gap:15px + } + .dh-secondary { + font-size:11px + } + .dh-capabilities { + flex-wrap:wrap; + justify-content:flex-start; + gap:18px 30px } + .dh-path { + padding:20px + } + } -/** - * Component: Custom Block - * -------------------------------------------------------------------------- */ +@media(max-width:700px) { + .docs-home { + padding:0 23px + } + .dh-hero { + grid-template-columns:1fr; + padding:40px 0 32px; + gap:25px + } + .dh-intro h1 { + font-size:58px + } + .dh-lead { + max-width:440px + } + .dh-code { + font-size:11px; + min-height:0 + } + .dh-code-footer { + flex-wrap:wrap + } + .dh-section { + padding-top:40px + } + .dh-section-heading { + align-items:flex-start; + flex-direction:column; + gap:12px + } + .dh-section h2 { + font-size:25px + } + .dh-paths { + grid-template-columns:1fr + } + .dh-path-top { + margin-bottom:18px + } + .dh-topic-grid { + grid-template-columns:1fr + } + .dh-topic-grid>a:nth-child(even) { + padding-left:0 + } + .dh-footer { + flex-direction:column + } -:root { - --vp-custom-block-tip-border: transparent; - --vp-custom-block-tip-text: var(--vp-c-text-1); - --vp-custom-block-tip-bg: var(--vp-c-brand-soft); - --vp-custom-block-tip-code-bg: var(--vp-c-brand-soft); } -/** - * Component: Algolia - * -------------------------------------------------------------------------- */ -.DocSearch { - --docsearch-primary-color: var(--vp-c-brand-1) !important; +/* One consistent Lucide stroke style for feature and navigation icons. */ +.dh-icon { + display: inline-block; + width: 16px; + height: 16px; + flex-shrink: 0; + vertical-align: middle; +} +.dh-path-icon .dh-icon, +.dh-topic-icon .dh-icon { + width: 22px; + height: 22px; +} +.dh-topic-icon { + display: flex; + align-items: center; + flex-shrink: 0; +} +.dh-section-heading > a, +.dh-capabilities > span, +.dh-capabilities > a, +.dh-code-footer > a, +.dh-footer a { + display: inline-flex; + align-items: center; + gap: 7px; +} +.dh-code-footer .dh-icon, +.dh-footer .dh-icon { + width: 12px; + height: 12px; } +.VPFooter .message, +.VPFooter .copyright { + font-size: 11px; + line-height: 20px; +} diff --git a/design/client-api.md b/docs/guide/client-api-design.md similarity index 63% rename from design/client-api.md rename to docs/guide/client-api-design.md index 15a7f1957..12e681c7b 100644 --- a/design/client-api.md +++ b/docs/guide/client-api-design.md @@ -1,7 +1,9 @@ -# webrtc-java Client API +# Client API Design -Status: phase 1 implemented on the `client-api` branch, based on `main` at 6cc938ab. See -[Implementation status](#implementation-status) for where the code differs from this design. +This page explains why the client API looks the way it does: the decisions behind it, its threading +model and what it guarantees. To use the API, start with the [Client API](/guide/client-api) guide; +the Javadoc is the reference. [Implementation](#implementation) tells how it is built and what is +still open. A high-level layer over the existing JNI API. It owns every native object, gives application code one thread per peer, negotiates on its own, and returns futures instead of nested observers. The @@ -10,11 +12,12 @@ low-level API stays as it is. - Package `dev.onvoid.webrtc.client`, in the existing `webrtc-java` jar, exported by the `webrtc.java` module. - Java 11, like the rest of the module: no records, no sealed types. -- Pure Java. Phase 1 needs no native or JNI changes and changes no existing signature. +- Plain Java over the existing classes, with a few native additions such as voice activity + detection. ## Decisions -These were open questions in the mockup. Each went with its recommendation. +The questions that shaped the API, and how they were decided. | Question | Decision | Consequence | |---|---|---| @@ -25,25 +28,24 @@ These were open questions in the mockup. Each went with its recommendation. | A camera opened twice? | Shared when the options match, `MediaException` when they differ. | One capture per device. Most platforms can't open a device with two capabilities anyway. | | Entry point name? | `WebRtc`. | `try (WebRtc rtc = WebRtc.create()) { ... }` | -## What hurts today +## What hurts on the core API -Each row comes from the current code, docs or examples on `main`. +Each row describes the core API, which stays as it is. | Problem | Where it shows | Answer | |---|---|---| | Observers run on WebRTC's own threads | `PeerConnectionObserver` is called on the signaling thread. A handler that blocks, or waits for work that needs that thread, stalls every connection of the factory. | Native callbacks only copy and enqueue. Handlers run on a per-peer event thread, where they may block or call `close()`. | | Threading rules differ per class | Data channel send results, DTLS and injector observers go through `JavaCallbackThread`. Peer connection observers don't. Frame sinks run on capture and decode threads. Custom audio has to be pushed from a single thread. | One rule for all control events. Frames get their own documented thread with a drop policy. Custom audio is serialized by the library. | -| Nested callbacks for offer and answer | `createOffer` → `CreateSessionDescriptionObserver` → `setLocalDescription` → `SetSessionDescriptionObserver`, with the error as a `String`. `WhepExample` uses three `CountDownLatch`es to flatten it. | `CompletableFuture` everywhere, failing with typed exceptions. In automatic mode the application never calls offer or answer. | +| Nested callbacks for offer and answer | `createOffer` → `CreateSessionDescriptionObserver` → `setLocalDescription` → `SetSessionDescriptionObserver`, with the error as a `String`. A WHEP client needs latches to flatten it. | `CompletableFuture` everywhere, failing with typed exceptions. In automatic mode the application never calls offer or answer. | | Signaling correctness is left to the app | Glare, rollback, candidates that arrive before the remote description (they fail silently with the plain `addIceCandidate`), and `onRenegotiationNeeded` firing mid-negotiation. | Built-in perfect negotiation with a polite/impolite role, candidate queuing, and a browser-compatible JSON message format. | | Manual disposal of query results | Every `RTCRtpSender`, `RTCRtpReceiver` and `RTCRtpTransceiver` returned to the app must be disposed, sources are not owned by tracks, and the factory has to outlive its connections. | No `dispose()` in the API. Everything is `AutoCloseable`, owned by its creator, and closed in the right order. | -| Receive-only needs a dummy track | `WhepExample` creates a `VideoDeviceSource` and a `VideoTrack` only to pass them to a `RECV_ONLY` transceiver. | `PeerOptions.receive(VIDEO, AUDIO)`. | +| Receive-only needs a dummy track | A WHEP client creates a `VideoDeviceSource` and a `VideoTrack` only to pass them to a `RECV_ONLY` transceiver. | `PeerOptions.receive(VIDEO, AUDIO)`. | | Audio input mode is found at run time | Mixing device and custom audio in one factory throws `IllegalStateException` on the first track of the other kind. | `AudioMode` is chosen when the runtime is built. The wrong call fails at once with a message naming the mode. | -| Device queries can block the caller | The guides say to query devices on worker threads, never on UI or render threads. | `Devices` is a snapshot kept current in the background, so reading it is instant on any thread. | +| Device queries can block the caller | The guides say to query devices on worker threads, never on UI or render threads. | `Devices` is a snapshot kept current in the background, so reading it is cheap on any thread. | ## Before and after -A video call over a WebSocket. Today the web example spreads this over `PeerConnectionManager` -(460 lines) and `MediaManager` (274 lines). This is the core of it, shortened: +A video call over a WebSocket on the core API, shortened: ```java PeerConnectionFactory factory = new PeerConnectionFactory(); @@ -126,37 +128,26 @@ try (WebRtc rtc = WebRtc.create()) { ## Threading model The model borrows from Netty's event loop: each peer has one event thread for application code, -and the library never runs application code on a thread WebRTC needs. - -```mermaid -sequenceDiagram - participant App as Your thread - participant Ops as Peer operation queue - participant RTC as WebRTC threads - participant Ev as Peer event thread - participant H as Your handlers - App->>Ops: peer.addTrack(camera), returns at once - Ops->>RTC: addTrack (proxy call, may block Ops) - RTC--)Ev: onRenegotiationNeeded (copied, enqueued) - Ev->>Ops: start offer (perfect negotiation) - Ops->>RTC: setLocalDescription() - RTC--)Ev: local offer set, onIceCandidate ... - Ev->>H: Signaling.send(offer), Signaling.send(candidate) - RTC--)Ev: onConnectionChange(CONNECTED) - Ev->>H: onStateChange(CONNECTED), whenConnected() completes - H->>Ops: peer.close() from a handler, fine -``` +and the library never runs application code on a thread WebRTC needs. A second serial executor per +peer, *control*, is the only place that calls the native connection. WebRTC's callbacks post to it, +and it hands on to the event executor what the application should hear. + + > **Invariant the implementation must keep:** nothing the library runs on a WebRTC thread ever -> waits for a Java thread. Native observers copy their arguments, enqueue, and return. That rules -> out the deadlock cycle no matter what a handler does. +> waits for a Java thread. Native observers copy their arguments, post them, and return, and neither +> executor of a peer waits for the other. That rules out the deadlock cycle no matter what a handler +> does. | Code | Runs on | May it block? | |---|---|---| -| Calls into the API | the caller's thread, any thread | They don't block. The only exceptions are `WebRtc.close()`, which waits up to `closeTimeout`, and a `join()` the caller writes. | +| Calls into the API | the caller's thread, any thread | They don't block, with these exceptions. `createPeer` waits for the connection, so that an invalid configuration fails there. The `LocalMedia` methods that make a track and `LocalTrack.setEnabled` wait briefly for a WebRTC thread, since the factory and the tracks are proxies. `camera()` and `screen()` also open their capture on the caller's thread. The first `devices()`, `screens()` and `windows()` ask the system there. `WebRtc.close()` waits up to `closeTimeout`, and a `join()` the caller writes waits as written. | | Event handlers, future callbacks, `Signaling.send` | the peer's event thread, or the configured `eventExecutor` | Yes, but it only delays that peer's events. It must not `join()` a future of this API: a direct `join()`/`get()` throws `BlockingCallException`. | -| Frame handlers (`onFrame`, `onAudio`) | one frame thread per subscription | Better not. A slow video handler gets the newest frame next, and the frames in between are dropped and released. | -| Native calls | internal operation threads | Not application code. Each operation has a timeout (default 30 s), so a stuck native call fails with a `TimeoutException` instead of hanging. | +| `LocalTrack.onEnded`, `LocalAudio.onVoiceActivity`, `Devices.onChange`, futures of local tracks and devices | the event thread of the runtime's local media, or the configured `eventExecutor` | Yes, but it delays the other events of local media. The rule against `join()` holds here too. | +| Frame handlers (`onFrame`, `onAudio`) | a thread of each subscription, from the frame pool | Better not. A slow video handler gets the newest frame next, and the frames in between are dropped and released. A slow audio handler loses the oldest audio beyond its buffer. | +| Encoded transforms | a thread of each sender and receiver | Better not. A slow transform delays its own frames. A frame it throws on is dropped, and the first such failure reaches `onError`. | +| Native calls | internal control threads | Not application code. Each operation has a timeout (default 30 s), so a stuck native call fails with a `TimeoutException` instead of hanging. The peer then brings signaling back to stable, and gives up if that fails too. | +| WHIP and WHEP requests | `java.net.http.HttpClient`, never the control pool | Not application code. A slow server holds up no peer. | | WebRTC callbacks | signaling, network and capture threads | Not application code. The library copies and enqueues only. | ### Guarantees @@ -170,8 +161,9 @@ sequenceDiagram ordering holds whatever executor is given. 4. **No lost events from registration races.** `onStateChange` is called with the current state first. `onTrack` and `onChannel` replay what already arrived. A data channel keeps the messages - that arrive before its first `onMessage` handler. A handler registered from within another - handler takes effect at once, so it also sees the events already queued behind that one. + that arrive before its first `onMessage` handler, up to `channelReceiveLimit`. A handler + registered from within another handler takes effect at once, so it also sees the events already + queued behind that one. 5. **Operations run in order.** Each peer runs its operations one at a time, like the W3C operations chain. `addTrack` followed by `createChannel` always negotiates both, in that order. 6. **Close is final and quiet.** After `close()` the only event is `onStateChange(CLOSED)`. Pending @@ -179,6 +171,8 @@ sequenceDiagram in native code. 7. **Handler exceptions are contained.** An exception thrown by a handler goes to the runtime's `errorHandler`. It never stops delivery and never crosses into native code. +8. **No future stays open forever.** A task that completes a future has a fallback for when its + executor rejects it, and a closing runtime fails every future still open. ## Ownership and lifecycle @@ -194,12 +188,19 @@ never handed out. | `Sender` | `peer.addTrack` | `sender.remove()`, or the peer | renegotiates in automatic mode. The track stays open. | | `DataChannel` | `peer.createChannel`, or the remote side | the application, or the peer | completes pending sends with `PeerClosedException` | | `RemoteTrack` | the peer | the peer, when the remote side removes it or the peer closes | calls `onEnded` and ends its frame subscriptions | +| `Whip.Session`, `Whep.Session` | `publish`, `play` | the application | deletes the resource on the server and closes the peer. Tracks stay open. | | `Subscription` | every `on…` method | the application, or the owner of the event | removes the handler | +A source passed to `LocalMedia.videoTrack` or `audioTrack` stays the caller's. It must outlive the +track, and `closeAsync()` of the track says when it may be closed. + +A runtime close that cannot close everything in time leaves the factory undisposed and fails +`closeAsync()`. It never frees what WebRTC's threads may still use. + ## API surface -Signatures only. Value types reuse the existing ones where they are plain data -(`RTCSessionDescription`, `RTCIceCandidate`, `VideoFrame`, `AudioOptions`, `VideoDevice`, +Signatures only, the Javadoc has the rest. Value types reuse the existing ones where they are plain +data (`RTCSessionDescription`, `RTCIceCandidate`, `VideoFrame`, `AudioOptions`, `VideoDevice`, `AudioDevice`, `DesktopSource`). ### `WebRtc`, the runtime @@ -216,6 +217,8 @@ public final class WebRtc implements AutoCloseable { public Peer createPeer(PeerOptions options); public LocalMedia media(); // cameras, microphones, screens, custom sources public List peers(); // snapshot of the open peers + public AudioMode audioMode(); + public LoadStats loadStats(); // how much work waits and runs, cheap enough to read every second public CompletableFuture closeAsync(); @Override @@ -227,6 +230,9 @@ public final class WebRtc implements AutoCloseable { public Builder hardwareVideoCodecs(boolean enabled); // GPU encoders and decoders where present public Builder fieldTrials(Map fieldTrials); public Builder eventExecutor(Executor executor); // e.g. SwingUtilities::invokeLater, Platform::runLater + public Builder eventThreads(int limit); // unlimited by default + public Builder frameThreads(int limit); // unlimited by default + public Builder audioBuffer(Duration buffer); // default 5 s, what onAudio keeps for a slow handler public Builder errorHandler(Consumer handler); // handler exceptions, failures nobody observed public Builder operationTimeout(Duration timeout); // default 30 s public Builder closeTimeout(Duration timeout); // default 10 s @@ -245,8 +251,34 @@ public enum AudioMode { - `AudioMode` moves the factory's device-or-custom rule to build time. `media().microphone()` on a `CUSTOM` runtime throws `ConfigurationException` saying why. - `HEADLESS` uses `HeadlessAudioDeviceModule`, so servers and bots run without audio hardware. -- Library threads are daemon threads named after their peer (`webrtc-client-events-alice`), so - thread dumps show which peer is busy. +- Library threads are daemon threads. On the runtime's own event pool a thread takes the name of + the peer it works for (`webrtc-client-events-alice`), so thread dumps show which peer is busy. +- By default each peer and each subscription with work waiting gets a thread. `eventThreads` and + `frameThreads` cap them for applications with many peers: peers and subscriptions then take turns, + so a slow handler delays the others but never starves them. Events wait and are never dropped. + Media that waits is bounded by its subscription. The limits don't apply to an `eventExecutor` of + the application, and control threads are never limited, since their tasks wait for one another. + +```java +public final class LoadStats { + + public Work control(); // tasks of the library that call into WebRTC + public Work events(); // events of all peers + public Work video(); // frames for onFrame handlers + public Work audio(); // chunks for onAudio handlers + public int controlThreads(); + public int eventThreads(); + public int frameThreads(); + + public static final class Work { + + public int queued(); + public Duration oldestWaiting(); + public int active(); + public long dropped(); // since the runtime started + } +} +``` ### `PeerOptions` @@ -264,6 +296,11 @@ public final class PeerOptions { public Builder polite(boolean polite); // perfect negotiation role, default false public Builder negotiation(Negotiation negotiation); // AUTOMATIC by default, or MANUAL public Builder receive(MediaKind... kinds); // receive-only audio and video + public Builder gatheringTimeout(Duration timeout); // the longest Gathering.COMPLETE waits, default 3 s + public Builder channelSendLimit(long bytes); // backlog of a data channel, default 16 MiB + public Builder channelReceiveLimit(long bytes); // unhandled messages of a data channel, default 16 MiB + public Builder sendTransform(RTCEncodedFrameTransformer transform); // every sender, from its first frame + public Builder receiveTransform(RTCEncodedFrameTransformer transform); // every receiver, from its first frame public Builder configure(Consumer customizer); // anything else RTCConfiguration has public PeerOptions build(); } @@ -326,6 +363,8 @@ public enum PeerState { NEW, CONNECTING, CONNECTED, DISCONNECTED, FAILED, CLOSED itself. `FAILED` needs `restartIce()` or a new peer. - `addTrack` returns the `Sender` handle right away. If the native call fails, the error goes to `onError` and the sender's futures fail. +- `addTrack` without stream ids puts every such track of a peer into one shared stream, so a browser + plays its audio and video in sync. - `close()` never blocks, so it is safe in a handler and on the Swing EDT. `closeAsync().join()` waits, from a thread that is not an event thread. - Objects obtained inside `withNative` are owned by the caller, as in the low-level API, and must @@ -344,8 +383,10 @@ public interface Signaling { void send(SignalMessage message); // Called once when the peer is created. A transport that receives messages - // can push them into inbound instead of calling peer.signal(...). - default void attach(Consumer inbound) { + // can push them into inbound instead of calling peer.signal(...). The peer + // closes the subscription when it closes, which must let go of inbound. + default Subscription attach(Consumer inbound) { + return () -> { }; } // Two linked ends, for tests and same-process demos. @@ -375,15 +416,17 @@ public final class SignalMessage { ```json {"type":"offer","sdp":"v=0\r\no=- 4611731400430051336 2 IN IP4 127.0.0.1\r\n..."} {"candidate":"candidate:842163049 1 udp 1677729535 203.0.113.7 49203 typ srflx raddr 0.0.0.0 rport 0 generation 0","sdpMid":"0","sdpMLineIndex":0} -{"candidate":"","sdpMid":"0","sdpMLineIndex":0} +{"candidate":""} ``` -- The last line is the browser's end-of-candidates form. It maps to `END_OF_CANDIDATES`. +- The last line is the end-of-candidates form. `fromJson` also takes the browser's variants, with + `sdpMid` and `sdpMLineIndex` set or with a null `candidate`. All map to `END_OF_CANDIDATES`. - Routing (rooms, sender and receiver ids) stays in the application's own envelope. The JSON is the payload inside it. -- Candidates that arrive before the remote description are queued and added once it is set. +- Candidates that arrive before the remote description are held and added once it is set, and the + operations behind them go on meanwhile. - The JSON codec is a small built-in one for these fixed shapes, so the module gains no - dependency. + dependency. It is strict and takes at most a MiB per message. ### `Negotiator`, manual mode @@ -396,8 +439,9 @@ public interface Negotiator { CompletableFuture createOffer(); // creates and applies the local offer CompletableFuture createOffer(Gathering gathering); // COMPLETE waits for all candidates CompletableFuture answer(RTCSessionDescription offer); + CompletableFuture answer(RTCSessionDescription offer, Gathering gathering); CompletableFuture applyAnswer(RTCSessionDescription answer); - CompletableFuture addCandidate(RTCIceCandidate candidate); // queued until the remote description is set + CompletableFuture addCandidate(RTCIceCandidate candidate); // held until the remote description is set } public enum Gathering { TRICKLE, COMPLETE } @@ -405,6 +449,10 @@ public enum Gathering { TRICKLE, COMPLETE } In manual mode a `Signaling`, if one is set, still receives the local candidates for trickle ICE. +`Gathering.COMPLETE` waits at most `gatheringTimeout`, since an unreachable STUN or TURN server holds +up the end of gathering far longer. A candidate the `addCandidate` future reported as held and WebRTC +later rejects goes to `onError`. + ### `LocalMedia`, `Devices`, local tracks ```java @@ -412,13 +460,15 @@ public interface LocalMedia { Devices devices(); - LocalVideo camera(); // default camera, default capability - LocalVideo camera(CameraOptions options); + LocalCamera camera(); // default camera, default capability + LocalCamera camera(CameraOptions options); LocalAudio microphone(); // AudioMode.DEVICES only LocalAudio microphone(AudioOptions options); // echo cancellation, noise suppression, gain control LocalVideo screen(ScreenOptions options); // a screen or a window from devices() CustomVideo customVideo(String label); CustomAudio customAudio(String label); // AudioMode.CUSTOM or HEADLESS + LocalVideo videoTrack(String label, VideoTrackSource source); // over a source of the core API + LocalAudio audioTrack(String label, AudioTrackSource source); // such as a MediaFileSource's } public interface Devices { @@ -440,18 +490,28 @@ public interface LocalTrack extends AutoCloseable { MediaKind kind(); boolean isEnabled(); void setEnabled(boolean enabled); // false sends black frames or silence, capture stays open - Subscription onEnded(Runnable handler); // device unplugged, window closed, track closed + Subscription onEnded(Runnable handler); // the track closed, see Open gaps + boolean isEnded(); + CompletableFuture closeAsync(); // completes once the native track is released @Override - void close(); // stops capture, detaches from every peer + void close(); // stops capture, detaches from every peer, never blocks } public interface LocalVideo extends LocalTrack { Subscription onFrame(Consumer handler); // local preview +} + +public interface LocalCamera extends LocalVideo { + + VideoDevice device(); CompletableFuture switchCamera(VideoDevice device); // peers keep sending, no renegotiation } public interface LocalAudio extends LocalTrack { + + Subscription onVoiceActivity(Consumer handler); // true when speech begins, false when it ends + Subscription onVoiceActivity(VoiceActivityConfig config, Consumer handler); } public interface CustomVideo extends LocalVideo { @@ -465,6 +525,13 @@ public interface CustomAudio extends LocalAudio { void push(byte[] pcm, PcmFormat format); // any length, any thread void queueLimit(Duration max, AudioOverflow overflow); // 10 s, REJECT by default + long queuedMillis(); + void clear(); +} + +public enum AudioOverflow { + REJECT, // refuse the push with an AudioQueueFullException + DROP_OLDEST // take the push and drop the oldest queued audio } ``` @@ -475,10 +542,10 @@ CameraOptions hd = CameraOptions.builder() .frameRate(30) .build(); // the camera's nearest supported capability is used -ScreenOptions screen = ScreenOptions.builder() - .source(rtc.media().devices().screens().get(0)) +ScreenOptions screen = ScreenOptions.screen(rtc.media().devices().screens().get(0)) .frameRate(15) - .build(); + .maxSize(1920, 1080) // scales down to fit, keeping the aspect ratio + .build(); // ScreenOptions.window(...) for a window ``` - One `LocalTrack` can be sent on any number of peers. The library keeps one source and one sender @@ -486,8 +553,20 @@ ScreenOptions screen = ScreenOptions.builder() - Opening a camera that is already open shares its capture when the options match, and fails with `MediaException` when they differ. The capture stops when the last track using it is closed. - `CustomAudio.push` takes any amount of PCM from any thread. The library cuts it into the 10 ms - chunks WebRTC wants and feeds them from one internal thread, which is the single-thread rule - `CustomAudioSource` has today. + chunks WebRTC wants and feeds them from one internal thread, which is the single-thread rule of + `CustomAudioSource`. `PcmFormat.of` refuses what WebRTC cannot send: it takes 1, 2, 4, 6 or 8 + channels, and rates that are multiples of 100 within the limits of `CustomAudioSource`. +- `LocalCamera` exists because only a camera can switch. A WebRTC track cannot change its source, so + a switch puts a new native track over the new camera behind the same `LocalCamera`, on every + sender. It opens the new camera first. When that fails, as with two sensors of one camera that + cannot stream at once, it closes the current one before opening the new one, and reopens the + current one if the new one fails too. +- The device lists are snapshots, read once by the first `devices()` call, on the caller's thread. + Where the system reports no device changes, as a Linux machine without PulseAudio, they are read on + each call instead. `screens()` and `windows()` always ask the system. A kind of device the system + cannot list comes back empty, and any other failed query throws `MediaException`, so that an empty + list means there are no such devices. +- `onVoiceActivity` analyzes the audio in native code, and only the changes reach Java. ### `Sender`, `RemoteTrack` @@ -497,6 +576,8 @@ public interface Sender { LocalTrack track(); CompletableFuture replaceTrack(LocalTrack track); // no renegotiation, null sends nothing CompletableFuture configure(Encoding encoding); // max bitrate, max frame rate, scale down, active + CompletableFuture transform(RTCEncodedFrameTransformer transform); // null sends frames unchanged + CompletableFuture generateKeyFrame(); CompletableFuture remove(); // renegotiates in AUTOMATIC mode CompletableFuture sendTones(String tones); // DTMF, audio senders only CompletableFuture sendTones(String tones, Duration duration, Duration gap); @@ -512,19 +593,24 @@ public interface RemoteTrack { boolean isAudio(); RemoteVideo asVideo(); // IllegalStateException for audio RemoteAudio asAudio(); + CompletableFuture transform(RTCEncodedFrameTransformer transform); + boolean isMuted(); Subscription onMute(Consumer handler); Subscription onEnded(Runnable handler); + boolean isEnded(); } public interface RemoteVideo extends RemoteTrack { Subscription onFrame(Consumer handler); // FrameDelivery.LATEST Subscription onFrame(FrameDelivery delivery, Consumer handler); // LATEST, or queue(n) + CompletableFuture requestKeyFrame(); } public interface RemoteAudio extends RemoteTrack { Subscription onAudio(Consumer handler); // 10 ms of PCM each, in order + Subscription onAudio(Duration buffer, Consumer handler); // a buffer of its own void setVolume(double volume); // playout gain, 0.0 to 10.0 } ``` @@ -535,8 +621,13 @@ Encoding.builder().maxBitrate(1_500_000).maxFrameRate(30).scaleDownBy(1.0).build - A frame passed to `onFrame` is valid while the handler runs, as today. `frame.retain()` keeps it longer. The library releases the frames it drops. -- Each frame subscription has its own thread, so a slow renderer never holds up WebRTC's decoder - or the peer's events. +- Each frame subscription has its own serial executor over the frame pool, so a slow renderer never + holds up WebRTC's decoder or the peer's events. +- DTMF is part of `Sender` rather than an object of its own. The `sendTones` future completes once + the tones have been sent, and fails a few seconds after their planned end if WebRTC stopped midway. +- Transforms see every encoded frame, after the encoder or before the decoder, as end-to-end + encryption needs. `PeerOptions` sets them before the first frame. A first transform set on a video + sender that already sends restarts its encoder, which costs a key frame. ### `DataChannel` @@ -564,6 +655,7 @@ public final class Message { public boolean isText(); public String text(); // UTF-8 public byte[] bytes(); // a copy you own + public int size(); } ``` @@ -571,9 +663,13 @@ public final class Message { ChannelOptions.builder().ordered(false).maxRetransmits(0).protocol("json").negotiatedId(3).build(); ``` -- `send` completes when the message reaches the transport. Above a high-water mark (1 MiB by - default) the library holds sends in Java, so a loop of `send(chunk).join()` slows down by itself - instead of filling native memory. +- `send` completes when the message reaches the transport. Above a high-water mark of 1 MiB the + library holds sends in Java, so a loop of `send(chunk).join()` slows down by itself instead of + filling native memory. A send that would take the backlog beyond `channelSendLimit` fails at once + with `ChannelFullException`. +- WebRTC cannot be told to stop receiving, so a channel whose handlers fall behind by more than + `channelReceiveLimit`, counted before messages are queued, closes, and `onError` hears why. That + beats filling memory or dropping messages unnoticed. - The buffer that `RTCDataChannelObserver.onMessage` passes is copied into `Message`. Nothing a handler gets refers to native memory. @@ -586,19 +682,86 @@ samples, so `onStats` fills them from its second call on. public final class PeerStats { public Instant timestamp(); + public TransportStats transport(); // the one in use, null while there is none + public List transports(); public String candidateType(); // host, srflx, prflx, relay public Duration roundTripTime(); public long bytesSent(); public long bytesReceived(); public long outgoingBitrate(); // bits per second since the previous sample public long incomingBitrate(); - public double packetLoss(); // inbound, 0.0 to 1.0 - public List outboundVideo();// width, height, framesPerSecond, codec, qualityLimitation + public double packetLoss(); // inbound so far, 0.0 to 1.0 + public double recentPacketLoss(); // since the previous sample, -1 without one + public List outboundVideo();// trackId, width, height, framesPerSecond, codec, qualityLimitation public List inboundVideo(); public RTCStatsReport report(); // everything else } ``` +### `Whip` and `Whep` + +Sessions with a media server, over a peer with `Negotiation.MANUAL`. Their requests follow RFC 9725 +(WHIP) and draft-ietf-wish-whep-05 (WHEP), and the future completes once the peer is connected. + +```java +public final class Whip { + + public static Builder to(URI endpoint); // https, or http on this machine + + public static final class Builder { + public Builder track(LocalTrack track); + public Builder bearerToken(String token); + public Builder basicAuth(String user, String password); + public Builder videoCodecs(String... names); + public Builder audioCodecs(String... names); + public Builder alwaysOfferVideo(); + public Builder simulcast(); + public Builder simulcast(Encoding... layers); + public Builder iceServer(String... urls); // in place of those the endpoint names + public Builder turnServer(String url, String username, String password); + public Builder gathering(Gathering gathering); + public Builder timeout(Duration timeout); + public Builder sendTransform(RTCEncodedFrameTransformer transform); + public CompletableFuture publish(WebRtc rtc); + } +} + +public final class Whep { + + public static Builder from(URI endpoint); // https, or http on this machine + + public static final class Builder { + public Builder bearerToken(String token); + public Builder basicAuth(String user, String password); + public Builder videoCodecs(String... names); + public Builder audioCodecs(String... names); + public Builder iceServer(String... urls); + public Builder receive(MediaKind... kinds); // video and audio by default + public Builder turnServer(String url, String username, String password); + public Builder gathering(Gathering gathering); + public Builder timeout(Duration timeout); + public Builder receiveTransform(RTCEncodedFrameTransformer transform); + public CompletableFuture detect(WebRtc rtc); // does the endpoint serve WHEP? + public CompletableFuture play(WebRtc rtc); + } +} + +// Whip.Session and Whep.Session both have: +public Peer peer(); +public URI resource(); // the session URL from Location +public Map extensions(); +public CompletableFuture restartIce(); +public CompletableFuture closeAsync(); +public void close(); // ends the session on the server, closes the peer +``` + +- The offer goes out at once, without candidates, and candidates follow by PATCH. The peer takes the + ICE servers the endpoint names unless the builder named its own. +- The session restarts ICE by itself when the connection breaks, or by `session.restartIce()`. +- Requests go through `java.net.http.HttpClient` and never run on the control pool. Each has a + deadline for all of it, and the session's timeout or a cancel aborts what is out. +- Failures with a status are `HttpStatusException`s, with the problem details the server sent. + ### `Subscription` and errors ```java @@ -613,13 +776,17 @@ public class PeerClosedException extends WebRtcException { } // operation pe public class MediaException extends WebRtcException { } // device missing, busy, access denied, or opened with other options public class ConfigurationException extends WebRtcException { } // e.g. microphone() on an AudioMode.CUSTOM runtime public class BlockingCallException extends WebRtcException { } // join() or get() on an event thread +public class ChannelFullException extends WebRtcException { } // a send beyond channelSendLimit +public class AudioQueueFullException extends WebRtcException { } // a push beyond queueLimit, with AudioOverflow.REJECT +public class HttpStatusException extends WebRtcException { } // a WHIP or WHEP endpoint answered with an error ``` ## Scenarios ### Desktop app with Swing -With the EDT as the event executor, every handler can touch Swing components directly. +With the EDT as the event executor, every handler can touch Swing components directly. `VideoView` +comes from the `webrtc-java-swing` module, and `webrtc-java-javafx` has one for JavaFX. ```java WebRtc rtc = WebRtc.builder() @@ -666,10 +833,22 @@ peer.onChannel(channel -> { // channels the other side opens }); ``` -### WHEP playback, by hand +### WHEP playback -This replaces `WhepExample`'s three latches and dummy camera track. A `Whep.play(rtc, uri)` helper -would wrap the same steps (phase 2). +```java +Whep.Session session = Whep.from(URI.create("https://example.com/live/whep")) + .play(rtc) + .get(15, TimeUnit.SECONDS); + +session.peer().onTrack(track -> log.info("Receiving {}", track.kind())); +... +session.close(); +``` + +### A server of your own, by hand + +For an exchange that is neither WHIP nor WHEP, `Negotiator` gives the same steps without latches or +dummy tracks. ```java Peer peer = rtc.createPeer(PeerOptions.builder() @@ -702,7 +881,7 @@ try (WebRtc rtc = WebRtc.builder().audio(AudioMode.HEADLESS).build()) { } ``` -## How it maps onto today's classes +## How it maps onto the core API Anything the client API doesn't cover stays reachable through `withNative` and `configureFactory`. @@ -718,110 +897,47 @@ Anything the client API doesn't cover stays reachable through `withNative` and | `Devices` | `MediaDevices`, refreshed on a background thread when `DeviceChangeListener` fires | | `DataChannel` | `RTCDataChannel`, `RTCDataChannelObserver`, `sendAsync` with `RTCDataChannelSendObserver` | | `PeerStats` | `getStats(RTCStatsCollectorCallback)`, `RTCStatsReport` | +| `Whip`, `Whep` | a peer with `Negotiation.MANUAL`, `java.net.http.HttpClient` | +| `transform` on senders and tracks | `RTCEncodedFrameTransformer` | -Testing: - -- Each guarantee in the threading section gets a test: a handler that closes its own peer, a - handler that sleeps five seconds while a second peer keeps exchanging data, `join()` on an event - thread, event order under a thread pool, glare between two impolite peers, and the whole suite - under `-Pjni-check` for reference leaks. -- The examples and the get-started guide move to the new API once it lands. The low-level guides - stay for the advanced topics. +## Implementation -## Phases - -1. **Core:** `WebRtc`, `Peer` and the threading model; signaling, JSON and loopback; automatic and - manual negotiation; local media, devices and remote tracks; data channels, errors and stats. -2. **Helpers:** `Whip.publish` and `Whep.play`; `VideoView` for Swing; media files from - `webrtc-java-media` as a `LocalTrack`; recording a `Peer` with `MediaRecorder`. -3. **Adoption:** port the examples, rewrite the get-started guide, and mark the client package as - the recommended entry point. - -## Implementation status - -Phase 1 lives in `webrtc/src/main/java/dev/onvoid/webrtc/client/`, with tests in -`webrtc/src/test/java/dev/onvoid/webrtc/client/`. It changes no native code; the only change -outside the package is the `exports dev.onvoid.webrtc.client` line in `module-info.java`. +The package lives in `webrtc/src/main/java/dev/onvoid/webrtc/client/`, with tests in +`webrtc/src/test/java/dev/onvoid/webrtc/client/`. `module-info.java` exports it, and exports +`dev.onvoid.webrtc.client.internal` to the media module only: `EncodedFrames` hands `MediaRecorder` +the encoded frames of senders and remote tracks, taken on the peer's control executor. `VideoView` +lives in `webrtc-java-swing` (package `dev.onvoid.webrtc.client.swing`), so that the core module does +not need `java.desktop`, and in `webrtc-java-javafx` (`dev.onvoid.webrtc.client.javafx`), where +JavaFX is an optional dependency the application brings. How the threading model is built: -- Each peer has two `SerialExecutor`s over shared pools. The *control* executor owns the +- A runtime runs on a control pool, a frame pool, a timer, an audio pacer and the event executor, + which is its own pool or one the application passes. +- Each peer has two `SerialExecutor`s over those pools. The *control* executor owns the `RTCPeerConnection` and all negotiation state; every WebRTC callback only posts to it. The *event* executor runs application code and owns what the handlers have been told so far. -- Operations that the standard puts on the operations chain go through `PeerImpl.enqueue`, which - starts one only after the previous one finished and fails it after `operationTimeout`. +- `PeerImpl` holds the two together and leaves the rest to classes of their own: `OperationChain`, + `PerfectNegotiation`, `ManualNegotiation`, `NegotiationSteps`, `RemoteTracks`, `DataChannels`, + `StatsSampler` and `SignalingLink`. +- Operations that the standard puts on the operations chain go through `OperationChain.enqueue`, + which starts one only after the previous one finished and fails it after `operationTimeout`. - Native observer completions are posted back to the control executor before anything is chained on them, so no internal code ever runs on a WebRTC thread. - Public futures are `ClientFuture`s completed on the event executor. `join()`/`get()` on an unfinished one from any event thread throws `BlockingCallException`. Derived stages refuse too, through `newIncompleteFuture`. -- Frame and audio subscriptions each get a `SerialExecutor` over a frame pool, with the drop - policies described above. -- `CustomAudio` is cut into 10 ms chunks and pushed from the runtime's timer thread, every 10 ms. - -Where the code differs from the API above: - -- `camera()` returns a `LocalCamera`, a `LocalVideo` with `device()` and `switchCamera(device)`; - other video tracks cannot switch. A WebRTC track cannot change its source, so a switch puts a new - native track over the new camera behind the same `LocalCamera`, on every sender. It opens the new - camera first, and when that fails, as with two sensors of one camera that cannot stream at once, - closes the current one before opening the new one, and reopens the current one if the new one - fails too. `CameraIntegrationTest` covers it with a real camera and skips without one. -- DTMF is `Sender.sendTones()` and `Sender.onTone()` instead of a `DtmfSender` object; the future - completes once the tones have been sent. -- `Devices.screens()` and `windows()` ask the system on every call; only the camera, microphone and - speaker lists are snapshots. The first `devices()` call reads them once, synchronously. -- `Peer.addTrack` without stream ids puts every such track of a peer into one shared stream, so a - browser plays its audio and video in sync. -- Additions: `WebRtc.audioMode()`, `RemoteTrack.isMuted()`/`isEnded()`, `LocalTrack.isEnded()`, - `CustomAudio.queuedMillis()`/`clear()`, `Message.size()`, `Negotiator.answer(offer, gathering)`. +- Frame and audio subscriptions each get a `SerialExecutor` over the frame pool and a `Dispatcher` + with the drop policies described above. +- `CustomAudio` is cut into 10 ms chunks and pushed from the runtime's audio pacer, every 10 ms. - An impolite peer that ignored an offer reports the two-impolite-peers collision after 5 seconds without an answer. -- Received messages a data channel holds, waiting for its handlers or kept while it has none, are - capped by `PeerOptions.Builder.channelReceiveLimit` (16 MiB by default), counted before they are - queued; past that the channel closes and the peer's `onError` handlers hear why. -- `Gathering.COMPLETE` waits at most `PeerOptions.Builder.gatheringTimeout` (3 seconds by default), - since an unreachable STUN or TURN server holds up the end of gathering far longer. - -Covered by tests (`PeerTests`, `MediaTests`, `SignalMessageTests`): -- data channel round trip; -- early messages kept; -- 2000 messages in order, with no overlapping handler calls; -- a handler closing its own peer; -- `join()` on an event thread refused; -- a blocked handler not delaying another peer; -- collision resolved by the polite peer, and reported between two impolite ones; -- manual negotiation with complete gathering; -- pending work failing on close; -- runtime close; -- stats; -- subscriptions removed; -- pushed audio and video arriving; -- a slow frame handler not slowing the connection; -- a removed sender ending the remote track; -- a closed local track leaving every peer; -- sender configuration; -- audio mode checks. - -Every test also fails if anything reached the runtime's error handler, including while it closed. - -Next: -- a guide page and an example; -- `LocalMedia.videoTrack(label, source)` and `audioTrack(label, source)` wrap sources of the core - API, such as those of the media module's `MediaFileSource`, which stay the caller's. `MediaRecorder` - takes client API senders and remote tracks: `dev.onvoid.webrtc.client.internal.EncodedFrames`, - exported to the media module only, hands it their encoded frames, taken on the peer's control - executor, where key frame requests run too, and do nothing once the sender or receiver is gone. -- `VideoView` for JavaFX lives in the `webrtc-java-javafx` module, package - `dev.onvoid.webrtc.client.javafx`, compiled for Java 11 since OpenJFX is; JavaFX is an optional - dependency the application brings. `JavaFxCameraExample` in `webrtc-examples` uses it. -- `VideoView` for Swing lives in the `webrtc-java-swing` module, package - `dev.onvoid.webrtc.client.swing`, so that the core module does not need `java.desktop`. -- phase 2 is done: `Whip.to(...).publish(rtc)` and - `Whep.from(...).play(rtc)` return sessions over `java.net.http.HttpClient`, and `VideoView` is in - `dev.onvoid.webrtc.client.swing`; -- porting the existing examples (phases 2 and 3); `MediaFilePlayerExample` is ported, with a - Record button, and `LocalTrack.closeAsync()` came with it. `PeerConnectionExample`, - `DesktopVideoExample` and `MediaFileExample` are ported too, each over a loopback signaling. - `CodecListExample`, `EncryptedRecordingExample` and `VoiceActivityExample` stay on the core API, - which they demonstrate: the factory's codecs, encoded frame transforms and voice activity. + +### Open gaps + +- **A lost device does not end its track.** The first design had `LocalTrack.onEnded` fire when a + device is unplugged or a captured window closes. That was not built, and the Javadoc and the guide + say so. The code ends a local track only when it closes: by the + application, by the runtime, or when a camera switch fails and gets no camera back. After a loss, + `Devices.onChange` fires for a device, and the application has to close the track itself. Nothing + in the client API reports a captured window that closes. diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 8859fec78..5038d01c3 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -36,7 +36,7 @@ What the client API takes care of: - **Lifetime**: everything belongs to the runtime that created it and is closed with it. Senders, receivers and transceivers stay inside the library. - **Futures**: operations return `CompletableFuture`s that fail with typed exceptions, instead of taking observers. -The client API is plain Java on top of the classes the other guides describe, and it does not replace them. Its peers, tracks and channels are the same native objects, and [Using the Low-Level API](#using-the-low-level-api) shows how to reach them for anything it does not cover. +The client API is plain Java on top of the classes the other guides describe, and it does not replace them. Its peers, tracks and channels are the same native objects, and [Using the Low-Level API](#using-the-low-level-api) shows how to reach them for anything it does not cover. [Client API Design](/guide/client-api-design) explains the decisions behind it. ## The Runtime @@ -215,11 +215,11 @@ peer.whenClosed().thenRun(() -> System.out.println("Closed")); ## Threads -Every method of the client API may be called from any thread, including from inside a handler. None of them waits for a WebRTC thread: methods that change a peer return at once and take effect in the order they were called. +Every method of the client API may be called from any thread, including from inside a handler. Methods that change a peer return at once and take effect in the order they were called. | Code | Runs on | May it block? | |---|---|---| -| Your calls into the API | your thread | They don't block. The exceptions are `WebRtc.createPeer`, which waits briefly for the connection, and `WebRtc.close()`, which waits up to the close timeout. | +| Your calls into the API | your thread | They don't block, with these exceptions. `WebRtc.createPeer`, the `LocalMedia` methods that make a track and `LocalTrack.setEnabled` wait briefly for WebRTC. `camera()` and `screen()` also open their capture on your thread, which can take longer, so a UI thread should leave them to another thread. The first `media.devices()`, `screens()` and `windows()` ask the system on your thread. `WebRtc.close()` waits up to the close timeout. | | Peer, track and channel handlers, future callbacks, `Signaling.send` | the peer's event thread | Yes, but that delays only the events of this peer. They must not wait for a future of this API, see below. | | `onFrame` and `onAudio` handlers | a thread of each subscription | Better not. A slow video handler gets the newest frame next, and the frames in between are dropped; a slow audio handler loses the oldest audio beyond its buffer. | | [Encoded transforms](#encoded-transforms) | a thread of each sender and receiver | Better not. A slow transform delays only its own frames, and one that falls several seconds behind has frames dropped. | @@ -496,7 +496,7 @@ The new camera keeps the resolution and frame rate of the old one, as far as it ### Devices -`media.devices()` returns the cameras, microphones and speakers. The first call reads them from the system; after that, the lists are snapshots kept current in the background, so reading them is cheap on any thread. `screens()` and `windows()` ask the system on each call. A kind of device the system cannot list, such as audio devices on a machine without an audio system, comes back as an empty list; a query that fails otherwise throws a `MediaException`, so an empty list means there are no such devices. +`media.devices()` returns the cameras, microphones and speakers. The first call reads them from the system; after that, the lists are snapshots kept current in the background, so reading them is cheap on any thread. Where the system reports no device changes, as on a Linux machine without PulseAudio, they are read on each call instead. `screens()` and `windows()` ask the system on each call. A kind of device the system cannot list, such as audio devices on a machine without an audio system, comes back as an empty list; a query that fails otherwise throws a `MediaException`, so an empty list means there are no such devices. ```java Devices devices = media.devices(); @@ -508,6 +508,8 @@ devices.useSpeaker(devices.speakers().get(0)); `useMicrophone` and `useSpeaker` switch devices also for tracks that are sent or played now. A device that was disconnected since the list was read fails the returned future, and the device in use stays as it was. On Linux, where WebRTC's audio device module cannot tell devices apart, the default device is used whichever is given. +A track does not end by itself when its device is disconnected or a captured window closes. `LocalTrack.onEnded` follows only from closing the track, or from a camera switch that can open neither camera. `onChange` tells of a device that went away; closing the track, or switching a camera to another device, is up to you. Nothing tells of a captured window that closes. + ## Receiving Media `peer.onTrack` is called for every track the remote peer sends. Tracks that already arrived are handed to a handler added later. diff --git a/docs/index.md b/docs/index.md index 168fdb07c..b5b10a1f4 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,85 +1,6 @@ --- -layout: home - -hero: - name: "webrtc-java" - text: "Java native interface for WebRTC" - tagline: Build real‑time audio, video, and data with a clean Java API. - actions: - - theme: brand - text: Get Started - link: /guide/get-started - - theme: alt - text: What is webrtc-java? - link: /guide/introduction - - theme: alt - text: Sponsor this project - link: https://buymeacoffee.com/devopvoid - image: - src: /logo.png - alt: webrtc-java - -# Icons from Lucide (https://lucide.dev, ISC license). Keep the number of features a multiple -# of three, so that the default theme lays them out in full rows of three. -features: - - icon: - title: Cross-platform, Native Speed - details: One Java API on Windows, macOS and Linux, with prebuilt native libraries. A thin JNI layer keeps the overhead between Java and native code minimal. - link: /guide/introduction - linkText: Introduction - - icon: - title: Audio and Video Streaming - details: Capture audio and video from microphones and cameras, or feed your own media sources into a call. - link: /guide/media/media-devices - linkText: Media devices - - icon: - title: Screen Sharing - details: Share application windows or the full desktop with minimal setup, and send them like any other video stream. - link: /guide/video/desktop-capture - linkText: Desktop capture - - icon: - title: Data Channels - details: Reliable or unreliable, ordered or unordered SCTP data channels for messaging, file transfer and app signaling. - link: /guide/data/data-channels - linkText: Data channels - - icon: - title: Hardware Video Codecs - details: Encode and decode H.264, H.265, VP9 and AV1 on the GPU through NVENC and NVDEC, Media Foundation, VA-API and VideoToolbox, with fallback to software. - link: /guide/advanced/video-codecs#hardware-encoding - linkText: Hardware codecs - - icon: - title: Custom Video Codecs - details: Plug video encoders and decoders written in Java into WebRTC, to bring in a codec of your own or a hardware encoder from another library. - link: /guide/advanced/video-codecs#adding-a-codec - linkText: Video codecs - - icon: - title: Video Processing - details: Change, replace or drop each camera or desktop frame before it is sent, for background blur, overlays, mirroring or hiding part of the screen. - link: /guide/video/camera-capture#changing-frames-before-they-are-sent - linkText: Processing frames - - icon: - title: End-to-End Encryption - details: Encoded transforms let Java code read, change or drop every encoded frame, like insertable streams in the browser, for encryption, metadata and analysis. - link: /guide/advanced/encoded-transforms - linkText: Encoded transforms - - icon: - title: Send Pre-encoded Media - details: Send frames that are already encoded, such as an IP camera's H.264 stream or a recording, without encoding them again in WebRTC. - link: /guide/advanced/encoded-transforms#injecting-encoded-frames - linkText: Injecting frames - - icon: - title: Media File Playback - details: Play video and audio files or RTSP streams into a peer connection. The optional media module decodes with FFmpeg and keeps audio and video in sync. - link: /guide/media/media-files - linkText: Media files - - icon: - title: Call Recording - details: Record what a peer connection sends or receives into MKV, WebM or MP4 files, without re-encoding, at next to no CPU cost and in the exact quality of the call. - link: /guide/media/media-recording - linkText: Recording - - icon: - title: Statistics and Monitoring - details: Read WebRTC stats such as bitrate, packet loss, jitter, round-trip time and frame rate to monitor and tune media quality. - link: /guide/monitoring/rtc-stats - linkText: Statistics +layout: page +title: Real-time. Native. Made for Java. --- + + diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/LocalMedia.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/LocalMedia.java index 5bbf2b4b5..c2789235e 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/LocalMedia.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/LocalMedia.java @@ -24,6 +24,11 @@ /** * Creates the tracks a runtime sends, from {@link WebRtc#media()}. Every track * belongs to the runtime and is closed with it, unless it was closed before. + *

+ * The methods that make a track work on the calling thread and wait briefly + * for a WebRTC thread. {@link #camera()} and {@link #screen(ScreenOptions)} + * also open their capture there, which can take longer, so a UI thread should + * leave them to another thread. */ public interface LocalMedia { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/LocalTrack.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/LocalTrack.java index 14d40ea52..0c0938a24 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/LocalTrack.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/LocalTrack.java @@ -41,7 +41,7 @@ public interface LocalTrack extends AutoCloseable { /** * Mutes or unmutes the track. A muted track sends black frames or silence, - * while its capture stays open. + * while its capture stays open. Waits briefly for a WebRTC thread. * * @param enabled false to mute. */ @@ -50,6 +50,12 @@ public interface LocalTrack extends AutoCloseable { /** * Calls the handler once the track ended and its native track is * released. A handler added after that is called at once. + *

+ * A track ends when it is closed, by the application or with its runtime, + * or when a camera switch can open neither camera. It does not end by + * itself when its device is disconnected or a captured window closes: + * {@link Devices#onChange(java.util.function.Consumer)} tells of a device + * that went away, and closing the track is up to the application. * * @param handler called on an event thread of the runtime, where waiting * for a future of this API that is not done throws a diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java index 9d1450946..56b5317aa 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java @@ -74,8 +74,11 @@ * } * } *

Threads

- * Every method of this API may be called from any thread, and none waits for a - * WebRTC thread. The library never runs application code on a thread WebRTC + * Every method of this API may be called from any thread. Methods that change + * a peer return at once. {@link #createPeer}, the methods of {@link LocalMedia} + * that make a track and {@link LocalTrack#setEnabled(boolean)} wait briefly + * for a WebRTC thread, and {@link #close()} waits for everything to close. + * The library never runs application code on a thread WebRTC * needs: what WebRTC reports is copied and queued, then handed to the * application on the event thread of the peer it belongs to. The handlers of * one peer run one at a time and in order; those of different peers may run