├── .eslintignore ├── .eslintrc ├── .github └── workflows │ ├── node.yaml │ ├── playwright.yaml │ ├── publish_docs.yaml │ └── vitest.yaml ├── .gitignore ├── .gitmodules ├── .npmignore ├── .prettierrc ├── .tool-versions ├── LICENSE ├── README.md ├── dist.zip ├── e2e ├── app │ ├── .gitignore │ ├── README.md │ ├── compile_proto.sh │ ├── index.html │ ├── package-lock.json │ ├── package.json │ ├── src │ │ ├── App.tsx │ │ ├── MockComponent.tsx │ │ ├── VideoPlayer.tsx │ │ ├── VideoPlayerWithDetector.tsx │ │ ├── main.tsx │ │ ├── mocks.ts │ │ ├── protos │ │ │ └── jellyfish │ │ │ │ └── peer_notifications.ts │ │ └── vite-env.d.ts │ ├── tsconfig.json │ ├── tsconfig.node.json │ └── vite.config.ts ├── docker-compose-test.yaml ├── scenarios │ ├── basic.spec.ts │ ├── metadataParsing.spec.ts │ ├── raceCondition.spec.ts │ └── utils.ts └── setup │ ├── globalSetupState.ts │ ├── setupJellyfish.ts │ └── teardownJellyfish.ts ├── package-lock.json ├── package.json ├── playwright.config.ts ├── src ├── commands.ts ├── const.ts ├── deferred.ts ├── index.ts ├── mediaEvent.ts └── webRTCEndpoint.ts ├── test ├── events │ ├── bandwidthEstimationEvent.test.ts │ ├── connectedEvent.test.ts │ ├── encodingSwitchedEvent.test.ts │ ├── endpointAddedEvent.test.ts │ ├── endpointRemovedEvent.test.ts │ ├── endpointUpdatedEvent.test.ts │ ├── trackAddedEvent.test.ts │ ├── trackRemovedEvent.test.ts │ ├── trackUpdatedEvent.test.ts │ └── vadNotificationEvent.test.ts ├── fixtures.ts ├── methods │ ├── addTrackMethod.test.ts │ ├── cleanUpMethod.test.ts │ ├── connectMethod.test.ts │ └── disconnectMethod.test.ts ├── mocks.ts ├── schema.ts └── utils.ts ├── tsconfig.json └── vite.config.ts /.eslintignore: -------------------------------------------------------------------------------- 1 | dist 2 | tests/app/dist 3 | 4 | # Playwright 5 | test-results 6 | playwright-report 7 | blob-report 8 | playwright/.cache 9 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "plugins": ["@typescript-eslint", "react-refresh"], 5 | "extends": [ 6 | "eslint:recommended", 7 | "plugin:@typescript-eslint/eslint-recommended", 8 | "plugin:@typescript-eslint/recommended", 9 | "plugin:react-hooks/recommended", 10 | "prettier" 11 | ], 12 | "rules": { 13 | "@typescript-eslint/no-explicit-any": "off", 14 | "@typescript-eslint/ban-ts-comment": "off", 15 | "@typescript-eslint/no-unused-vars": [ 16 | "warn", 17 | { 18 | "argsIgnorePattern": "^_", 19 | "varsIgnorePattern": "^_", 20 | "caughtErrorsIgnorePattern": "^_" 21 | } 22 | ], 23 | "no-console": ["error", { "allow": ["warn", "error"] }], 24 | "react-refresh/only-export-components": ["warn", { "allowConstantExport": true }] 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.github/workflows/node.yaml: -------------------------------------------------------------------------------- 1 | name: Check Pull Request 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | jobs: 10 | check_and_build: 11 | name: Check formatting and run linter 12 | runs-on: ubuntu-latest 13 | 14 | strategy: 15 | matrix: 16 | node-version: [18.x] 17 | 18 | steps: 19 | - uses: actions/checkout@v4 20 | - name: Use Node.js ${{ matrix.node-version }} 🛎️ 21 | uses: actions/setup-node@v3 22 | with: 23 | node-version: ${{ matrix.node-version }} 24 | cache: "npm" 25 | 26 | - name: Install dependencies ⬇️ 27 | run: npm ci 28 | 29 | - name: Check formatting 🎨 30 | run: npm run format:check 31 | 32 | - name: Run linter 33 | run: npm run lint:check 34 | 35 | - name: Build 📦 36 | run: npm run build 37 | -------------------------------------------------------------------------------- /.github/workflows/playwright.yaml: -------------------------------------------------------------------------------- 1 | name: Playwright Tests 2 | on: 3 | push: 4 | branches: [main, master] 5 | pull_request: 6 | branches: [main, master] 7 | jobs: 8 | test: 9 | timeout-minutes: 60 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: actions/setup-node@v3 14 | with: 15 | node-version: 18 16 | - name: Install dependencies 17 | run: npm ci 18 | - name: Build SDK 19 | run: npm run build 20 | - name: Install test app dependencies 21 | run: npm ci 22 | working-directory: e2e/app 23 | - name: Install Playwright Browsers 24 | run: npx playwright install --with-deps 25 | - name: Run Playwright tests 26 | run: npm run e2e 27 | - uses: actions/upload-artifact@v3 28 | if: always() 29 | with: 30 | name: playwright-report 31 | path: playwright-report/ 32 | retention-days: 30 33 | -------------------------------------------------------------------------------- /.github/workflows/publish_docs.yaml: -------------------------------------------------------------------------------- 1 | name: Deploy Docs 2 | on: 3 | push: 4 | tags: 5 | - "v*" 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | - uses: actions/setup-node@v3 13 | with: 14 | # the same as in our docker_membrane repository 15 | node-version: "14.16.1" 16 | 17 | - name: Install npm Dependencies 18 | run: npm install 19 | 20 | - name: Build Docs 21 | run: npm run docs 22 | 23 | - name: Deploy 24 | uses: s0/git-publish-subdir-action@develop 25 | env: 26 | REPO: self 27 | BRANCH: gh-pages 28 | FOLDER: docs 29 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 30 | -------------------------------------------------------------------------------- /.github/workflows/vitest.yaml: -------------------------------------------------------------------------------- 1 | name: Unit Tests 2 | on: 3 | push: 4 | branches: [main, master] 5 | pull_request: 6 | branches: [main, master] 7 | jobs: 8 | test: 9 | timeout-minutes: 60 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: actions/setup-node@v3 14 | with: 15 | node-version: 18 16 | - name: Install dependencies 17 | run: npm ci 18 | - name: Build SDK 19 | run: npm run build 20 | - name: Run unit tests 21 | run: npm run test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | 3 | docs/ 4 | 5 | node_modules/ 6 | 7 | .idea 8 | *.iml 9 | 10 | # Playwright 11 | /test-results/ 12 | /playwright-report/ 13 | /blob-report/ 14 | /playwright/.cache/ 15 | /coverage 16 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "e2e/app/protos"] 2 | path = e2e/app/protos 3 | url = https://github.com/jellyfish-dev/protos 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .github/ 2 | 3 | docs/ 4 | 5 | node_modules/ 6 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 120 3 | } 4 | -------------------------------------------------------------------------------- /.tool-versions: -------------------------------------------------------------------------------- 1 | nodejs 18.14.2 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 2022 Software Mansion 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. 203 | 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > [!IMPORTANT] 2 | > This repository is now archived. 3 | > 4 | > All `membrane-webrtc-js` functionality is now available as part of [`ts-client-sdk`](https://github.com/jellyfish-dev/ts-client-sdk) 5 | 6 | # membrane-webrtc-js 7 | 8 | [![NPM version](https://img.shields.io/npm/v/@jellyfish-dev/membrane-webrtc-js)](https://www.npmjs.com/package/@jellyfish-dev/membrane-webrtc-js) 9 | 10 | Official JS/TS client library for [Membrane RTC Engine](https://github.com/jellyfish-dev/membrane_rtc_engine) 11 | 12 | ## Installation 13 | 14 | Using **npm**: 15 | 16 | ``` 17 | npm install @jellyfish-dev/membrane-webrtc-js 18 | ``` 19 | 20 | or 21 | 22 | ``` 23 | yarn add @jellyfish-dev/membrane-webrtc-js 24 | ``` 25 | 26 | Using **GitHub**: 27 | 28 | ``` 29 | npm install jellyfish-dev/membrane-webrtc-js# 30 | ``` 31 | 32 | ## e2e tests 33 | 34 | We use [Playwright](https://playwright.dev/) to run e2e tests. 35 | 36 | Use the `npm run e2e` command to run them. You may need to install the browsers using this command: `npx playwright install --with-deps`. 37 | 38 | The e2e tests start a Jellyfish instance via Docker and [Testcontainers](https://node.testcontainers.org/). 39 | 40 | ### Colima 41 | 42 | If you are using [colima](https://github.com/abiosoft/colima), you need to run these commands first: 43 | 44 | ```bash 45 | export DOCKER_HOST=unix://${HOME}/.colima/default/docker.sock 46 | export TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock 47 | ``` 48 | 49 | See the Testcontainers' documentation to learn about [known issues](https://node.testcontainers.org/supported-container-runtimes/#known-issues_1). 50 | 51 | ## Documentation 52 | 53 | Documentation is available [here](https://jellyfish-dev.github.io/membrane-webrtc-js/) 54 | 55 | ## Supported Membrane RTC Engine versions 56 | 57 | Below table presents mappings between JS SDK and RTC Engine versions that can be used together. 58 | 59 | | JS SDK | RTC Engine | 60 | | ------- | ---------- | 61 | | 0.1-0.2 | 0.2-0.7 | 62 | | 0.3.0 | 0.7-0.8 | 63 | | 0.4.0 | 0.9-0.13 | 64 | | 0.5.0 | 0.14+ | 65 | 66 | ## Copyright and License 67 | 68 | Copyright 2022, [Software Mansion](https://swmansion.com/?utm_source=git&utm_medium=readme&utm_campaign=membrane-webrtc-js) 69 | 70 | [![Software Mansion](https://logo.swmansion.com/logo?color=white&variant=desktop&width=200&tag=membrane-github)](https://swmansion.com/?utm_source=git&utm_medium=readme&utm_campaign=membrane_rtc_engine) 71 | 72 | Licensed under the [Apache License, Version 2.0](LICENSE) 73 | -------------------------------------------------------------------------------- /dist.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fishjam-dev/membrane-webrtc-js/83a97a598aae18b20ccfad21b47341d8438d361e/dist.zip -------------------------------------------------------------------------------- /e2e/app/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | /test-results/ 26 | /playwright-report/ 27 | /blob-report/ 28 | /playwright/.cache/ 29 | -------------------------------------------------------------------------------- /e2e/app/README.md: -------------------------------------------------------------------------------- 1 | # React + TypeScript + Vite 2 | 3 | This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. 4 | 5 | Currently, two official plugins are available: 6 | 7 | - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh 8 | - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh 9 | 10 | ## Expanding the ESLint configuration 11 | 12 | If you are developing a production application, we recommend updating the configuration to enable type aware lint rules: 13 | 14 | - Configure the top-level `parserOptions` property like this: 15 | 16 | ```js 17 | parserOptions: { 18 | ecmaVersion: 'latest', 19 | sourceType: 'module', 20 | project: ['./tsconfig.json', './tsconfig.node.json'], 21 | tsconfigRootDir: __dirname, 22 | }, 23 | ``` 24 | 25 | - Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked` 26 | - Optionally add `plugin:@typescript-eslint/stylistic-type-checked` 27 | - Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list 28 | -------------------------------------------------------------------------------- /e2e/app/compile_proto.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Terminate on errors 4 | set -e 5 | 6 | 7 | printf "Synchronising submodules... " 8 | git submodule sync --recursive >> /dev/null 9 | git submodule update --recursive --remote --init >> /dev/null 10 | printf "DONE\n\n" 11 | 12 | file="./protos/jellyfish/peer_notifications.proto" 13 | 14 | printf "Compiling: file %s\n" "$file" 15 | protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_out=./src/ $file 16 | printf "DONE\n" 17 | 18 | cd ../.. 19 | npm run format:fix 20 | npm run lint:fix 21 | -------------------------------------------------------------------------------- /e2e/app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite + React + TS 8 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /e2e/app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "tsc && vite build", 9 | "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", 10 | "preview": "vite preview" 11 | }, 12 | "dependencies": { 13 | "@jellyfish-dev/membrane-webrtc-js": "file:../..", 14 | "protobufjs": "^7.2.6", 15 | "react": "^18.2.0", 16 | "react-dom": "^18.2.0", 17 | "ts-proto": "^1.167.3" 18 | }, 19 | "devDependencies": { 20 | "@playwright/test": "^1.41.2", 21 | "@types/node": "^20.11.18", 22 | "@types/react": "^18.2.55", 23 | "@types/react-dom": "^18.2.19", 24 | "@typescript-eslint/eslint-plugin": "^7.0.1", 25 | "@typescript-eslint/parser": "^7.0.1", 26 | "@vitejs/plugin-react": "^4.2.1", 27 | "eslint": "^8.56.0", 28 | "eslint-plugin-react-hooks": "^4.6.0", 29 | "eslint-plugin-react-refresh": "^0.4.5", 30 | "typescript": "5.3.3", 31 | "vite": "^5.1.2" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /e2e/app/src/App.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | Endpoint, 3 | SerializedMediaEvent, 4 | TrackContext, 5 | TrackEncoding, 6 | WebRTCEndpoint, 7 | } from "@jellyfish-dev/membrane-webrtc-js"; 8 | import { PeerMessage } from "./protos/jellyfish/peer_notifications"; 9 | import { useEffect, useState, useSyncExternalStore } from "react"; 10 | import { MockComponent } from "./MockComponent.tsx"; 11 | import { VideoPlayerWithDetector } from "./VideoPlayerWithDetector.tsx"; 12 | import { 13 | WebRTCEndpointEvents, 14 | TrackContextEvents, 15 | BandwidthLimit, 16 | SimulcastConfig, 17 | } from "@jellyfish-dev/membrane-webrtc-js"; 18 | 19 | /* eslint-disable no-console */ 20 | 21 | export type EndpointMetadata = { 22 | goodStuff: string; 23 | }; 24 | 25 | export type TrackMetadata = { 26 | goodTrack: string; 27 | }; 28 | 29 | function endpointMetadataParser(a: any): EndpointMetadata { 30 | if (typeof a !== "object" || a === null || !("goodStuff" in a) || typeof a.goodStuff !== "string") 31 | throw "Invalid metadata!!!"; 32 | return { goodStuff: a.goodStuff }; 33 | } 34 | 35 | function trackMetadataParser(a: any): TrackMetadata { 36 | if (typeof a !== "object" || a === null || !("goodTrack" in a) || typeof a.goodTrack !== "string") 37 | throw "Invalid track metadata!!!"; 38 | return { goodTrack: a.goodTrack }; 39 | } 40 | 41 | class RemoteStore { 42 | cache: Record< 43 | string, 44 | [ 45 | Record>, 46 | Record>, 47 | ] 48 | > = {}; 49 | invalidateCache: boolean = false; 50 | 51 | constructor(private webrtc: WebRTCEndpoint) {} 52 | 53 | subscribe(callback: () => void) { 54 | const cb = () => { 55 | this.invalidateCache = true; 56 | callback(); 57 | }; 58 | 59 | const trackCb: TrackContextEvents["encodingChanged"] = () => cb(); 60 | 61 | const trackAddedCb: WebRTCEndpointEvents["trackAdded"] = (context) => { 62 | context.on("encodingChanged", () => trackCb); 63 | context.on("voiceActivityChanged", () => trackCb); 64 | 65 | callback(); 66 | }; 67 | 68 | const removeCb: WebRTCEndpointEvents["trackRemoved"] = (context) => { 69 | context.removeListener("encodingChanged", () => trackCb); 70 | context.removeListener("voiceActivityChanged", () => trackCb); 71 | 72 | callback(); 73 | }; 74 | 75 | this.webrtc.on("trackAdded", trackAddedCb); 76 | this.webrtc.on("trackReady", cb); 77 | this.webrtc.on("trackUpdated", cb); 78 | this.webrtc.on("trackRemoved", removeCb); 79 | this.webrtc.on("endpointAdded", cb); 80 | this.webrtc.on("endpointRemoved", cb); 81 | this.webrtc.on("endpointUpdated", cb); 82 | 83 | return () => { 84 | this.webrtc.removeListener("trackAdded", trackAddedCb); 85 | this.webrtc.removeListener("trackReady", cb); 86 | this.webrtc.removeListener("trackUpdated", cb); 87 | this.webrtc.removeListener("trackRemoved", removeCb); 88 | this.webrtc.removeListener("endpointAdded", cb); 89 | this.webrtc.removeListener("endpointRemoved", cb); 90 | this.webrtc.removeListener("endpointUpdated", cb); 91 | }; 92 | } 93 | 94 | snapshot() { 95 | const newTracks = webrtc.getRemoteTracks(); 96 | const newEndpoints = webrtc.getRemoteEndpoints(); 97 | const ids = Object.keys(newTracks).sort().join(":") + Object.keys(newEndpoints).sort().join(":"); 98 | if (!(ids in this.cache) || this.invalidateCache) { 99 | this.cache[ids] = [newEndpoints, newTracks]; 100 | this.invalidateCache = false; 101 | } 102 | return this.cache[ids]; 103 | } 104 | } 105 | 106 | // Assign a random client ID to make it easier to distinguish their messages 107 | const clientId = Math.floor(Math.random() * 100); 108 | 109 | const webrtc = new WebRTCEndpoint({ endpointMetadataParser, trackMetadataParser }); 110 | (window as typeof window & { webrtc: WebRTCEndpoint }).webrtc = webrtc; 111 | const remoteTracksStore = new RemoteStore(webrtc); 112 | 113 | function connect(token: string, metadata: EndpointMetadata) { 114 | const websocketUrl = "ws://localhost:5002/socket/peer/websocket"; 115 | const websocket = new WebSocket(websocketUrl); 116 | websocket.binaryType = "arraybuffer"; 117 | 118 | function socketOpenHandler(_event: Event) { 119 | const message = PeerMessage.encode({ authRequest: { token } }).finish(); 120 | websocket.send(message); 121 | } 122 | 123 | websocket.addEventListener("open", socketOpenHandler); 124 | 125 | webrtc.on("sendMediaEvent", (mediaEvent: SerializedMediaEvent) => { 126 | console.log(`%c(${clientId}) - Send: ${mediaEvent}`, "color:blue"); 127 | const message = PeerMessage.encode({ mediaEvent: { data: mediaEvent } }).finish(); 128 | websocket.send(message); 129 | }); 130 | 131 | const messageHandler = (event: MessageEvent) => { 132 | const uint8Array = new Uint8Array(event.data); 133 | try { 134 | const data = PeerMessage.decode(uint8Array); 135 | if (data?.mediaEvent) { 136 | // @ts-ignore 137 | const mediaEvent = JSON.parse(data?.mediaEvent?.data); 138 | console.log(`%c(${clientId}) - Received: ${JSON.stringify(mediaEvent)}`, "color:green"); 139 | } else { 140 | console.log(`%c(${clientId}) - Received: ${JSON.stringify(data)}`, "color:green"); 141 | } 142 | 143 | if (data.authenticated !== undefined) { 144 | webrtc.connect(metadata); 145 | } else if (data.authRequest !== undefined) { 146 | console.warn("Received unexpected control message: authRequest"); 147 | } else if (data.mediaEvent !== undefined) { 148 | webrtc.receiveMediaEvent(data.mediaEvent.data); 149 | } 150 | } catch (e) { 151 | console.warn(`Received invalid control message, error: ${e}`); 152 | } 153 | }; 154 | 155 | websocket.addEventListener("message", messageHandler); 156 | 157 | const closeHandler = (event: any) => { 158 | console.log({ name: "Close handler!", event }); 159 | }; 160 | 161 | websocket.addEventListener("close", closeHandler); 162 | 163 | const errorHandler = (event: any) => { 164 | console.log({ name: "Error handler!", event }); 165 | }; 166 | 167 | websocket.addEventListener("error", errorHandler); 168 | 169 | const trackReady = (event: any) => { 170 | console.log({ name: "trackReady", event }); 171 | }; 172 | 173 | websocket.addEventListener("trackReady", trackReady); 174 | } 175 | 176 | async function addScreenshareTrack(): Promise { 177 | const stream = await window.navigator.mediaDevices.getDisplayMedia(); 178 | const track = stream.getVideoTracks()[0]; 179 | 180 | const trackMetadata: TrackMetadata = { goodTrack: "screenshare" }; 181 | const simulcastConfig: SimulcastConfig = { enabled: false, activeEncodings: [], disabledEncodings: [] }; 182 | const maxBandwidth: BandwidthLimit = 0; 183 | 184 | return webrtc.addTrack(track, stream, trackMetadata, simulcastConfig, maxBandwidth); 185 | } 186 | 187 | export function App() { 188 | const [tokenInput, setTokenInput] = useState(localStorage.getItem("token") ?? ""); 189 | const [endpointMetadataInput, setEndpointMetadataInput] = useState(JSON.stringify({ goodStuff: "ye" })); 190 | const [connected, setConnected] = useState(false); 191 | 192 | useEffect(() => { 193 | localStorage.setItem("token", tokenInput); 194 | }, [tokenInput]); 195 | 196 | const handleConnect = () => 197 | connect(tokenInput, endpointMetadataInput !== "" ? JSON.parse(endpointMetadataInput) : undefined); 198 | const handleStartScreenshare = () => addScreenshareTrack(); 199 | const handleUpdateEndpointMetadata = () => webrtc.updateEndpointMetadata(JSON.parse(endpointMetadataInput)); 200 | 201 | const [remoteEndpoints, remoteTracks] = useSyncExternalStore( 202 | (callback) => remoteTracksStore.subscribe(callback), 203 | () => remoteTracksStore.snapshot(), 204 | ); 205 | 206 | const setEncoding = (trackId: string, encoding: TrackEncoding) => { 207 | webrtc.setTargetTrackEncoding(trackId, encoding); 208 | }; 209 | 210 | useEffect(() => { 211 | const callback = () => setConnected(true); 212 | 213 | webrtc.on("connected", callback); 214 | 215 | return () => { 216 | webrtc.removeListener("connected", callback); 217 | }; 218 | }, []); 219 | 220 | return ( 221 |
222 |
223 |
224 | setTokenInput(e.target.value)} placeholder="token" /> 225 | setEndpointMetadataInput(e.target.value)} 228 | placeholder="endpoint metadata" 229 | /> 230 | 231 | 232 | 233 |
234 |
{connected ? "true" : "false"}
235 |
236 | 237 |
238 | {Object.values(remoteTracks).map( 239 | ({ stream, trackId, endpoint, metadata, rawMetadata, metadataParsingError }) => ( 240 |
241 |
Endpoint id: {endpoint.id}
242 | Metadata: {JSON.stringify(metadata)} 243 |
244 | Raw: {JSON.stringify(rawMetadata)} 245 |
246 | Error: {metadataParsingError} 247 |
248 | 249 |
250 |
{stream?.id}
251 |
252 | 253 | 254 | 255 |
256 |
257 | ), 258 | )} 259 |
260 |
261 |
262 | Our metadata: 263 | setEndpointMetadataInput(e.target.value)}> 264 |
265 |
266 | Endpoints: 267 | {Object.values(remoteEndpoints).map(({ id, metadata, rawMetadata, metadataParsingError }) => ( 268 |
269 | {id} 270 | metadata: {JSON.stringify(metadata)} 271 |
272 | raw metadata: {JSON.stringify(rawMetadata)} 273 |
274 | metadata parsing error:{" "} 275 | 276 | {metadataParsingError?.toString?.() ?? metadataParsingError} 277 | 278 |
279 | ))} 280 |
281 |
282 |
283 | ); 284 | } 285 | -------------------------------------------------------------------------------- /e2e/app/src/MockComponent.tsx: -------------------------------------------------------------------------------- 1 | import { createStream } from "./mocks.ts"; 2 | import { WebRTCEndpoint } from "@jellyfish-dev/membrane-webrtc-js"; 3 | import { VideoPlayer } from "./VideoPlayer.tsx"; 4 | import { useRef, useState } from "react"; 5 | import { EndpointMetadata, TrackMetadata } from "./App.tsx"; 6 | import { BandwidthLimit, SimulcastConfig } from "@jellyfish-dev/membrane-webrtc-js"; 7 | 8 | const brainMock = createStream("🧠", "white", "low", 24); 9 | const brain2Mock = createStream("🤯", "#00ff00", "low", 24); 10 | const heartMock = createStream("🫀", "white", "low", 24); 11 | const heart2Mock = createStream("💝", "#FF0000", "low", 24); 12 | 13 | type Props = { 14 | webrtc: WebRTCEndpoint; 15 | }; 16 | 17 | export const MockComponent = ({ webrtc }: Props) => { 18 | const heartId = useRef | null>(null); 19 | const brainId = useRef | null>(null); 20 | const [replaceStatus, setReplaceStatus] = useState<"unknown" | "success" | "failure">("unknown"); 21 | const [trackMetadataInput, setTrackMetadataInput] = useState(JSON.stringify({ goodTrack: "ye" })); 22 | 23 | const addHeart = async () => { 24 | const stream = heartMock.stream; 25 | const track = stream.getVideoTracks()[0]; 26 | 27 | heartId.current = webrtc.addTrack(track, stream, JSON.parse(trackMetadataInput)); 28 | }; 29 | 30 | const removeHeart = async () => { 31 | if (!heartId.current) throw Error("Heart id is undefined"); 32 | 33 | webrtc.removeTrack(await heartId.current); 34 | }; 35 | 36 | const removeBrain = async () => { 37 | if (!brainId.current) throw Error("Brain id is undefined"); 38 | 39 | webrtc.removeTrack(await brainId.current); 40 | }; 41 | 42 | const replaceHeart = async () => { 43 | if (!heartId.current) throw Error("Track Id is not set"); 44 | 45 | const stream = heart2Mock.stream; 46 | const track = stream.getVideoTracks()[0]; 47 | 48 | await webrtc.replaceTrack(await heartId.current, track, JSON.parse(trackMetadataInput)); 49 | setReplaceStatus("success"); 50 | }; 51 | 52 | const replaceBrain = async () => { 53 | if (!brainId.current) throw Error("Track Id is not set"); 54 | 55 | const stream = brain2Mock.stream; 56 | const track = stream.getVideoTracks()[0]; 57 | 58 | await webrtc.replaceTrack(await brainId.current, track, JSON.parse(trackMetadataInput)); 59 | }; 60 | 61 | const addBrain = () => { 62 | const stream = brainMock.stream; 63 | const track = stream.getVideoTracks()[0]; 64 | 65 | const simulcastConfig: SimulcastConfig = { enabled: false, activeEncodings: [], disabledEncodings: [] }; 66 | const maxBandwidth: BandwidthLimit = 0; 67 | 68 | brainId.current = webrtc.addTrack(track, stream, JSON.parse(trackMetadataInput), simulcastConfig, maxBandwidth); 69 | }; 70 | 71 | const addBoth = () => { 72 | addHeart(); 73 | addBrain(); 74 | }; 75 | 76 | const addAndReplaceHeart = () => { 77 | addHeart(); 78 | replaceHeart(); 79 | }; 80 | 81 | const addAndRemoveHeart = () => { 82 | addHeart(); 83 | removeHeart(); 84 | }; 85 | 86 | const updateMetadataOnLastTrack = async () => { 87 | const awaitedHeartId = await heartId.current; 88 | if (!awaitedHeartId) return; 89 | webrtc.updateTrackMetadata(awaitedHeartId, JSON.parse(trackMetadataInput)); 90 | }; 91 | 92 | return ( 93 |
94 | setTrackMetadataInput(e.target.value)} 97 | placeholder="track metadata" 98 | /> 99 | 100 |
101 | 102 | 103 | 104 | 105 | 106 |
107 | Replace status: 108 | {replaceStatus} 109 |
110 |
111 |
112 | 113 | 114 | 115 | 116 | 117 |
118 | 119 | 120 | 121 | 122 |
123 | ); 124 | }; 125 | -------------------------------------------------------------------------------- /e2e/app/src/VideoPlayer.tsx: -------------------------------------------------------------------------------- 1 | import { useEffect, useRef } from "react"; 2 | 3 | type Props = { 4 | stream?: MediaStream; 5 | id?: string; 6 | }; 7 | 8 | export const VideoPlayer = ({ stream, id }: Props) => { 9 | const heartRef = useRef(null); 10 | 11 | useEffect(() => { 12 | if (!heartRef.current) return; 13 | heartRef.current.srcObject = stream || null; 14 | }, [stream]); 15 | 16 | return