├── .gitignore
├── LICENSE
├── NOTICE
├── README.md
├── README_warp.md
├── cert
├── .gitignore
├── fingerprint
└── generate
├── media
├── .gitignore
└── generate
├── player
├── .env.production
├── .gitignore
├── package-lock.json
├── package.json
├── src
│ ├── appsettings.js
│ ├── assets
│ │ └── github-mark-white.svg
│ ├── db.ts
│ ├── estimator.ts
│ ├── index.html
│ ├── index.ts
│ ├── init.ts
│ ├── message.ts
│ ├── mp4.ts
│ ├── mp4box.all.js
│ ├── player.css
│ ├── player.ts
│ ├── segment.ts
│ ├── source.ts
│ ├── stream.ts
│ ├── track.ts
│ ├── types
│ │ ├── global.d.ts
│ │ └── webtransport.d.ts
│ └── util.ts
├── tsconfig.json
└── yarn.lock
├── server
├── .gitignore
├── bin
│ └── speedtest.sh
├── go.mod
├── go.sum
├── internal
│ └── warp
│ │ ├── media.go
│ │ ├── message.go
│ │ ├── server.go
│ │ ├── session.go
│ │ └── stream.go
├── main.go
├── start.sh
└── tc_scripts
│ ├── profile_cascade
│ ├── profile_fast_jitters
│ ├── profile_intra_cascade
│ ├── profile_lte
│ ├── profile_slow_jitters
│ ├── profile_spike
│ ├── profile_twitch
│ ├── tc_reset.sh
│ ├── test_profile
│ ├── test_profile copy
│ └── throttle.sh
├── side-load
└── 1MB-chunk.m4s
└── tc_profiles
├── FCCamazone
├── FCCamazone_x0.25
├── NYUbus
├── NYUbus_x0.25
├── Synthtic
├── Synthtic_x0.25
├── bandwidth_scale.ods
├── cascade_profile
├── cascade_profile_x0.05
├── cascade_profile_x0.25
├── cascade_profile_x1.25
├── cascade_profile_x3
├── cascade_profile_x4
├── cascade_profile_x4.5
├── lte_profile
├── lte_profile_x0.25
├── lte_profile_x3
├── lte_profile_x4
├── tc_clear.sh
├── tc_limit.sh
├── tc_netem.sh
├── tc_policy.sh
├── tc_start.sh
├── twitch_profile
├── twitch_profile_x0.25
├── twitch_profile_x3
└── twitch_profile_x4
/.gitignore:
--------------------------------------------------------------------------------
1 | *.mp4
2 | logs/
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/NOTICE:
--------------------------------------------------------------------------------
1 | Copyright Amazon.com Inc. or its affiliates.
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
9 | Unless required by applicable law or agreed to in writing, software
10 | distributed under the License is distributed on an "AS IS" BASIS,
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | See the License for the specific language governing permissions and
13 | limitations under the License.
14 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # WARP as a MOQ Protocol
2 |
3 | Warp is a live media transport protocol over QUIC. Media is split into objects based on the underlying media encoding and transmitted independently over QUIC streams. QUIC streams are prioritized based on the delivery order, allowing less important objects to be starved or dropped during congestion.
4 |
5 | See the [Warp draft](https://datatracker.ietf.org/doc/draft-lcurley-warp/).
6 |
7 | # MOQ Testbed
8 |
9 | This demo has been forked off the original [WARP demo application code](https://github.com/kixelated/warp).
10 |
11 | You can find a working demo [here](https://moq.streaming.university).
12 |
13 | There are numerous additions as follows:
14 |
15 | - Server-to-client informational messages: Added Common Media Server Data (CMSD, CTA-5006)
16 | keys: Availability Time (at) and Estimated Throughput (ETP).
17 | - Client-to-server control messages
18 | - Passive bandwidth measurements: Sliding Window Moving Average with Threshold (SWMAth) and I-Frame Average (IFA).
19 | - Active bandwidth measurements
20 | - Enhanced user interface
21 |
22 | More information and test results have been published in the following paper:
23 |
24 | Z. Gurel, T. E. Civelek, A. Bodur, S. Bilgin, D. Yeniceri, and A. C. Begen. Media
25 | over QUIC: Initial testing, findings and results. In ACM MMSys, 2023.
--------------------------------------------------------------------------------
/README_warp.md:
--------------------------------------------------------------------------------
1 | # Warp
2 | Segmented live media delivery protocol utilizing QUIC streams. See the [Warp draft](https://datatracker.ietf.org/doc/draft-lcurley-warp/).
3 |
4 | Warp works by delivering each audio and video segment as a separate QUIC stream. These streams are assigned a priority such that old video will arrive last and can be dropped. This avoids buffering in many cases, offering the viewer a potentially better experience.
5 |
6 | # Limitations
7 | ## Browser Support
8 | This demo currently only works on Chrome for two reasons:
9 |
10 | 1. WebTransport support.
11 | 2. [Media underflow behavior](https://github.com/whatwg/html/issues/6359).
12 |
13 | The ability to skip video abuses the fact that Chrome can play audio without video for up to 3 seconds (hardcoded!) when using MSE. It is possible to use something like WebCodecs instead... but that's still Chrome only at the moment.
14 |
15 | ## Streaming
16 | This demo works by reading pre-encoded media and sleeping based on media timestamps. Obviously this is not a live stream; you should plug in your own encoder or source.
17 |
18 | The media is encoded on disk as a LL-DASH playlist. There's a crude parser and I haven't used DASH before so don't expect it to work with arbitrary inputs.
19 |
20 | ## QUIC Implementation
21 | This demo uses a fork of [quic-go](https://github.com/lucas-clemente/quic-go). There are two critical features missing upstream:
22 |
23 | 1. ~~[WebTransport](https://github.com/lucas-clemente/quic-go/issues/3191)~~
24 | 2. [Prioritization](https://github.com/lucas-clemente/quic-go/pull/3442)
25 |
26 | ## Congestion Control
27 | This demo uses a single rendition. A production implementation will want to:
28 |
29 | 1. Change the rendition bitrate to match the estimated bitrate.
30 | 2. Switch renditions at segment boundaries based on the estimated bitrate.
31 | 3. or both!
32 |
33 | Also, quic-go ships with the default New Reno congestion control. Something like [BBRv2](https://github.com/lucas-clemente/quic-go/issues/341) will work much better for live video as it limits RTT growth.
34 |
35 |
36 | # Setup
37 | ## Requirements
38 | * Go
39 | * ffmpeg
40 | * openssl
41 | * Chrome Canary
42 |
43 | ## Media
44 | This demo simulates a live stream by reading a file from disk and sleeping based on media timestamps. Obviously you should hook this up to a real live stream to do anything useful.
45 |
46 | Download your favorite media file:
47 | ```
48 | wget http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4 -O media/source.mp4
49 | ```
50 |
51 | Use ffmpeg to create a LL-DASH playlist. This creates a segment every 2s and MP4 fragment every 10ms.
52 | ```
53 | ffmpeg -i media/source.mp4 -f dash -use_timeline 0 -r:v 24 -g:v 48 -keyint_min:v 48 -sc_threshold:v 0 -tune zerolatency -streaming 1 -ldash 1 -seg_duration 2 -frag_duration 0.01 -frag_type duration media/playlist.mpd
54 | ```
55 |
56 | You can increase the `frag_duration` (microseconds) to slightly reduce the file size in exchange for higher latency.
57 |
58 | ## TLS
59 | Unfortunately, QUIC mandates TLS and makes local development difficult.
60 |
61 | If you have a valid certificate you can use it instead of self-signing. The go binaries take a `-tls-cert` and `-tls-key` argument. Skip the remaining steps in this section and use your hostname instead.
62 |
63 | Otherwise, use [mkcert](https://github.com/FiloSottile/mkcert) to install a self-signed CA:
64 | ```
65 | mkcert -install
66 | ```
67 |
68 | With no arguments, the server will generate self-signed cert using this root CA.
69 |
70 | ## Server
71 | The Warp server supports WebTransport, pushing media over streams once a connection has been established. A more refined implementation would load content based on the WebTransport URL or some other messaging scheme.
72 |
73 | ```
74 | cd server
75 | go run main.go
76 | ```
77 |
78 | This can be accessed via WebTransport on `https://localhost:4443` by default.
79 |
80 | ## Web Player
81 | The web assets need to be hosted with a HTTPS server. If you're using a self-signed certificate, you may need to ignore the security warning in Chrome (Advanced -> proceed to localhost).
82 |
83 | ```
84 | cd player
85 | yarn install
86 | yarn serve
87 | ```
88 |
89 | These can be accessed on `https://localhost:4444` by default.
90 |
91 | If you use a custom domain for the Warp server, make sure to override the server URL with the `url` query string parameter, e.g. `https://localhost:4444/?url=https://warp.demo`.
92 |
93 | ## Chrome
94 | Now we need to make Chrome accept these certificates, which normally would involve trusting a root CA but this was not working with WebTransport when I last tried.
95 |
96 | Instead, we need to run a *fresh instance* of Chrome, instructing it to allow our self-signed certificate. This command will not work if Chrome is already running, so it's easier to use Chrome Canary instead.
97 |
98 | Launch a new instance of Chrome Canary:
99 | ```
100 | /Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary --allow-insecure-localhost --origin-to-force-quic-on=localhost:4443 https://localhost:4444
101 | ```
102 |
--------------------------------------------------------------------------------
/cert/.gitignore:
--------------------------------------------------------------------------------
1 | *.crt
2 | *.key
3 |
--------------------------------------------------------------------------------
/cert/fingerprint:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -euo pipefail
3 |
4 | HOST="localhost"
5 |
6 | cd "$(dirname "${BASH_SOURCE[0]}")"
7 |
8 | # Outputs the certificate fingerprint in the format Chrome expects
9 | openssl x509 -pubkey -noout -in "${HOST}.crt" |
10 | openssl rsa -pubin -outform der 2>/dev/null |
11 | openssl dgst -sha256 -binary |
12 | base64
13 |
--------------------------------------------------------------------------------
/cert/generate:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -euxo pipefail
3 |
4 | cd "$(dirname "${BASH_SOURCE[0]}")"
5 |
6 | mkcert -cert-file localhost.crt -key-file localhost.key localhost 127.0.0.1 ::1
7 |
--------------------------------------------------------------------------------
/media/.gitignore:
--------------------------------------------------------------------------------
1 | *.mp4
2 | *.mpd
3 | *.m4s
4 |
--------------------------------------------------------------------------------
/media/generate:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | input_file="source.mp4"
3 | segment_duration=2
4 | chunk_duration=0.04
5 | fps=25
6 |
7 | ffmpeg -i $input_file \
8 | -f dash -ldash 1 \
9 | -c:v libx264 \
10 | -filter:v fps=$fps \
11 | -preset veryfast -tune zerolatency \
12 | -c:a aac \
13 | -b:a 128k -ac 2 -ar 44100 \
14 | -map v:0 -s:v:0 1920x1080 -b:v:0 4M \
15 | -map v:0 -s:v:1 1080x720 -b:v:1 2.6M \
16 | -map v:0 -s:v:2 960x540 -b:v:2 1.3M \
17 | -map v:0 -s:v:3 640x360 -b:v:3 365k \
18 | -map 0:a \
19 | -force_key_frames "expr:gte(t,n_forced*2)" \
20 | -sc_threshold 0 \
21 | -streaming 1 \
22 | -use_timeline 0 \
23 | -seg_duration $segment_duration -frag_duration $chunk_duration \
24 | -frag_type duration \
25 | playlist.mpd
26 |
--------------------------------------------------------------------------------
/player/.env.production:
--------------------------------------------------------------------------------
1 | PUBLIC_URL=https://moq.streaming.university
2 | SERVER_URL=https://moq.streaming.university:8443
3 |
4 | HOST=moq.streaming.university
5 | PORT=443
--------------------------------------------------------------------------------
/player/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .parcel-cache
3 | dist
4 | .env.development
--------------------------------------------------------------------------------
/player/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "source": "src/index.html",
3 | "scripts": {
4 | "serve": "parcel serve --https --cert ../cert/cert.pem --key ../cert/privkey.pem",
5 | "build": "parcel build src/index.html --no-optimize src/appsettings.js",
6 | "check": "tsc --noEmit"
7 | },
8 | "devDependencies": {
9 | "@parcel/validator-typescript": "^2.6.0",
10 | "@types/node": "^18.11.18",
11 | "@types/plotly.js-dist": "npm:@types/plotly.js",
12 | "buffer": "^5.7.1",
13 | "parcel": "^2.8.2",
14 | "typescript": ">=3.0.0"
15 | },
16 | "dependencies": {
17 | "plotly.js-dist": "^2.17.0"
18 | }
19 | }
--------------------------------------------------------------------------------
/player/src/appsettings.js:
--------------------------------------------------------------------------------
1 | window.config = {
2 | serverURL: ":4443",
3 | resolutions: { 3: "360p", 2: "540p", 1: "720p", 0: "1080p" },
4 | throttleData: {
5 | 209715200: "200Mb/s",
6 | 67108864: "64Mb/s",
7 | 16777216: "16Mb/s",
8 | 4194304: "4Mb/s",
9 | 2097152: "2Mb/s",
10 | 1048576: "1Mb/s",
11 | 524288: "512Kb/s",
12 | 262144: "256Kb/s",
13 | 131072: "128Kb/s",
14 | },
15 | activeBWAsset: {
16 | url: "https://moq.streaming.university/side-load/1MB-chunk.m4s"
17 | },
18 | activeBWTestInterval: 1000000,
19 | autoStart: false,
20 | testDuration: 100,
21 | swma_calculation_type: 'segment',
22 | swma_threshold: 5,
23 | swma_threshold_type: 'percentage',
24 | swma_window_size: 25,
25 | swma_calculation_interval: 5
26 | };
27 |
--------------------------------------------------------------------------------
/player/src/assets/github-mark-white.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/player/src/db.ts:
--------------------------------------------------------------------------------
1 | const DB_VERSION = 8;
2 | let db: IDBDatabase;
3 | let status: 'none' | 'pending' | 'inited' = 'none';
4 |
5 | const getStatus = () => {
6 | return status;
7 | };
8 |
9 | const init = (): Promise => {
10 | return new Promise((resolve, reject) => {
11 | try {
12 | if (status !== 'none') {
13 | resolve(false);
14 | }
15 | status = 'pending';
16 |
17 | console.log('opening db');
18 | const DBOpenRequest = window.indexedDB.open('logs', DB_VERSION);
19 |
20 | console.log('opened db');
21 |
22 | // Register two event handlers to act on the database being opened successfully, or not
23 | DBOpenRequest.onerror = (event) => {
24 | console.error('error opening database', event);
25 | reject('error opening database');
26 | };
27 |
28 | DBOpenRequest.onsuccess = (event) => {
29 | console.log('Database initialised.');
30 | db = DBOpenRequest.result;
31 | status = 'inited';
32 | resolve(true);
33 | };
34 |
35 | DBOpenRequest.onupgradeneeded = (event: any) => {
36 | console.log('onupgradeneeded', event)
37 |
38 | db = event.target.result;
39 |
40 | db.onerror = (event) => {
41 | console.error('error loading database', event);
42 | reject('error loading database');
43 | };
44 |
45 | // Create an objectStore for this database
46 | try {
47 | let testStore, logStore, resultStore;
48 | if (db.objectStoreNames.contains('tests')) {
49 | db.deleteObjectStore('tests')
50 | }
51 |
52 | if (db.objectStoreNames.contains('test_logs')) {
53 | db.deleteObjectStore('test_logs')
54 | }
55 |
56 | if (db.objectStoreNames.contains('test_results')) {
57 | db.deleteObjectStore('test_results')
58 | }
59 |
60 |
61 | logStore = db.createObjectStore('test_logs', { keyPath: 'key', autoIncrement: true });
62 | testStore = db.createObjectStore('tests', { keyPath: 'testId' });
63 | resultStore = db.createObjectStore('test_results', { keyPath: 'key', autoIncrement: true });
64 |
65 | testStore.createIndex('ix_testId', 'testId', { unique: false });
66 | logStore.createIndex('ix_testId', 'testId', { unique: false });
67 | logStore.createIndex('ix_chunk_no', 'no', { unique: false });
68 | resultStore.createIndex('ix_testId', 'testId', { unique: false });
69 |
70 | console.log('Object stores created.');
71 | status = 'inited';
72 | } catch (ex) {
73 | console.error('exception in onupgradeneeded', ex);
74 | reject(ex);
75 | }
76 | // a 1 sec delay to avoid the error "A version change transaction is running"
77 | setTimeout(() => resolve(true), 1000);
78 | };
79 | } catch (ex) {
80 | console.error('Error in opening db', ex);
81 | reject(ex);
82 | }
83 | });
84 | };
85 |
86 | const addTestEntry = (test: any) => {
87 | addEntry('tests', test);
88 | };
89 |
90 | const addLogEntry = (log: any) => {
91 | addEntry('test_logs', log);
92 | };
93 |
94 | const addResultEntry = (result: any) => {
95 | addEntry('test_results', result);
96 | };
97 |
98 | const addEntry = (storeName: string, entry: any) => {
99 | // console.log('addEntry to %s', storeName, entry);
100 |
101 | const transaction = db.transaction([storeName], 'readwrite');
102 | transaction.oncomplete = () => {
103 | // console.log('added to %s', storeName);
104 | };
105 | transaction.onerror = () => {
106 | console.error('add to %s | error: %s', storeName, transaction.error);
107 | };
108 | const objectStore = transaction.objectStore(storeName);
109 | const objectStoreRequest = objectStore.add(entry);
110 | objectStoreRequest.onsuccess = (event) => {
111 | // console.log('request successful - %s', storeName)
112 | };
113 | };
114 |
115 | const getLogs = async (testId?: string): Promise => {
116 | if (testId) {
117 | return getEntriesByTestId('test_logs', testId);
118 | } else {
119 | return getEntries('test_logs');
120 | }
121 |
122 | };
123 |
124 | const getResults = async (testId: string): Promise => {
125 | return getEntriesByTestId('test_results', testId);
126 | };
127 |
128 | const getTests = async (): Promise => {
129 | return getEntries('tests');
130 | };
131 |
132 | const getEntries = async (storeName: string): Promise => {
133 | console.log('in getEntries | %s', storeName);
134 | return new Promise((resolve, reject) => {
135 | const transaction = db.transaction([storeName], 'readonly');
136 | transaction.oncomplete = () => {
137 | console.log('getEntries | transaction complete: %s', storeName);
138 | resolve(objectStoreRequest.result);
139 | };
140 | transaction.onerror = () => {
141 | console.error('add to %s | error: %s', storeName, transaction.error);
142 | reject('transaction error ' + transaction.error);
143 | };
144 | const objectStore = transaction.objectStore(storeName);
145 | const objectStoreRequest = objectStore.getAll();
146 | objectStoreRequest.onsuccess = (event) => {
147 | console.log('request successful', event);
148 | };
149 | });
150 | };
151 |
152 | const getEntriesByTestId = async (storeName: string, testId: string): Promise => {
153 | console.log('in getEntries | store: %s testId: %s', storeName, testId);
154 | return new Promise((resolve, reject) => {
155 | const keyRangeValue = IDBKeyRange.only(testId);
156 | const transaction = db.transaction([storeName], 'readonly');
157 | transaction.oncomplete = () => {
158 | console.log('transaction complete', objectStoreRequest.result);
159 | resolve(objectStoreRequest.result);
160 | };
161 | transaction.onerror = () => {
162 | console.error('add to %s | error: %s', storeName, transaction.error);
163 | reject('transaction error ' + transaction.error);
164 | };
165 | const objectStore = transaction.objectStore(storeName);
166 | const storeIndex = objectStore.index("ix_testId");
167 | const objectStoreRequest = storeIndex.getAll(keyRangeValue);
168 | objectStoreRequest.onsuccess = (event) => {
169 | console.log('request successful', event);
170 | };
171 | });
172 | };
173 |
174 | const getDb = () => {
175 | return db;
176 | };
177 |
178 |
179 | export const dbStore = {
180 | getStatus,
181 | addTestEntry,
182 | addLogEntry,
183 | addResultEntry,
184 | init,
185 | getLogs,
186 | getResults,
187 | getDb,
188 | getTests
189 | };
190 |
--------------------------------------------------------------------------------
/player/src/estimator.ts:
--------------------------------------------------------------------------------
1 | import { dbStore } from './db';
2 |
3 | const chunkStats: any[] = [];
4 | let totalChunkCount = 0;
5 | let tputs: any[] = [];
6 |
7 | const getSWMAThreshold = () => {
8 | return window.config.swma_threshold || 5;
9 | }
10 |
11 | const getSWMACalculationType = () => {
12 | return window.config.swma_calculation_type;
13 | }
14 |
15 | const getSWMAThresholdType = () => {
16 | return window.config.swma_threshold_type || 'percentage'
17 | };
18 |
19 | const getSWMACalculationInterval = () => {
20 | return window.config.swma_calculation_interval || 10;
21 | }
22 |
23 | const getSWMAWindowSize = () => {
24 | return window.config.swma_window_size || 50;
25 | }
26 |
27 | const initDb = async () => {
28 | try {
29 | console.log('initing db');
30 | if (!await dbStore.init()) {
31 | console.log('db already inited');
32 | } else {
33 | console.log('db inited');
34 | }
35 | } catch (ex) {
36 | alert('db store could not be created');
37 | console.error(ex);
38 | return;
39 | }
40 | }
41 |
42 | const getTests = async () => {
43 | await initDb();
44 | const tests = await dbStore.getTests();
45 | return tests;
46 | }
47 | const computeByTestId = async (testId: string) => {
48 | await initDb();
49 | const logs = await dbStore.getLogs(testId);
50 | if (logs?.length > 0) {
51 | tputs.splice(0);
52 | let lastTPut = 0;
53 | logs.forEach((item, i) => {
54 | totalChunkCount++;
55 | chunkStats.push([item.chunkSize, item.chunkDownloadDuration]);
56 | if (totalChunkCount >= getSWMAWindowSize() && totalChunkCount % getSWMACalculationInterval() === 0) {
57 | let stats = chunkStats.slice(-getSWMAWindowSize());
58 | let filteredStats = filterStats(stats, getSWMAThreshold(), getSWMAThresholdType(), lastTPut);
59 | // this.throughputs.set('swma', computeTPut(filteredStats));
60 | const tput = computeTPut(filteredStats);
61 |
62 | filteredStats = filterStats(stats, getSWMAThreshold(), getSWMAThresholdType());
63 | const tput2 = computeTPut(filteredStats);
64 |
65 | tputs.push([
66 | tput,
67 | tput2,
68 | item.msg_tc_rate * 1000,
69 | !item.msg_tc_rate ? 0 : Math.round(Math.abs(tput - item.msg_tc_rate * 1000)), // abs diff
70 | !item.msg_tc_rate ? 0 : Math.round(Math.abs(tput - item.msg_tc_rate * 1000) / (item.msg_tc_rate * 1000) * 100), // abs diff percent
71 | !item.msg_tc_rate ? 0 : Math.round(Math.abs(tput2 - item.msg_tc_rate * 1000)), // abs diff
72 | !item.msg_tc_rate ? 0 : Math.round(Math.abs(tput2 - item.msg_tc_rate * 1000) / (item.msg_tc_rate * 1000) * 100) // abs diff percent
73 | ]);
74 | lastTPut = tput;
75 | console.log('%d %f %f', (i + 1), tput, tput2);
76 | }
77 | });
78 |
79 | const totalAbsDiff = tputs.reduce((prev: number, current: any) => {
80 | return (prev || 0) + current[3];
81 | }, 0);
82 |
83 | const totalAbsDiffPercentage = tputs.reduce((prev: number, current: any) => {
84 | return (prev || 0) + current[4]; // percentage diff
85 | }, 0);
86 |
87 | const totalAbsDiff_2 = tputs.reduce((prev: number, current: any) => {
88 | return (prev || 0) + current[5];
89 | }, 0);
90 |
91 | const totalAbsDiffPercentage_2 = tputs.reduce((prev: number, current: any) => {
92 | return (prev || 0) + current[6]; // percentage diff
93 | }, 0);
94 |
95 | const meanAbsDiff = Math.round(totalAbsDiff / tputs.length);
96 | const meanAbsDiffPercentage = Math.round(totalAbsDiffPercentage / tputs.length);
97 | const meanAbsDiff_2 = Math.round(totalAbsDiff_2 / tputs.length);
98 | const meanAbsDiffPercentage_2 = Math.round(totalAbsDiffPercentage_2 / tputs.length);
99 |
100 | // console.log(tputs.map(x => x.join(',')).join('\n'));
101 | // console.log('totalAbsDiff: %f totalAbsDiffPercentage: %f meanAbsDiff: %f meanAbsDiffPercentage: %f total: %d', totalAbsDiff, totalAbsDiffPercentage, meanAbsDiff, meanAbsDiffPercentage, tputs.length);
102 | console.log('meanAbsDiff: %f meanAbsDiffPercentage: %f meanAbsDiff_2: %f meanAbsDiffPercentage_2: %f total: %d', meanAbsDiff, meanAbsDiffPercentage, meanAbsDiff_2, meanAbsDiffPercentage_2, tputs.length);
103 | }
104 | }
105 |
106 | const filterStats = (chunkStats: any[], threshold: number, thresholdType: string, lastTPut?: number) => {
107 | // filter out the ones with zero download duration
108 | let filteredStats = chunkStats.slice().filter(a => a[1] > 0);
109 | console.log('computeTPut | chunk count: %d thresholdType: %s threshold: %d', filteredStats.length, thresholdType, threshold);
110 |
111 | if (threshold > 0 && threshold < 100) {
112 | // sort chunk by download rate, in descending order
113 | filteredStats.sort((a, b) => {
114 | return (a[1] ? a[0] / a[1] : 0) > (b[1] ? b[0] / b[1] : 0) ? -1 : 1;
115 | });
116 |
117 | const topCut = Math.ceil(threshold / 100 * filteredStats.length);
118 | const bottomCut = Math.floor(threshold / 100 * filteredStats.length);
119 |
120 | filteredStats.splice(0, topCut);
121 | filteredStats.splice(filteredStats.length - bottomCut, bottomCut);
122 | }
123 |
124 | if (lastTPut) {
125 | const magicalNumber = 5;
126 | filteredStats = filteredStats.filter(m => {
127 | const chunkTPut = m[0] * 8 * 1000 / m[1];
128 | // if lastTPut is less than n time chunk tput or n times lastTPut is greater than chunk tput
129 | if (lastTPut < magicalNumber * chunkTPut && lastTPut * magicalNumber > chunkTPut) {
130 | return true;
131 | } else {
132 | console.log('filter %f %f', chunkTPut, lastTPut);
133 | return false;
134 | };
135 | });
136 | }
137 |
138 | console.log('computeTPut | after filtering: chunk count: %d', filteredStats.length);
139 | return filteredStats;
140 | }
141 |
142 | const computeTPut = (stats: any[]) => {
143 | let totalSize = 0;
144 | let totalDuration = 0;
145 | stats.forEach((arr, i) => {
146 | const size = arr[0];
147 | const downloadDurationOfChunk = arr[1];
148 | if (size > 0 && downloadDurationOfChunk > 0) {
149 | totalSize += size;
150 | totalDuration += downloadDurationOfChunk;
151 | }
152 | });
153 | return totalSize * 8 * 1000 / totalDuration;
154 | };
155 |
156 | export const estimator = {
157 | computeByTestId,
158 | getTests
159 | };
160 |
161 |
162 |
--------------------------------------------------------------------------------
/player/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | WARP
9 |
10 |
11 |
12 |
13 |
14 |