p2p-media-loader-plugin.ts 6.19 KB
Newer Older
Chocobozzz's avatar
Chocobozzz committed
1
2
3
import * as Hlsjs from 'hls.js/dist/hls.light.js'
import { Events, Segment } from 'p2p-media-loader-core'
import { Engine, initHlsJsPlayer, initVideoJsContribHlsJsPlayer } from 'p2p-media-loader-hlsjs'
Chocobozzz's avatar
Chocobozzz committed
4
import videojs from 'video.js'
Chocobozzz's avatar
Chocobozzz committed
5
import { P2PMediaLoaderPluginOptions, PlayerNetworkInfo } from '../peertube-videojs-typings'
Chocobozzz's avatar
Chocobozzz committed
6
import { timeToInt } from '../utils'
7
import { registerConfigPlugin, registerSourceHandler } from './hls-plugin'
Chocobozzz's avatar
Chocobozzz committed
8

9
10
registerConfigPlugin(videojs)
registerSourceHandler(videojs)
Chocobozzz's avatar
Chocobozzz committed
11

Chocobozzz's avatar
Chocobozzz committed
12
const Plugin = videojs.getPlugin('plugin')
Chocobozzz's avatar
Chocobozzz committed
13
14
class P2pMediaLoaderPlugin extends Plugin {

15
16
17
  private readonly CONSTANTS = {
    INFO_SCHEDULER: 1000 // Don't change this
  }
Chocobozzz's avatar
Chocobozzz committed
18
  private readonly options: P2PMediaLoaderPluginOptions
19

20
  private hlsjs: Hlsjs
21
22
23
24
25
26
27
28
  private p2pEngine: Engine
  private statsP2PBytes = {
    pendingDownload: [] as number[],
    pendingUpload: [] as number[],
    numPeers: 0,
    totalDownload: 0,
    totalUpload: 0
  }
Chocobozzz's avatar
Chocobozzz committed
29
30
31
32
33
34
  private statsHTTPBytes = {
    pendingDownload: [] as number[],
    pendingUpload: [] as number[],
    totalDownload: 0,
    totalUpload: 0
  }
Chocobozzz's avatar
Chocobozzz committed
35
  private startTime: number
36
37
38

  private networkInfoInterval: any

Chocobozzz's avatar
Chocobozzz committed
39
40
41
  private hlsjsCurrentLevel: number
  private hlsjsLevels: Hlsjs.Level[]

Chocobozzz's avatar
Chocobozzz committed
42
  constructor (player: videojs.Player, options?: P2PMediaLoaderPluginOptions) {
Chocobozzz's avatar
Chocobozzz committed
43
    super(player)
Chocobozzz's avatar
Chocobozzz committed
44

Chocobozzz's avatar
Chocobozzz committed
45
46
    this.options = options

Chocobozzz's avatar
Chocobozzz committed
47
48
    // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
    if (!(videojs as any).Html5Hlsjs) {
49
      console.warn('HLS.js does not seem to be supported. Try to fallback to built in HLS.')
50

51
52
53
      if (!player.canPlayType('application/vnd.apple.mpegurl')) {
        const message = 'Cannot fallback to built-in HLS'
        console.warn(message)
54

55
56
57
58
59
60
61
62
        player.ready(() => player.trigger('error', new Error(message)))
        return
      }
    } else {
      // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
      (videojs as any).Html5Hlsjs.addHook('beforeinitialize', (videojsPlayer: any, hlsjs: any) => {
        this.hlsjs = hlsjs
      })
63

64
65
      initVideoJsContribHlsJsPlayer(player)
    }
Chocobozzz's avatar
Chocobozzz committed
66

Chocobozzz's avatar
Chocobozzz committed
67
68
    this.startTime = timeToInt(options.startTime)

Chocobozzz's avatar
Chocobozzz committed
69
70
71
72
    player.src({
      type: options.type,
      src: options.src
    })
Chocobozzz's avatar
Chocobozzz committed
73

74
75
    player.ready(() => {
      this.initializeCore()
Chocobozzz's avatar
Chocobozzz committed
76

77
78
79
80
      if ((videojs as any).Html5Hlsjs) {
        this.initializePlugin()
      }
    })
Chocobozzz's avatar
Chocobozzz committed
81
82
  }

83
  dispose () {
Chocobozzz's avatar
Chocobozzz committed
84
85
86
    if (this.hlsjs) this.hlsjs.destroy()
    if (this.p2pEngine) this.p2pEngine.destroy()

87
88
89
    clearInterval(this.networkInfoInterval)
  }

Chocobozzz's avatar
Chocobozzz committed
90
91
92
93
94
95
96
97
98
99
  getCurrentLevel () {
    return this.hlsjsLevels.find(l => l.level === this.hlsjsCurrentLevel)
  }

  getLiveLatency () {
    return undefined as number
    // FIXME: Use latency when hls >= V1
    // return this.hlsjs.latency
  }

Chocobozzz's avatar
Chocobozzz committed
100
101
102
103
  getHLSJS () {
    return this.hlsjs
  }

104
105
106
107
108
109
110
111
112
113
114
115
116
  private initializeCore () {
    this.player.one('play', () => {
      this.player.addClass('vjs-has-big-play-button-clicked')
    })

    this.player.one('canplay', () => {
      if (this.startTime) {
        this.player.currentTime(this.startTime)
      }
    })
  }

