main
Raw Download raw file
 1/*
 2 * noVNC: HTML5 VNC client
 3 * Copyright (C) 2020 The noVNC authors
 4 * Licensed under MPL 2.0 (see LICENSE.txt)
 5 *
 6 * See README.md for usage and integration instructions.
 7 */
 8
 9import { deflateInit, deflate } from "../vendor/pako/lib/zlib/deflate.js";
10import { Z_FULL_FLUSH, Z_DEFAULT_COMPRESSION } from "../vendor/pako/lib/zlib/deflate.js";
11import ZStream from "../vendor/pako/lib/zlib/zstream.js";
12
13export default class Deflator {
14    constructor() {
15        this.strm = new ZStream();
16        this.chunkSize = 1024 * 10 * 10;
17        this.outputBuffer = new Uint8Array(this.chunkSize);
18
19        deflateInit(this.strm, Z_DEFAULT_COMPRESSION);
20    }
21
22    deflate(inData) {
23        /* eslint-disable camelcase */
24        this.strm.input = inData;
25        this.strm.avail_in = this.strm.input.length;
26        this.strm.next_in = 0;
27        this.strm.output = this.outputBuffer;
28        this.strm.avail_out = this.chunkSize;
29        this.strm.next_out = 0;
30        /* eslint-enable camelcase */
31
32        let lastRet = deflate(this.strm, Z_FULL_FLUSH);
33        let outData = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out);
34
35        if (lastRet < 0) {
36            throw new Error("zlib deflate failed");
37        }
38
39        if (this.strm.avail_in > 0) {
40            // Read chunks until done
41
42            let chunks = [outData];
43            let totalLen = outData.length;
44            do {
45                /* eslint-disable camelcase */
46                this.strm.output = new Uint8Array(this.chunkSize);
47                this.strm.next_out = 0;
48                this.strm.avail_out = this.chunkSize;
49                /* eslint-enable camelcase */
50
51                lastRet = deflate(this.strm, Z_FULL_FLUSH);
52
53                if (lastRet < 0) {
54                    throw new Error("zlib deflate failed");
55                }
56
57                let chunk = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out);
58                totalLen += chunk.length;
59                chunks.push(chunk);
60            } while (this.strm.avail_in > 0);
61
62            // Combine chunks into a single data
63
64            let newData = new Uint8Array(totalLen);
65            let offset = 0;
66
67            for (let i = 0; i < chunks.length; i++) {
68                newData.set(chunks[i], offset);
69                offset += chunks[i].length;
70            }
71
72            outData = newData;
73        }
74
75        /* eslint-disable camelcase */
76        this.strm.input = null;
77        this.strm.avail_in = 0;
78        this.strm.next_in = 0;
79        /* eslint-enable camelcase */
80
81        return outData;
82    }
83
84}