separation of concerns
This commit is contained in:
23
renderer/lib/capture-video-frame.js
Normal file
23
renderer/lib/capture-video-frame.js
Normal file
@@ -0,0 +1,23 @@
|
||||
module.exports = captureVideoFrame
|
||||
|
||||
function captureVideoFrame (video, format) {
|
||||
if (typeof video === 'string') video = document.querySelector(video)
|
||||
if (!video || video.nodeName !== 'VIDEO') {
|
||||
throw new Error('First argument must be a <video> element or selector')
|
||||
}
|
||||
if (format == null) format = 'png'
|
||||
if (format !== 'png' && format !== 'jpg' && format !== 'webp') {
|
||||
throw new Error('Second argument must be one of "png", "jpg", or "webp"')
|
||||
}
|
||||
|
||||
var canvas = document.createElement('canvas')
|
||||
canvas.width = video.videoWidth
|
||||
canvas.height = video.videoHeight
|
||||
|
||||
canvas.getContext('2d').drawImage(video, 0, 0)
|
||||
|
||||
var dataUri = canvas.toDataURL('image/' + format)
|
||||
var data = dataUri.split(',')[1]
|
||||
|
||||
return new Buffer(data, 'base64')
|
||||
}
|
||||
53
renderer/lib/torrent-poster.js
Normal file
53
renderer/lib/torrent-poster.js
Normal file
@@ -0,0 +1,53 @@
|
||||
module.exports = torrentPoster
|
||||
|
||||
var captureVideoFrame = require('./capture-video-frame')
|
||||
var path = require('path')
|
||||
|
||||
function torrentPoster (torrent, cb) {
|
||||
// use largest file
|
||||
var file = torrent.files
|
||||
.filter(function (file) {
|
||||
var extname = path.extname(file.name)
|
||||
return ['.mp4', '.webm', '.mov', '.mkv'].indexOf(extname) !== -1
|
||||
})
|
||||
.reduce(function (a, b) {
|
||||
return a.length > b.length ? a : b
|
||||
})
|
||||
var index = torrent.files.indexOf(file)
|
||||
|
||||
var server = torrent.createServer(0)
|
||||
server.listen(0, onListening)
|
||||
|
||||
function onListening () {
|
||||
var port = server.address().port
|
||||
var url = 'http://localhost:' + port + '/' + index
|
||||
var video = document.createElement('video')
|
||||
video.addEventListener('canplay', onCanPlay)
|
||||
|
||||
video.volume = 0
|
||||
video.src = url
|
||||
video.play()
|
||||
|
||||
function onCanPlay () {
|
||||
video.removeEventListener('canplay', onCanPlay)
|
||||
video.addEventListener('seeked', onSeeked)
|
||||
|
||||
video.currentTime = Math.min((video.duration || 600) * 0.03, 60)
|
||||
}
|
||||
|
||||
function onSeeked () {
|
||||
video.removeEventListener('seeked', onSeeked)
|
||||
|
||||
var buf = captureVideoFrame(video)
|
||||
|
||||
// unload video element
|
||||
video.pause()
|
||||
video.src = ''
|
||||
video.load()
|
||||
|
||||
server.destroy()
|
||||
|
||||
cb(null, buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user