UNPKG

luby

Version:

Generate fountain codes / erasure codes (Luby Transform, robust)

72 lines 2.53 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const distributions_1 = require("./distributions"); const selectNeighbours_1 = __importDefault(require("./selectNeighbours")); class Symbol { constructor(index, degree, data, K) { this.index = index; this.degree = degree; this.data = data; this.K = K; } } function splitFile(file, blockSize) { let blocks = []; for (var i = 0; i < file.length; i += blockSize) { blocks.push(Array.from(file.slice(i, i + blockSize))); } if (blocks[blocks.length - 1].length < blockSize) { blocks[blocks.length - 1] = blocks[blocks.length - 1].concat(new Array(blockSize - blocks[blocks.length - 1].length).fill(0)); } return blocks; } function choices(weights, k) { const choice = () => { const randomNr = Math.random(); let threshold = 0; let winner = null; for (var i = 0; i < weights.length; i++) { threshold += weights[i]; if (threshold > randomNr) { winner = i; return winner; } } return winner; }; const _choices = []; for (let i = 0; i < k; i++) { _choices[i] = choice(); } return _choices; } function getRandomDegrees(K, desiredNumberOfSymbols) { return [1, ...choices(distributions_1.generateRobustDistribution(K), desiredNumberOfSymbols)]; } function encode(file, blockSize, seed = "None") { const sourceSymbols = splitFile(file, blockSize); const K = sourceSymbols.length; let desiredNumberOfSymbols = Math.floor(K * 1.7); if (desiredNumberOfSymbols < 65) desiredNumberOfSymbols = 65; const randomDegrees = getRandomDegrees(K, desiredNumberOfSymbols); const xaEncode = (arar) => arar.reduce((a, b) => { const out = []; for (let i = 0; i < arar[0].length; i++) { out.push(a[i] ^ b[i]); } return out; }); const symbols = []; for (let i = 0; i < desiredNumberOfSymbols; i++) { const selectedNeighbours = selectNeighbours_1.default(i, randomDegrees[i], K); const data = xaEncode(selectedNeighbours.map(sn => sourceSymbols[sn])); symbols.push(new Symbol(i, selectedNeighbours.length, data, K)); } return symbols; } exports.default = encode; //# sourceMappingURL=encoder.js.map