]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/shared/p2p-media-loader/p2p-media-loader-plugin.ts
Prevent console error with HLS fallback
[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 } else {
70 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
71 (videojs as any).Html5Hlsjs.addHook('beforeinitialize', (videojsPlayer: any, hlsjs: any) => {
72 this.hlsjs = hlsjs
73 })
74
75 initVideoJsContribHlsJsPlayer(player)
76 }
77
78 this.startTime = timeToInt(options.startTime)
79
80 player.src({
81 type: options.type,
82 src: options.src
83 })
84
85 player.ready(() => {
86 this.initializeCore()
87
88 if ((videojs as any).Html5Hlsjs) {
89 this.initializePlugin()
90 }
91 })
92 }
93
94 dispose () {
95 if (this.hlsjs) this.hlsjs.destroy()
96 if (this.p2pEngine) this.p2pEngine.destroy()
97
98 clearInterval(this.networkInfoInterval)
99 }
100
101 getCurrentLevel () {
102 if (!this.hlsjs) return undefined
103
104 return this.hlsjs.levels[this.hlsjs.currentLevel]
105 }
106
107 getLiveLatency () {
108 return Math.round(this.hlsjs.latency)
109 }
110
111 getHLSJS () {
112 return this.hlsjs
113 }
114
115 private initializeCore () {
116 this.player.one('play', () => {
117 this.player.addClass('vjs-has-big-play-button-clicked')
118 })
119
120 this.player.one('canplay', () => {
121 if (this.startTime) {
122 this.player.currentTime(this.startTime)
123 }
124 })
125 }
126
127 private initializePlugin () {
128 initHlsJsPlayer(this.hlsjs)
129
130 this.p2pEngine = this.options.loader.getEngine()
131
132 this.p2pEngine.on(Events.SegmentError, (segment: Segment, err) => {
133 if (navigator.onLine === false) return
134
135 logger.error(`Segment ${segment.id} error.`, err)
136
137 this.options.redundancyUrlManager.removeBySegmentUrl(segment.requestUrl)
138 })
139
140 this.statsP2PBytes.numPeers = 1 + this.options.redundancyUrlManager.countBaseUrls()
141
142 this.runStats()
143
144 this.hlsjs.on(Hlsjs.Events.LEVEL_SWITCHED, () => this.player.trigger('engineResolutionChange'))
145 }
146
147 private runStats () {
148 this.p2pEngine.on(Events.PieceBytesDownloaded, (method: string, _segment, bytes: number) => {
149 const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
150
151 elem.pendingDownload.push(bytes)
152 elem.totalDownload += bytes
153 })
154
155 this.p2pEngine.on(Events.PieceBytesUploaded, (method: string, _segment, bytes: number) => {
156 if (method !== 'p2p') {
157 logger.error(`Received upload from unknown method ${method}`)
158 return
159 }
160
161 this.statsP2PBytes.pendingUpload.push(bytes)
162 this.statsP2PBytes.totalUpload += bytes
163 })
164
165 this.p2pEngine.on(Events.PeerConnect, () => this.statsP2PBytes.numPeers++)
166 this.p2pEngine.on(Events.PeerClose, () => this.statsP2PBytes.numPeers--)
167
168 this.networkInfoInterval = setInterval(() => {
169 const p2pDownloadSpeed = this.arraySum(this.statsP2PBytes.pendingDownload)
170 const p2pUploadSpeed = this.arraySum(this.statsP2PBytes.pendingUpload)
171
172 const httpDownloadSpeed = this.arraySum(this.statsHTTPBytes.pendingDownload)
173
174 this.statsP2PBytes.pendingDownload = []
175 this.statsP2PBytes.pendingUpload = []
176 this.statsHTTPBytes.pendingDownload = []
177
178 return this.player.trigger('p2pInfo', {
179 source: 'p2p-media-loader',
180 http: {
181 downloadSpeed: httpDownloadSpeed,
182 downloaded: this.statsHTTPBytes.totalDownload
183 },
184 p2p: {
185 downloadSpeed: p2pDownloadSpeed,
186 uploadSpeed: p2pUploadSpeed,
187 numPeers: this.statsP2PBytes.numPeers,
188 downloaded: this.statsP2PBytes.totalDownload,
189 uploaded: this.statsP2PBytes.totalUpload
190 },
191 bandwidthEstimate: (this.hlsjs as any).bandwidthEstimate / 8
192 } as PlayerNetworkInfo)
193 }, this.CONSTANTS.INFO_SCHEDULER)
194 }
195
196 private arraySum (data: number[]) {
197 return data.reduce((a: number, b: number) => a + b, 0)
198 }
199 }
200
201 videojs.registerPlugin('p2pMediaLoader', P2pMediaLoaderPlugin)
202 export { P2pMediaLoaderPlugin }