  private initializePlugin () {
Chocobozzz's avatar
Chocobozzz committed
117
118
    initHlsJsPlayer(this.hlsjs)

Chocobozzz's avatar
Chocobozzz committed
119
120
121
    // FIXME: typings
    const options = this.player.tech(true).options_ as any
    this.p2pEngine = options.hlsjsConfig.loader.getEngine()
122

123
    this.hlsjs.on(Hlsjs.Events.LEVEL_SWITCHING, (_: any, data: any) => {
124
125
126
      this.trigger('resolutionChange', { auto: this.hlsjs.autoLevelEnabled, resolutionId: data.height })
    })

127
128
129
130
    this.hlsjs.on(Hlsjs.Events.MANIFEST_LOADED, (_: any, data: any) => {
      this.trigger('resolutionsLoaded')
    })

Chocobozzz's avatar
Chocobozzz committed
131
    this.p2pEngine.on(Events.SegmentError, (segment: Segment, err) => {
Chocobozzz's avatar
Chocobozzz committed
132
      console.error('Segment error.', segment, err)
Chocobozzz's avatar
Chocobozzz committed
133

134
      this.options.redundancyUrlManager.removeBySegmentUrl(segment.requestUrl)
Chocobozzz's avatar
Chocobozzz committed
135
136
    })

Chocobozzz's avatar
Chocobozzz committed
137
    this.statsP2PBytes.numPeers = 1 + this.options.redundancyUrlManager.countBaseUrls()
Chocobozzz's avatar
Chocobozzz committed
138

139
140
141
142
143
    this.runStats()
  }

  private runStats () {
    this.p2pEngine.on(Events.PieceBytesDownloaded, (method: string, size: number) => {
Chocobozzz's avatar
Chocobozzz committed
144
145
146
147
      const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes

      elem.pendingDownload.push(size)
      elem.totalDownload += size
148
149
150
    })

    this.p2pEngine.on(Events.PieceBytesUploaded, (method: string, size: number) => {
Chocobozzz's avatar
Chocobozzz committed
151
152
153
154
      const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes

      elem.pendingUpload.push(size)
      elem.totalUpload += size
155
156
157
158
159
    })

    this.p2pEngine.on(Events.PeerConnect, () => this.statsP2PBytes.numPeers++)
    this.p2pEngine.on(Events.PeerClose, () => this.statsP2PBytes.numPeers--)

Chocobozzz's avatar
Chocobozzz committed
160
161
162
163
164
165
166
167
    this.hlsjs.on(Hlsjs.Events.MANIFEST_PARSED, (_e, manifest) => {
      this.hlsjsCurrentLevel = manifest.firstLevel
      this.hlsjsLevels = manifest.levels
    })
    this.hlsjs.on(Hlsjs.Events.LEVEL_LOADED, (_e, level) => {
      this.hlsjsCurrentLevel = level.levelId || (level as any).id
    })

168
    this.networkInfoInterval = setInterval(() => {
Chocobozzz's avatar
Chocobozzz committed
169
170
171
172
173
      const p2pDownloadSpeed = this.arraySum(this.statsP2PBytes.pendingDownload)
      const p2pUploadSpeed = this.arraySum(this.statsP2PBytes.pendingUpload)

      const httpDownloadSpeed = this.arraySum(this.statsHTTPBytes.pendingDownload)
      const httpUploadSpeed = this.arraySum(this.statsHTTPBytes.pendingUpload)
174
175
176

      this.statsP2PBytes.pendingDownload = []
      this.statsP2PBytes.pendingUpload = []
Chocobozzz's avatar
Chocobozzz committed
177
178
      this.statsHTTPBytes.pendingDownload = []
      this.statsHTTPBytes.pendingUpload = []
179
180

      return this.player.trigger('p2pInfo', {
181
        source: 'p2p-media-loader',
Chocobozzz's avatar
Chocobozzz committed
182
183
184
185
186
187
        http: {
          downloadSpeed: httpDownloadSpeed,
          uploadSpeed: httpUploadSpeed,
          downloaded: this.statsHTTPBytes.totalDownload,
          uploaded: this.statsHTTPBytes.totalUpload
        },
188
        p2p: {
Chocobozzz's avatar
Chocobozzz committed
189
190
          downloadSpeed: p2pDownloadSpeed,
          uploadSpeed: p2pUploadSpeed,
191
192
193
          numPeers: this.statsP2PBytes.numPeers,
          downloaded: this.statsP2PBytes.totalDownload,
          uploaded: this.statsP2PBytes.totalUpload
Chocobozzz's avatar
Chocobozzz committed
194
195
        },
        bandwidthEstimate: (this.hlsjs as any).bandwidthEstimate / 8
196
197
198
      } as PlayerNetworkInfo)
    }, this.CONSTANTS.INFO_SCHEDULER)
  }
Chocobozzz's avatar
Chocobozzz committed
199
200
201
202

  private arraySum (data: number[]) {
    return data.reduce((a: number, b: number) => a + b, 0)
  }
Chocobozzz's avatar
Chocobozzz committed
203
204
205
206
}

videojs.registerPlugin('p2pMediaLoader', P2pMediaLoaderPlugin)
export { P2pMediaLoaderPlugin }