参考文章链接
https://blog.csdn.net/kaimo313/article/details/117090375
export default class Decoder {
init(M) {
// M = self.Module 即wasm环境变量
this.M = M
// 创建wasm的回调函数,viii表示有3个int参数
const callback = this.M.addFunction(this._handleYUVData, 'viii')
// 通过我们上面decoder.c文件的方法传入回调
this.M._init_decoder(callback)
}
decode(packet) {
const { data } = packet
const typedArray = data
const bufferLength = typedArray.length
// 申请内存区,并放入数据
const bufferPtr = this.M._malloc(bufferLength)
this.M.HEAPU8.set(typedArray, bufferPtr)
// 解码buffer
this.M._decode_buffer(bufferPtr, bufferLength)
// 释放内存区
this.M._free(bufferPtr)
}
_handleYUVData(start, size, pts) {
// 回调传回来的第一个参数是yuv_buffer的内存起始索引
const u8s = this.M.HEAPU8.subarray(start, start + size)
const output = new Uint8Array(u8s)
this.emit('decoded-frame', {
data: output,
pts,
})
}
}
import Decoder from './decoder'
const global = self
export default class DecoderManager {
// let loaded = false
// let decoder = new Decoder()
// let cachePackets = []
constructor(loaded, decoder, cachePackets) {
this.loaded = loaded;
this.decoder = decoder
this.cachePackets = cachePackets
}
load() {
// 表明wasm文件的位置
global.Module = {
locateFile: (wasm) => './wasm/' + wasm,
}
global.importScripts('./wasm/libffmpeg.js')
// 初始化之后,执行一次push,把缓存的packet送到decoder里
global.Module.onRuntimeInitialized = () => {
this.loaded = true
this.decoder.init(global.Module)
this.push([])
}
// this.decoder.on('decoded-frame', this.handleYUVBuffer)
// decoder.on('decoded-frame', this.handleYUVBuffer)
}
push(packets) {
// 没加载就缓存起来,加载了就先取缓存
if (!this.loaded) {
this.cachePackets = this.cachePackets.concat(packets)
} else {
if (this.cachePackets.length) {
this.cachePackets.forEach((frame) => this.decoder.decode(frame))
this.cachePackets = []
}
packets.forEach((frame) => this.decoder.decode(frame))
}
}
handleYUVBuffer(frame) {
global.postMessage({
type: 'decoded-frame',
data: frame,
})
}
}
const manager = new DecoderManager()
manager.load()
self.onmessage = function (event) {
const data = event.data
const type = data.type
switch (type) {
case 'decode':
manager.push(data.data)
break
}
}
前端调用js部分看不太懂,我的环境是vue2,文章里面是用ts写的,本地把ts 写成 js, js里面的函数报错
有没有做过的友友 可以帮忙解决一下
打印下global,看下面是不是没有importScripts这个方法
可能是引入不正确