UNPKG

hyper-beats

Version:

Decentralised music using hypercore

57 lines (49 loc) 1.72 kB
const cenc = require('compact-encoding') const safetyCatch = require('safety-catch') const BEATS_METADATA_VERSION_MAJOR = 1 const BEATS_METADATA_VERSION_MINOR = 0 const BeatsMetadataEnc = { preencode (state, m) { cenc.string.preencode(state, 'HYPERBEATS') cenc.uint.preencode(state, BEATS_METADATA_VERSION_MAJOR) cenc.uint.preencode(state, BEATS_METADATA_VERSION_MINOR) cenc.string.preencode(state, m.mimeType) cenc.uint.preencode(state, m.framesPerBlock) cenc.uint.preencode(state, m.bytesPerFrame) }, encode (state, m) { cenc.string.encode(state, 'HYPERBEATS') cenc.uint.encode(state, BEATS_METADATA_VERSION_MAJOR) cenc.uint.encode(state, BEATS_METADATA_VERSION_MINOR) cenc.string.encode(state, m.mimeType) cenc.uint.encode(state, m.framesPerBlock) cenc.uint.encode(state, m.bytesPerFrame) }, decode (state) { try { const dataType = cenc.string.decode(state) if (dataType !== 'HYPERBEATS') { throw new Error('No hyperbeats here') } const version = { major: cenc.uint.decode(state), minor: cenc.uint.decode(state) } if (version.major !== BEATS_METADATA_VERSION_MAJOR) { throw new Error('Incompatible Hyperbeats version') } return { version, mimeType: cenc.string.decode(state), framesPerBlock: cenc.uint.decode(state), bytesPerFrame: cenc.uint.decode(state) } } catch (e) { // TODO: differentiate between errors safetyCatch(e) throw new Error(`The core does not contain valid hyperbeats (version ${BEATS_METADATA_VERSION_MAJOR}.${BEATS_METADATA_VERSION_MINOR})`) } } } module.exports = { BeatsMetadataEnc }