
importScripts('./jsFFMPEG.js');
let initDecoder = null;
let decoderContext = null;
let decodeByFFMPEG = null;
let getWidth = null;
let getHeight = null;
let closeContext = null;
let context = null;
let outpic = null;
let outpicptr = null;
let ID = 265;
let initialized = false;
let firstIFrame = true;

class H265Decoder {
    constructor() {

        initDecoder = Module.cwrap('init_jsFFmpeg', 'void', []);
        decoderContext = Module.cwrap('context_jsFFmpeg', 'number', ['number']);
        decodeByFFMPEG = Module.cwrap('decode_video_jsFFmpeg', 'number', ['number', 'array', 'number', 'number']);
        getWidth = Module.cwrap('get_width', 'number', ['number']);
        getHeight = Module.cwrap('get_height', 'number', ['number']);
        closeContext = Module.cwrap('close_jsFFmpeg', 'number', ['number']);

        initDecoder();
        this.init();
        initialized = true;
    }
    init() {
        console.log("H265 Decoder init");
        if (context !== null) {
            closeContext(context);
            context = null;
        }
        context = decoderContext(ID);
    }

    setOutputSize(size) {
        console.log("H265 Decoder setOutputSize");
        let outpicsize = size * 1.5;
        outpicptr = Module._malloc(outpicsize);
        outpic = new Uint8Array(Module.HEAPU8.buffer, outpicptr, outpicsize);
    }

    decode(data) {
        if(!initialized) {
            console.log('未初始化完成')
            return null;
        }

        let frameType = (data[4] == 0x40) ? 'I' : 'P';
        //console.log(data[4] & 0x1f)
        if(frameType === 'I' && initialized) {
            firstIFrame = true;
        }
        if(!firstIFrame) {
            console.log('非 firstIFrame')
            return null;
        }
        let beforeDecoding = Date.now();
        let decodingTime = null;
        let frameData = null;
        decodeByFFMPEG(context, data, data.length, outpic.byteOffset);
        decodingTime = Date.now() - beforeDecoding;

        let width = getWidth(context);
        let height = getHeight(context);

        //console.log(width, height)
        if (width > 0 && height > 0) {
            let copyOutput = new Uint8Array(outpic);
            frameData = {
                'data': copyOutput,
                'width': width,
                'height': height,
                'codecType': 'h264',
                'decodingTime': decodingTime,
                'frameType': frameType,
            };

            return frameData;
        }

    }
}
