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