]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/shared/p2p-media-loader/p2p-media-loader-plugin.ts
Merge branch 'release/4.3.0' into develop
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / shared / p2p-media-loader / p2p-media-loader-plugin.ts
1 import Hlsjs from 'hls.js'
2 import videojs from 'video.js'
3 import { Events, Segment } from '@peertube/p2p-media-loader-core'
4 import { Engine, initHlsJsPlayer, initVideoJsContribHlsJsPlayer } from '@peertube/p2p-media-loader-hlsjs'
5 import { logger } from '@root-helpers/logger'
6 import { timeToInt } from '@shared/core-utils'
7 import { P2PMediaLoaderPluginOptions, PlayerNetworkInfo } from '../../types'
8 import { registerConfigPlugin, registerSourceHandler } from './hls-plugin'
9
10 registerConfigPlugin(videojs)
11 registerSourceHandler(videojs)
12
13 const Plugin = videojs.getPlugin('plugin')
14 class P2pMediaLoaderPlugin extends Plugin {
15
16 private readonly CONSTANTS = {
17 INFO_SCHEDULER: 1000 // Don't change this
18 }
19 private readonly options: P2PMediaLoaderPluginOptions
20
21 private hlsjs: Hlsjs
22 private p2pEngine: Engine
23 private statsP2PBytes = {
24 pendingDownload: [] as number[],
25 pendingUpload: [] as number[],
26 numPeers: 0,
27 totalDownload: 0,
28 totalUpload: 0
29 }
30 private statsHTTPBytes = {
31 pendingDownload: [] as number[],
32 totalDownload: 0
33 }
34 private startTime: number
35
36 private networkInfoInterval: any
37
38 constructor (player: videojs.Player, options?: P2PMediaLoaderPluginOptions) {
39 super(player)
40
41 this.options = options
42
43 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
44 if (!(videojs as any).Html5Hlsjs) {
45 logger.warn('HLS.js does not seem to be supported. Try to fallback to built in HLS.')
46
47 let message: string
48 if (!player.canPlayType('application/vnd.apple.mpegurl')) {
49 message = 'Cannot fallback to built-in HLS'
50 } else if (options.requiresAuth) {
51 message = 'Video requires auth which is not compatible to build-in HLS player'
52 }
53
54 if (message) {
55 logger.warn(message)
56
57 const error: MediaError = {
58 code: MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED,
59 message,
60 MEDIA_ERR_ABORTED: MediaError.MEDIA_ERR_ABORTED,
61 MEDIA_ERR_DECODE: MediaError.MEDIA_ERR_DECODE,
62 MEDIA_ERR_NETWORK: MediaError.MEDIA_ERR_NETWORK,
63 MEDIA_ERR_SRC_NOT_SUPPORTED: MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED
64 }
65
66 player.ready(() => player.error(error))
67 return
68 }
69
70 // Workaround to force video.js to not re create a video element
71 (this.player as any).playerElIngest_ = this.player.el().parentNode
72 } else {
73 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
74 (videojs as any).Html5Hlsjs.addHook('beforeinitialize', (videojsPlayer: any, hlsjs: any) => {
75 this.hlsjs = hlsjs
76 })
77
78 initVideoJsContribHlsJsPlayer(player)
79 }
80
81 this.startTime = timeToInt(options.startTime)
82
83 player.src({
84 type: options.type,
85 src: options.src
86 })
87
88 player.ready(() => {
89 this.initializeCore()
90
91 if ((videojs as any).Html5Hlsjs) {
92 this.initializePlugin()
93 }
94 })
95 }
96
97 dispose () {
98 if (this.hlsjs) this.hlsjs.destroy()
99 if (this.p2pEngine) this.p2pEngine.destroy()
100
101 clearInterval(this.networkInfoInterval)
102 }
103
104 getCurrentLevel () {
105 if (!this.hlsjs) return undefined
106
107 return this.hlsjs.levels[this.hlsjs.currentLevel]
108 }
109
110 getLiveLatency () {
111 return Math.round(this.hlsjs.latency)
112 }
113
114 getHLSJS () {
115 return this.hlsjs
116 }
117
118 private initializeCore () {
119 this.player.one('play', () => {
120 this.player.addClass('vjs-has-big-play-button-clicked')
121 })
122
123 this.player.one('canplay', () => {
124 if (this.startTime) {
125 this.player.currentTime(this.startTime)
126 }
127 })
128 }
129
130 private initializePlugin () {
131 initHlsJsPlayer(this.hlsjs)
132
133 this.p2pEngine = this.options.loader.getEngine()
134
135 this.p2pEngine.on(Events.SegmentError, (segment: Segment, err) => {
136 if (navigator.onLine === false) return
137
138 logger.error(`Segment ${segment.id} error.`, err)
139
140 this.options.redundancyUrlManager.removeBySegmentUrl(segment.requestUrl)
141 })
142
143 this.statsP2PBytes.numPeers = 1 + this.options.redundancyUrlManager.countBaseUrls()
144
145 this.runStats()
146
147 this.hlsjs.on(Hlsjs.Events.LEVEL_SWITCHED, () => this.player.trigger('engineResolutionChange'))
148 }
149
150 private runStats () {
151 this.p2pEngine.on(Events.PieceBytesDownloaded, (method: string, _segment, bytes: number) => {
152 const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
153
154 elem.pendingDownload.push(bytes)
155 elem.totalDownload += bytes
156 })
157
158 this.p2pEngine.on(Events.PieceBytesUploaded, (method: string, _segment, bytes: number) => {
159 if (method !== 'p2p') {
160 logger.error(`Received upload from unknown method ${method}`)
161 return
162 }
163
164 this.statsP2PBytes.pendingUpload.push(bytes)
165 this.statsP2PBytes.totalUpload += bytes
166 })
167
168 this.p2pEngine.on(Events.PeerConnect, () => this.statsP2PBytes.numPeers++)
169 this.p2pEngine.on(Events.PeerClose, () => this.statsP2PBytes.numPeers--)
170
171 this.networkInfoInterval = setInterval(() => {
172 const p2pDownloadSpeed = this.arraySum(this.statsP2PBytes.pendingDownload)
173 const p2pUploadSpeed = this.arraySum(this.statsP2PBytes.pendingUpload)
174
175 const httpDownloadSpeed = this.arraySum(this.statsHTTPBytes.pendingDownload)
176
177 this.statsP2PBytes.pendingDownload = []
178 this.statsP2PBytes.pendingUpload = []
179 this.statsHTTPBytes.pendingDownload = []
180
181 return this.player.trigger('p2pInfo', {
182 source: 'p2p-media-loader',
183 http: {
184 downloadSpeed: httpDownloadSpeed,
185 downloaded: this.statsHTTPBytes.totalDownload
186 },
187 p2p: {
188 downloadSpeed: p2pDownloadSpeed,
189 uploadSpeed: p2pUploadSpeed,
190 numPeers: this.statsP2PBytes.numPeers,
191 downloaded: this.statsP2PBytes.totalDownload,
192 uploaded: this.statsP2PBytes.totalUpload
193 },
194 bandwidthEstimate: (this.hlsjs as any).bandwidthEstimate / 8
195 } as PlayerNetworkInfo)
196 }, this.CONSTANTS.INFO_SCHEDULER)
197 }
198
199 private arraySum (data: number[]) {
200 return data.reduce((a: number, b: number) => a + b, 0)
201 }
202 }
203
204 videojs.registerPlugin('p2pMediaLoader', P2pMediaLoaderPlugin)
205 export { P2pMediaLoaderPlugin }