-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathwatch.js
77 lines (63 loc) · 2.01 KB
/
watch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
var html = require('choo/html')
var signalhub = require('signalhubws')
var swarm = require('webrtc-swarm')
var hypercore = require('hypercore')
var ram = require('random-access-memory')
var pump = require('pump')
var mimeType = require('./lib/getMimeType')(window.MediaSource.isTypeSupported)
var config = require('./config')
module.exports = watch
function watch (state, emit) {
var mediaSource = new window.MediaSource()
return html`
<div>
<div style="margin-bottom: 12px">
<video id="player" controls autoplay></video>
</div>
<div style="margin-bottom: 12px">
<button onclick=${startWatching}>
Watch broadcast
</button>
</div>
<div>
Key: <input type="text" id="key-input"/>
</div>
</div>
`
function startWatching () {
mediaSource.addEventListener('sourceopen', open)
var elPlayer = document.getElementById('player')
elPlayer.src = window.URL.createObjectURL(mediaSource)
elPlayer.play()
}
function open () {
var sourceBuffer = mediaSource.addSourceBuffer(mimeType)
var hash = document.getElementById('key-input').value
var feed = hypercore(ram, hash, {sparse: true})
feed.on('ready', function () {
feed.download({ linear: true })
var key = feed.discoveryKey.toString('hex')
var hub = signalhub(key, config.signalhub)
var sw = swarm(hub)
console.log('🌐 connecting to swarm')
sw.on('peer', function (peer, id) {
console.log('🙋 new peer found:', id)
pump(peer, feed.replicate({ live: true, download: true, encrypt: false }), peer)
})
var block = 0
getBlock(function () {
sourceBuffer.addEventListener('updateend', function () {
getBlock()
})
})
function getBlock (cb) {
feed.get(block, function (err, data) {
console.log('⚡️ appending block ' + block)
sourceBuffer.appendBuffer(data.buffer)
block++
if (cb) return cb()
})
}
})
}
}