Merge branch 'release/v1.3.0' into develop
[oweals/peertube.git] / client / src / assets / player / p2p-media-loader / p2p-media-loader-plugin.ts
1 // FIXME: something weird with our path definition in tsconfig and typings
2 // @ts-ignore
3 import * as videojs from 'video.js'
4 import { P2PMediaLoaderPluginOptions, PlayerNetworkInfo, VideoJSComponentInterface } from '../peertube-videojs-typings'
5 import { Engine, initHlsJsPlayer, initVideoJsContribHlsJsPlayer } from 'p2p-media-loader-hlsjs'
6 import { Events } from 'p2p-media-loader-core'
7 import { timeToInt } from '../utils'
8
9 // videojs-hlsjs-plugin needs videojs in window
10 window['videojs'] = videojs
11 require('@streamroot/videojs-hlsjs-plugin')
12
13 const Plugin: VideoJSComponentInterface = 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: any // Don't type hlsjs to not bundle the module
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     pendingUpload: [] as number[],
33     totalDownload: 0,
34     totalUpload: 0
35   }
36   private startTime: number
37
38   private networkInfoInterval: any
39
40   constructor (player: videojs.Player, options: P2PMediaLoaderPluginOptions) {
41     super(player, options)
42
43     this.options = options
44
45     if (!videojs.Html5Hlsjs) {
46       const message = 'HLS.js does not seem to be supported.'
47       console.warn(message)
48
49       player.ready(() => player.trigger('error', new Error(message)))
50       return
51     }
52
53     videojs.Html5Hlsjs.addHook('beforeinitialize', (videojsPlayer: any, hlsjs: any) => {
54       this.hlsjs = hlsjs
55     })
56
57     initVideoJsContribHlsJsPlayer(player)
58
59     this.startTime = timeToInt(options.startTime)
60
61     player.src({
62       type: options.type,
63       src: options.src
64     })
65
66     player.one('play', () => {
67       player.addClass('vjs-has-big-play-button-clicked')
68     })
69
70     player.ready(() => this.initialize())
71   }
72
73   dispose () {
74     if (this.hlsjs) this.hlsjs.destroy()
75     if (this.p2pEngine) this.p2pEngine.destroy()
76
77     clearInterval(this.networkInfoInterval)
78   }
79
80   private initialize () {
81     initHlsJsPlayer(this.hlsjs)
82
83     const tech = this.player.tech_
84     this.p2pEngine = tech.options_.hlsjsConfig.loader.getEngine()
85
86     // Avoid using constants to not import hls.hs
87     // https://github.com/video-dev/hls.js/blob/master/src/events.js#L37
88     this.hlsjs.on('hlsLevelSwitching', (_: any, data: any) => {
89       this.trigger('resolutionChange', { auto: this.hlsjs.autoLevelEnabled, resolutionId: data.height })
90     })
91
92     this.p2pEngine.on(Events.SegmentError, (segment, err) => {
93       console.error('Segment error.', segment, err)
94     })
95
96     this.statsP2PBytes.numPeers = 1 + this.options.redundancyBaseUrls.length
97
98     this.runStats()
99
100     this.hlsjs.on('hlsLevelLoaded', () => {
101       if (this.startTime) this.player.currentTime(this.startTime)
102
103       this.hlsjs.off('hlsLevelLoaded', this)
104     })
105   }
106
107   private runStats () {
108     this.p2pEngine.on(Events.PieceBytesDownloaded, (method: string, size: number) => {
109       const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
110
111       elem.pendingDownload.push(size)
112       elem.totalDownload += size
113     })
114
115     this.p2pEngine.on(Events.PieceBytesUploaded, (method: string, size: number) => {
116       const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
117
118       elem.pendingUpload.push(size)
119       elem.totalUpload += size
120     })
121
122     this.p2pEngine.on(Events.PeerConnect, () => this.statsP2PBytes.numPeers++)
123     this.p2pEngine.on(Events.PeerClose, () => this.statsP2PBytes.numPeers--)
124
125     this.networkInfoInterval = setInterval(() => {
126       const p2pDownloadSpeed = this.arraySum(this.statsP2PBytes.pendingDownload)
127       const p2pUploadSpeed = this.arraySum(this.statsP2PBytes.pendingUpload)
128
129       const httpDownloadSpeed = this.arraySum(this.statsHTTPBytes.pendingDownload)
130       const httpUploadSpeed = this.arraySum(this.statsHTTPBytes.pendingUpload)
131
132       this.statsP2PBytes.pendingDownload = []
133       this.statsP2PBytes.pendingUpload = []
134       this.statsHTTPBytes.pendingDownload = []
135       this.statsHTTPBytes.pendingUpload = []
136
137       return this.player.trigger('p2pInfo', {
138         http: {
139           downloadSpeed: httpDownloadSpeed,
140           uploadSpeed: httpUploadSpeed,
141           downloaded: this.statsHTTPBytes.totalDownload,
142           uploaded: this.statsHTTPBytes.totalUpload
143         },
144         p2p: {
145           downloadSpeed: p2pDownloadSpeed,
146           uploadSpeed: p2pUploadSpeed,
147           numPeers: this.statsP2PBytes.numPeers,
148           downloaded: this.statsP2PBytes.totalDownload,
149           uploaded: this.statsP2PBytes.totalUpload
150         }
151       } as PlayerNetworkInfo)
152     }, this.CONSTANTS.INFO_SCHEDULER)
153   }
154
155   private arraySum (data: number[]) {
156     return data.reduce((a: number, b: number) => a + b, 0)
157   }
158 }
159
160 videojs.registerPlugin('p2pMediaLoader', P2pMediaLoaderPlugin)
161 export { P2pMediaLoaderPlugin }