Skip to content

Instantly share code, notes, and snippets.

@cchudant
Last active March 22, 2020 18:51
Show Gist options
  • Save cchudant/4d08d7c2d78903ee40752d985096de01 to your computer and use it in GitHub Desktop.
Save cchudant/4d08d7c2d78903ee40752d985096de01 to your computer and use it in GitHub Desktop.
(() => {
const insertScript = src => {
const elem = document.createElement('script')
elem.src = src
document.head.append(elem)
}
const proxy = (original, proxyFn) => function (...args) {
try {
return proxyFn(original, this, args)
} catch (e) {
console.error('Error in proxy!', e)
throw e
}
}
const patchPrototype = (Constr, patch) => {
// doesnt support getters & setters
const proto = Constr.prototype
Object.entries(patch)
.map(([k, v]) => [k, proxy(proto[k], v)])
.forEach(([k, v]) => proto[k] = v)
}
insertScript('https://cdn.jsdelivr.net/npm/[email protected]/dist/ponyfill.min.js')
insertScript('https://cdn.jsdelivr.net/npm/[email protected]/StreamSaver.min.js')
const writer = new Promise(res => setTimeout(async () => {
window.streamSaver.WritableStream = window.WritableStream || window.WebStreamsPolyfill.WritableStream
const stream = window.streamSaver.createWriteStream('test.mp4')
const writer = stream.getWriter()
window.__writer = writer //debug
await writer.ready
res(writer)
}, 100))
patchPrototype(window.MediaSource, {
addSourceBuffer: (original, thisArg, args) => {
const id = thisArg.sourceBuffers.length
console.log(`New source buffer (id ${id}): ${args[0]}`)
const result = original.apply(thisArg, args)
result._id = id
result._mime = args[0]
return result
}
})
patchPrototype(window.SourceBuffer, {
appendBuffer: (original, thisArg, args) => {
console.log(`[${thisArg._id}/'${thisArg._mime}'] Append buffer`, args)
if (thisArg._mime.includes('video')) {
writer.then(handle => handle.write(args[0]))
}
return original.apply(thisArg, args)
}
})
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment