From 2600fa884f6d71d325dfad995cc1d053106a88d6 Mon Sep 17 00:00:00 2001 From: Trek H Date: Fri, 29 Mar 2019 16:08:10 +1030 Subject: [PATCH 01/18] adpcm: modified the adpcm encoding and decoding to not use blocks --- audio/adpcm/adpcm.go | 50 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/audio/adpcm/adpcm.go b/audio/adpcm/adpcm.go index 595728a2..3e1f48f1 100644 --- a/audio/adpcm/adpcm.go +++ b/audio/adpcm/adpcm.go @@ -300,15 +300,20 @@ func (d *decoder) decodeBlock(block []byte) (int, error) { // It writes its output to the encoder's dest. // The number of bytes written out is returned along with any error that occured. func (e *encoder) Write(inPcm []byte) (int, error) { - numBlocks := len(inPcm) / PcmBS - n := 0 - for i := 0; i < numBlocks; i++ { - block := inPcm[PcmBS*i : PcmBS*(i+1)] - _n, err := e.encodeBlock(block) - n += _n + + n, err := e.calcHead(inPcm[0:2]) + if err != nil { + return n, err + } + + for i := 3; i < len(inPcm); i += 4 { + nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i-1 : i+1]))) + nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i+1 : i+3]))) + err = e.dest.WriteByte(byte((nib2 << 4) | nib1)) if err != nil { return n, err } + n++ } return n, nil @@ -318,11 +323,34 @@ func (e *encoder) Write(inPcm []byte) (int, error) { // It writes its output to the decoder's dest. // The number of bytes written out is returned along with any error that occured. func (d *decoder) Write(inAdpcm []byte) (int, error) { - numBlocks := len(inAdpcm) / AdpcmBS - n := 0 - for i := 0; i < numBlocks; i++ { - block := inAdpcm[AdpcmBS*i : AdpcmBS*(i+1)] - _n, err := d.decodeBlock(block) + + // Initialize decoder with first 4 bytes of the inAdpcm. + d.pred = int16(binary.LittleEndian.Uint16(inAdpcm[0:2])) + d.index = int16(inAdpcm[2]) + d.step = stepTable[d.index] + n, err := d.dest.Write(inAdpcm[0:2]) + if err != nil { + return n, err + } + + // For each byte, seperate it into two nibbles (each nibble is a compressed sample), + // then decode each nibble and output the resulting 16-bit samples. + for i := 4; i < len(inAdpcm); i++ { + twoNibs := inAdpcm[i] + nib2 := byte(twoNibs >> 4) + nib1 := byte((nib2 << 4) ^ twoNibs) + + firstBytes := make([]byte, 2) + binary.LittleEndian.PutUint16(firstBytes, uint16(d.decodeSample(nib1))) + _n, err := d.dest.Write(firstBytes) + n += _n + if err != nil { + return n, err + } + + secondBytes := make([]byte, 2) + binary.LittleEndian.PutUint16(secondBytes, uint16(d.decodeSample(nib2))) + _n, err = d.dest.Write(secondBytes) n += _n if err != nil { return n, err From d136d13e38f3071530adabbec0db6ee76e38bc19 Mon Sep 17 00:00:00 2001 From: Trek H Date: Fri, 29 Mar 2019 16:08:10 +1030 Subject: [PATCH 02/18] adpcm: modified the adpcm encoding and decoding to not use blocks --- codec/adpcm/adpcm.go | 50 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 595728a2..3e1f48f1 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -300,15 +300,20 @@ func (d *decoder) decodeBlock(block []byte) (int, error) { // It writes its output to the encoder's dest. // The number of bytes written out is returned along with any error that occured. func (e *encoder) Write(inPcm []byte) (int, error) { - numBlocks := len(inPcm) / PcmBS - n := 0 - for i := 0; i < numBlocks; i++ { - block := inPcm[PcmBS*i : PcmBS*(i+1)] - _n, err := e.encodeBlock(block) - n += _n + + n, err := e.calcHead(inPcm[0:2]) + if err != nil { + return n, err + } + + for i := 3; i < len(inPcm); i += 4 { + nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i-1 : i+1]))) + nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i+1 : i+3]))) + err = e.dest.WriteByte(byte((nib2 << 4) | nib1)) if err != nil { return n, err } + n++ } return n, nil @@ -318,11 +323,34 @@ func (e *encoder) Write(inPcm []byte) (int, error) { // It writes its output to the decoder's dest. // The number of bytes written out is returned along with any error that occured. func (d *decoder) Write(inAdpcm []byte) (int, error) { - numBlocks := len(inAdpcm) / AdpcmBS - n := 0 - for i := 0; i < numBlocks; i++ { - block := inAdpcm[AdpcmBS*i : AdpcmBS*(i+1)] - _n, err := d.decodeBlock(block) + + // Initialize decoder with first 4 bytes of the inAdpcm. + d.pred = int16(binary.LittleEndian.Uint16(inAdpcm[0:2])) + d.index = int16(inAdpcm[2]) + d.step = stepTable[d.index] + n, err := d.dest.Write(inAdpcm[0:2]) + if err != nil { + return n, err + } + + // For each byte, seperate it into two nibbles (each nibble is a compressed sample), + // then decode each nibble and output the resulting 16-bit samples. + for i := 4; i < len(inAdpcm); i++ { + twoNibs := inAdpcm[i] + nib2 := byte(twoNibs >> 4) + nib1 := byte((nib2 << 4) ^ twoNibs) + + firstBytes := make([]byte, 2) + binary.LittleEndian.PutUint16(firstBytes, uint16(d.decodeSample(nib1))) + _n, err := d.dest.Write(firstBytes) + n += _n + if err != nil { + return n, err + } + + secondBytes := make([]byte, 2) + binary.LittleEndian.PutUint16(secondBytes, uint16(d.decodeSample(nib2))) + _n, err = d.dest.Write(secondBytes) n += _n if err != nil { return n, err From e55cc27a554b7dfa44d779bd564b552aa8f73f62 Mon Sep 17 00:00:00 2001 From: Trek H Date: Fri, 26 Apr 2019 19:58:30 +0930 Subject: [PATCH 03/18] adpcm: changed adpcm to not have blocks of fixed size --- codec/adpcm/adpcm.go | 43 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 3e1f48f1..f32c8875 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -193,7 +193,7 @@ func (d *decoder) decodeSample(nibble byte) int16 { // calcHead sets the state for the encoder by running the first sample through // the encoder, and writing the first sample to the encoder's io.Writer (dest). // It returns the number of bytes written to the encoder's io.Writer (dest) along with any errors. -func (e *encoder) calcHead(sample []byte) (int, error) { +func (e *encoder) calcHead(sample []byte, pad bool) (int, error) { // Check that we are given 1 16-bit sample (2 bytes). const sampSize = 2 if len(sample) != sampSize { @@ -214,7 +214,11 @@ func (e *encoder) calcHead(sample []byte) (int, error) { } n++ - err = e.dest.WriteByte(byte(0x00)) + if pad { + err = e.dest.WriteByte(0x01) + } else { + err = e.dest.WriteByte(0x00) + } if err != nil { return n, err } @@ -234,7 +238,7 @@ func (e *encoder) encodeBlock(block []byte) (int, error) { return 0, fmt.Errorf("unsupported block size. Given: %v, expected: %v, ie. 505 16-bit PCM samples", len(block), PcmBS) } - n, err := e.calcHead(block[0:2]) + n, err := e.calcHead(block[0:2], false) if err != nil { return n, err } @@ -300,13 +304,19 @@ func (d *decoder) decodeBlock(block []byte) (int, error) { // It writes its output to the encoder's dest. // The number of bytes written out is returned along with any error that occured. func (e *encoder) Write(inPcm []byte) (int, error) { + // Determine if there will be a byte that won't contain two full nibbles and will need padding. + pcmLen := len(inPcm) + pad := false + if (pcmLen-2)%4 != 0 { + pad = true + } - n, err := e.calcHead(inPcm[0:2]) + n, err := e.calcHead(inPcm[0:2], pad) if err != nil { return n, err } - for i := 3; i < len(inPcm); i += 4 { + for i := 3; i < pcmLen; i += 4 { nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i-1 : i+1]))) nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i+1 : i+3]))) err = e.dest.WriteByte(byte((nib2 << 4) | nib1)) @@ -315,6 +325,16 @@ func (e *encoder) Write(inPcm []byte) (int, error) { } n++ } + // If we've reached the end of the pcm data and there's a sample (2 bytes) left over, + // compress it to a nibble and leave the first half of the byte padded with 0s. + if pad { + nib := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[pcmLen-2 : pcmLen]))) + err = e.dest.WriteByte(nib) + if err != nil { + return n, err + } + n++ + } return n, nil } @@ -335,7 +355,8 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { // For each byte, seperate it into two nibbles (each nibble is a compressed sample), // then decode each nibble and output the resulting 16-bit samples. - for i := 4; i < len(inAdpcm); i++ { + // If padding flag is true (Adpcm[3]), only decode up until the last byte, then decode that separately. + for i := 4; i < len(inAdpcm)-int(inAdpcm[3]); i++ { twoNibs := inAdpcm[i] nib2 := byte(twoNibs >> 4) nib1 := byte((nib2 << 4) ^ twoNibs) @@ -356,6 +377,16 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { return n, err } } + if inAdpcm[3] == 0x01 { + padNib := inAdpcm[len(inAdpcm)-1] + samp := make([]byte, 2) + binary.LittleEndian.PutUint16(samp, uint16(d.decodeSample(padNib))) + _n, err := d.dest.Write(samp) + n += _n + if err != nil { + return n, err + } + } return n, nil } From a9b1891bbb0227110e1c922a7a05bf02361a4afa Mon Sep 17 00:00:00 2001 From: Trek H Date: Fri, 26 Apr 2019 20:02:38 +0930 Subject: [PATCH 04/18] adpcm: fixed merge error --- codec/adpcm/adpcm.go | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 350d4e42..f32c8875 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -304,7 +304,6 @@ func (d *decoder) decodeBlock(block []byte) (int, error) { // It writes its output to the encoder's dest. // The number of bytes written out is returned along with any error that occured. func (e *encoder) Write(inPcm []byte) (int, error) { -<<<<<<< HEAD:codec/adpcm/adpcm.go // Determine if there will be a byte that won't contain two full nibbles and will need padding. pcmLen := len(inPcm) pad := false @@ -313,15 +312,10 @@ func (e *encoder) Write(inPcm []byte) (int, error) { } n, err := e.calcHead(inPcm[0:2], pad) -======= - - n, err := e.calcHead(inPcm[0:2]) ->>>>>>> 2600fa884f6d71d325dfad995cc1d053106a88d6:audio/adpcm/adpcm.go if err != nil { return n, err } -<<<<<<< HEAD:codec/adpcm/adpcm.go for i := 3; i < pcmLen; i += 4 { nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i-1 : i+1]))) nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i+1 : i+3]))) @@ -336,12 +330,6 @@ func (e *encoder) Write(inPcm []byte) (int, error) { if pad { nib := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[pcmLen-2 : pcmLen]))) err = e.dest.WriteByte(nib) -======= - for i := 3; i < len(inPcm); i += 4 { - nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i-1 : i+1]))) - nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i+1 : i+3]))) - err = e.dest.WriteByte(byte((nib2 << 4) | nib1)) ->>>>>>> 2600fa884f6d71d325dfad995cc1d053106a88d6:audio/adpcm/adpcm.go if err != nil { return n, err } @@ -367,12 +355,8 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { // For each byte, seperate it into two nibbles (each nibble is a compressed sample), // then decode each nibble and output the resulting 16-bit samples. -<<<<<<< HEAD:codec/adpcm/adpcm.go // If padding flag is true (Adpcm[3]), only decode up until the last byte, then decode that separately. for i := 4; i < len(inAdpcm)-int(inAdpcm[3]); i++ { -======= - for i := 4; i < len(inAdpcm); i++ { ->>>>>>> 2600fa884f6d71d325dfad995cc1d053106a88d6:audio/adpcm/adpcm.go twoNibs := inAdpcm[i] nib2 := byte(twoNibs >> 4) nib1 := byte((nib2 << 4) ^ twoNibs) @@ -388,7 +372,6 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { secondBytes := make([]byte, 2) binary.LittleEndian.PutUint16(secondBytes, uint16(d.decodeSample(nib2))) _n, err = d.dest.Write(secondBytes) -<<<<<<< HEAD:codec/adpcm/adpcm.go n += _n if err != nil { return n, err @@ -399,8 +382,6 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { samp := make([]byte, 2) binary.LittleEndian.PutUint16(samp, uint16(d.decodeSample(padNib))) _n, err := d.dest.Write(samp) -======= ->>>>>>> 2600fa884f6d71d325dfad995cc1d053106a88d6:audio/adpcm/adpcm.go n += _n if err != nil { return n, err From c089980175afabdc7694c7829fe6334dc3df9311 Mon Sep 17 00:00:00 2001 From: Trek H Date: Fri, 26 Apr 2019 20:28:53 +0930 Subject: [PATCH 05/18] adpcm: added function for calculating number of adpcm bytes output per given pcm bytes --- codec/adpcm/adpcm.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index f32c8875..58942f74 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -390,3 +390,10 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { return n, nil } + +// BytesOutput will return the number of adpcm bytes that will be generated for the given pcm data +func BytesOutput(pcm int) int { + // for X pcm bytes, 2 bytes are left uncompressed, the rest is compressed by a factor of 4 + // and a start index and padding byte are added. + return (pcm-2)/4 + 2 + 1 + 1 +} From b412b75fc6a795a3640af95e81a13c36b3fb49a6 Mon Sep 17 00:00:00 2001 From: Trek H Date: Fri, 26 Apr 2019 23:54:05 +0930 Subject: [PATCH 06/18] adpcm: fixing offset error --- codec/adpcm/adpcm.go | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 58942f74..6f30ecd1 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -315,10 +315,11 @@ func (e *encoder) Write(inPcm []byte) (int, error) { if err != nil { return n, err } - - for i := 3; i < pcmLen; i += 4 { - nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i-1 : i+1]))) - nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i+1 : i+3]))) + // Skip the first sample and start at the end of the first two samples, then every two samples encode them into a byte of adpcm. + // TODO: make all hard coded numbers variables so that other bitrates and compression ratios can be used. + for i := 5; i < pcmLen; i += 4 { + nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i-3 : i-1]))) + nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i-1 : i+1]))) err = e.dest.WriteByte(byte((nib2 << 4) | nib1)) if err != nil { return n, err @@ -335,7 +336,6 @@ func (e *encoder) Write(inPcm []byte) (int, error) { } n++ } - return n, nil } @@ -343,7 +343,6 @@ func (e *encoder) Write(inPcm []byte) (int, error) { // It writes its output to the decoder's dest. // The number of bytes written out is returned along with any error that occured. func (d *decoder) Write(inAdpcm []byte) (int, error) { - // Initialize decoder with first 4 bytes of the inAdpcm. d.pred = int16(binary.LittleEndian.Uint16(inAdpcm[0:2])) d.index = int16(inAdpcm[2]) @@ -387,11 +386,10 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { return n, err } } - return n, nil } -// BytesOutput will return the number of adpcm bytes that will be generated for the given pcm data +// BytesOutput will return the number of adpcm bytes that will be generated for the given pcm data byte size. func BytesOutput(pcm int) int { // for X pcm bytes, 2 bytes are left uncompressed, the rest is compressed by a factor of 4 // and a start index and padding byte are added. From d06388cfe9a6fd99d52546876c1b861245fcd54d Mon Sep 17 00:00:00 2001 From: Trek H Date: Wed, 1 May 2019 23:53:08 +0930 Subject: [PATCH 07/18] adpcm: added overflow checks, improved initialization, naming --- codec/adpcm/adpcm.go | 144 +++++++++++++++---------------------------- 1 file changed, 50 insertions(+), 94 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 6f30ecd1..3b02f1ac 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -36,23 +36,24 @@ import ( "bytes" "encoding/binary" "fmt" + "math" ) // encoder is used to encode to ADPCM from PCM data. -// pred and index hold state that persists between calls to encodeSample and calcHead. +// est and index hold state that persists between calls to encodeSample and calcHead. // dest is the output buffer that implements io.writer and io.bytewriter, ie. where the encoded ADPCM data is written to. type encoder struct { dest *bytes.Buffer - pred int16 + est int16 index int16 } // decoder is used to decode from ADPCM to PCM data. -// pred, index, and step hold state that persists between calls to decodeSample. +// est, index, and step hold state that persists between calls to decodeSample. // dest is the output buffer that implements io.writer and io.bytewriter, ie. where the decoded PCM data is written to. type decoder struct { dest *bytes.Buffer - pred int16 + est int16 index int16 step int16 } @@ -98,7 +99,6 @@ func NewEncoder(dst *bytes.Buffer) *encoder { // NewDecoder retuns a new ADPCM decoder. func NewDecoder(dst *bytes.Buffer) *decoder { d := decoder{ - step: stepTable[0], dest: dst, } return &d @@ -107,8 +107,8 @@ func NewDecoder(dst *bytes.Buffer) *decoder { // encodeSample takes a single 16 bit PCM sample and // returns a byte of which the last 4 bits are an encoded ADPCM nibble. func (e *encoder) encodeSample(sample int16) byte { - // Find difference of actual sample from encoder's prediction. - delta := sample - e.pred + // Find difference between the sample and the previous estimation. + delta := capAdd16(sample, -e.est) // Create and set sign bit for nibble and find absolute value of difference. var nib byte @@ -124,20 +124,20 @@ func (e *encoder) encodeSample(sample int16) byte { for i := 0; i < 3; i++ { if delta > step { nib |= mask - delta -= step - diff += step + delta = capAdd16(delta, -step) + diff = capAdd16(diff, step) } mask >>= 1 step >>= 1 } - // Adjust predicted sample based on calculated difference. if nib&8 != 0 { - e.pred -= diff - } else { - e.pred += diff + diff = -diff } + // Adjust estimated sample based on calculated difference. + e.est = capAdd16(e.est, diff) + e.index += indexTable[nib&7] // Check for underflow and overflow. @@ -156,23 +156,23 @@ func (d *decoder) decodeSample(nibble byte) int16 { // Calculate difference. var diff int16 if nibble&4 != 0 { - diff += d.step + diff = capAdd16(diff, d.step) } if nibble&2 != 0 { - diff += d.step >> 1 + diff = capAdd16(diff, d.step>>1) } if nibble&1 != 0 { - diff += d.step >> 2 + diff = capAdd16(diff, d.step>>2) } - diff += d.step >> 3 + diff = capAdd16(diff, d.step>>3) // Account for sign bit. if nibble&8 != 0 { diff = -diff } - // Adjust predicted sample based on calculated difference. - d.pred += diff + // Adjust estimated sample based on calculated difference. + d.est = capAdd16(d.est, diff) // Adjust index into step size lookup table using nibble. d.index += indexTable[nibble] @@ -187,7 +187,20 @@ func (d *decoder) decodeSample(nibble byte) int16 { // Find new quantizer step size. d.step = stepTable[d.index] - return d.pred + return d.est +} + +// capAdd16 adds two int16s together and caps at max/min int16 instead of overflowing +func capAdd16(a, b int16) int16 { + c := int32(a) + int32(b) + switch { + case c < math.MinInt16: + return math.MinInt16 + case c > math.MaxInt16: + return math.MaxInt16 + default: + return int16(c) + } } // calcHead sets the state for the encoder by running the first sample through @@ -200,15 +213,12 @@ func (e *encoder) calcHead(sample []byte, pad bool) (int, error) { return 0, fmt.Errorf("length of given byte array is: %v, expected: %v", len(sample), sampSize) } - intSample := int16(binary.LittleEndian.Uint16(sample)) - e.encodeSample(intSample) - n, err := e.dest.Write(sample) if err != nil { return n, err } - err = e.dest.WriteByte(byte(uint16(e.index))) + err = e.dest.WriteByte(byte(int16(e.index))) if err != nil { return n, err } @@ -226,78 +236,23 @@ func (e *encoder) calcHead(sample []byte, pad bool) (int, error) { return n, nil } -// encodeBlock takes a slice of 1010 bytes (505 16-bit PCM samples). -// It writes encoded (compressed) bytes (each byte containing two ADPCM nibbles) to the encoder's io.Writer (dest). -// The number of bytes written is returned along with any errors. -// Note: nibbles are output in little endian order, eg. n1n0 n3n2 n5n4... -// Note: first 4 bytes are for initializing the decoder before decoding a block. -// - First two bytes contain the first 16-bit sample uncompressed. -// - Third byte is the decoder's starting index for the block, the fourth is padding and ignored. -func (e *encoder) encodeBlock(block []byte) (int, error) { - if len(block) != PcmBS { - return 0, fmt.Errorf("unsupported block size. Given: %v, expected: %v, ie. 505 16-bit PCM samples", len(block), PcmBS) - } +// init initializes the encoder's estimation to the first uncompressed sample and the index to +// point to a suitable quantizer step size. +func (e *encoder) init(samps []byte) { + int1 := int16(binary.LittleEndian.Uint16(samps[0:2])) + int2 := int16(binary.LittleEndian.Uint16(samps[2:4])) + e.est = int1 - n, err := e.calcHead(block[0:2], false) - if err != nil { - return n, err - } - - for i := 3; i < PcmBS; i += 4 { - nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(block[i-1 : i+1]))) - nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(block[i+1 : i+3]))) - err = e.dest.WriteByte(byte((nib2 << 4) | nib1)) - if err != nil { - return n, err - } - n++ - } - - return n, nil -} - -// decodeBlock takes a slice of 256 bytes, each byte after the first 4 should contain two ADPCM encoded nibbles. -// It writes the resulting decoded (decompressed) 16-bit PCM samples to the decoder's io.Writer (dest). -// The number of bytes written is returned along with any errors. -func (d *decoder) decodeBlock(block []byte) (int, error) { - if len(block) != AdpcmBS { - return 0, fmt.Errorf("unsupported block size. Given: %v, expected: %v", len(block), AdpcmBS) - } - - // Initialize decoder with first 4 bytes of the block. - d.pred = int16(binary.LittleEndian.Uint16(block[0:2])) - d.index = int16(block[2]) - d.step = stepTable[d.index] - n, err := d.dest.Write(block[0:2]) - if err != nil { - return n, err - } - - // For each byte, seperate it into two nibbles (each nibble is a compressed sample), - // then decode each nibble and output the resulting 16-bit samples. - for i := 4; i < AdpcmBS; i++ { - twoNibs := block[i] - nib2 := byte(twoNibs >> 4) - nib1 := byte((nib2 << 4) ^ twoNibs) - - firstBytes := make([]byte, 2) - binary.LittleEndian.PutUint16(firstBytes, uint16(d.decodeSample(nib1))) - _n, err := d.dest.Write(firstBytes) - n += _n - if err != nil { - return n, err - } - - secondBytes := make([]byte, 2) - binary.LittleEndian.PutUint16(secondBytes, uint16(d.decodeSample(nib2))) - _n, err = d.dest.Write(secondBytes) - n += _n - if err != nil { - return n, err + halfDiff := math.Abs(math.Abs(float64(int1)) - math.Abs(float64(int2))/2.0) + closest := math.Abs(float64(stepTable[0]) - halfDiff) + var cInd int16 + for i, step := range stepTable { + if math.Abs(float64(step)-halfDiff) < closest { + closest = math.Abs(float64(step) - halfDiff) + cInd = int16(i) } } - - return n, nil + e.index = cInd } // Write takes a slice of bytes of arbitrary length representing pcm and encodes in into adpcm. @@ -311,6 +266,7 @@ func (e *encoder) Write(inPcm []byte) (int, error) { pad = true } + e.init(inPcm[0:4]) n, err := e.calcHead(inPcm[0:2], pad) if err != nil { return n, err @@ -344,7 +300,7 @@ func (e *encoder) Write(inPcm []byte) (int, error) { // The number of bytes written out is returned along with any error that occured. func (d *decoder) Write(inAdpcm []byte) (int, error) { // Initialize decoder with first 4 bytes of the inAdpcm. - d.pred = int16(binary.LittleEndian.Uint16(inAdpcm[0:2])) + d.est = int16(binary.LittleEndian.Uint16(inAdpcm[0:2])) d.index = int16(inAdpcm[2]) d.step = stepTable[d.index] n, err := d.dest.Write(inAdpcm[0:2]) From ef9a38cb762cecd5aa3319168c064a0048d15562 Mon Sep 17 00:00:00 2001 From: Trek H Date: Thu, 2 May 2019 00:02:33 +0930 Subject: [PATCH 08/18] adpcm: length check before initialization --- codec/adpcm/adpcm.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 3b02f1ac..e152ede7 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -259,8 +259,13 @@ func (e *encoder) init(samps []byte) { // It writes its output to the encoder's dest. // The number of bytes written out is returned along with any error that occured. func (e *encoder) Write(inPcm []byte) (int, error) { - // Determine if there will be a byte that won't contain two full nibbles and will need padding. + // Check that pcm has enough data to initialize decoder pcmLen := len(inPcm) + if pcmLen < 4 { + return 0, fmt.Errorf("length of given byte array must be greater than 4") + } + + // Determine if there will be a byte that won't contain two full nibbles and will need padding. pad := false if (pcmLen-2)%4 != 0 { pad = true From 60d789e697254397ed7a3b49d0adcea7fb3c0911 Mon Sep 17 00:00:00 2001 From: Trek H Date: Sun, 5 May 2019 18:08:50 +0930 Subject: [PATCH 09/18] adpcm: updated tests to use new test files --- codec/adpcm/adpcm_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/codec/adpcm/adpcm_test.go b/codec/adpcm/adpcm_test.go index 9df24028..9c89221b 100644 --- a/codec/adpcm/adpcm_test.go +++ b/codec/adpcm/adpcm_test.go @@ -37,7 +37,7 @@ import ( // then compare the result with expected ADPCM. func TestEncodeBlock(t *testing.T) { // Read input pcm. - pcm, err := ioutil.ReadFile("../../../test/test-data/av/input/raw-voice.pcm") + pcm, err := ioutil.ReadFile("../../../test/test-data/av/input/original_8kHz_adpcm_test.pcm") if err != nil { t.Errorf("Unable to read input PCM file: %v", err) } @@ -52,7 +52,7 @@ func TestEncodeBlock(t *testing.T) { } // Read expected adpcm file. - exp, err := ioutil.ReadFile("../../../test/test-data/av/output/encoded-voice.adpcm") + exp, err := ioutil.ReadFile("../../../test/test-data/av/output/encoded_8kHz_adpcm_test.adpcm") if err != nil { t.Errorf("Unable to read expected ADPCM file: %v", err) } @@ -66,7 +66,7 @@ func TestEncodeBlock(t *testing.T) { // resulting PCM with the expected decoded PCM. func TestDecodeBlock(t *testing.T) { // Read adpcm. - comp, err := ioutil.ReadFile("../../../test/test-data/av/input/encoded-voice.adpcm") + comp, err := ioutil.ReadFile("../../../test/test-data/av/input/encoded_8kHz_adpcm_test.adpcm") if err != nil { t.Errorf("Unable to read input ADPCM file: %v", err) } @@ -81,7 +81,7 @@ func TestDecodeBlock(t *testing.T) { } // Read expected pcm file. - exp, err := ioutil.ReadFile("../../../test/test-data/av/output/decoded-voice.pcm") + exp, err := ioutil.ReadFile("../../../test/test-data/av/output/decoded_8kHz_adpcm_test.pcm") if err != nil { t.Errorf("Unable to read expected PCM file: %v", err) } From c27a726831695b6f86e8614211ec04944a4c1a87 Mon Sep 17 00:00:00 2001 From: Trek H Date: Sun, 5 May 2019 18:46:03 +0930 Subject: [PATCH 10/18] adpcm: updated BytesOutput function to account for padding --- codec/adpcm/adpcm.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index e152ede7..d4f08ddf 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -352,7 +352,12 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { // BytesOutput will return the number of adpcm bytes that will be generated for the given pcm data byte size. func BytesOutput(pcm int) int { - // for X pcm bytes, 2 bytes are left uncompressed, the rest is compressed by a factor of 4 - // and a start index and padding byte are added. - return (pcm-2)/4 + 2 + 1 + 1 + // for X pcm bytes, byteDepth (eg. 2 bytes) are left uncompressed, the rest is compressed by a factor of 4 + // and a start index and padding-flag byte are added. + // Also if there are an even number of samples, there will be half a byte of padding added to the last byte. + byteDepth := 2 + if pcm%2*byteDepth == 0 { // %2 because samples are encoded 2 at a time. + return (pcm-byteDepth)/4 + byteDepth + 1 + 1 + 1 + } + return (pcm-byteDepth)/4 + byteDepth + 1 + 1 } From 0570d7823d27be0e1ffdeb4f271414caff779156 Mon Sep 17 00:00:00 2001 From: Trek H Date: Mon, 6 May 2019 17:56:34 +0930 Subject: [PATCH 11/18] adpcm: using consts where needed --- codec/adpcm/adpcm.go | 115 ++++++++++++++++++++++++------------------- 1 file changed, 63 insertions(+), 52 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index d4f08ddf..4d426ba7 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -30,6 +30,7 @@ LICENSE Reference algorithms for ADPCM compression and decompression are in part 6. */ +// Package adpcm provides encoder and decoder structs to encode and decode PCM to and from ADPCM. package adpcm import ( @@ -39,20 +40,32 @@ import ( "math" ) +const ( + byteDepth = 2 // TODO(Trek): make configurable. + initSamps = 2 + initBytes = initSamps * byteDepth + headBytes = 4 + sampsPerEnc = 2 + bytesPerEnc = sampsPerEnc * byteDepth + compFact = 4 +) + // encoder is used to encode to ADPCM from PCM data. -// est and index hold state that persists between calls to encodeSample and calcHead. -// dest is the output buffer that implements io.writer and io.bytewriter, ie. where the encoded ADPCM data is written to. type encoder struct { - dest *bytes.Buffer + // dst is the output buffer that implements io.writer and io.bytewriter, ie. where the encoded ADPCM data is written to. + dst *bytes.Buffer + + // est and index hold state that persists between calls to encodeSample and calcHead. est int16 index int16 } // decoder is used to decode from ADPCM to PCM data. -// est, index, and step hold state that persists between calls to decodeSample. -// dest is the output buffer that implements io.writer and io.bytewriter, ie. where the decoded PCM data is written to. type decoder struct { - dest *bytes.Buffer + // dst is the output buffer that implements io.writer and io.bytewriter, ie. where the decoded PCM data is written to. + dst *bytes.Buffer + + // est, index, and step hold state that persists between calls to decodeSample. est int16 index int16 step int16 @@ -91,7 +104,7 @@ var stepTable = []int16{ // NewEncoder retuns a new ADPCM encoder. func NewEncoder(dst *bytes.Buffer) *encoder { e := encoder{ - dest: dst, + dst: dst, } return &e } @@ -99,7 +112,7 @@ func NewEncoder(dst *bytes.Buffer) *encoder { // NewDecoder retuns a new ADPCM decoder. func NewDecoder(dst *bytes.Buffer) *decoder { d := decoder{ - dest: dst, + dst: dst, } return &d } @@ -204,30 +217,29 @@ func capAdd16(a, b int16) int16 { } // calcHead sets the state for the encoder by running the first sample through -// the encoder, and writing the first sample to the encoder's io.Writer (dest). -// It returns the number of bytes written to the encoder's io.Writer (dest) along with any errors. +// the encoder, and writing the first sample to the encoder's io.Writer (dst). +// It returns the number of bytes written to the encoder's io.Writer (dst) along with any errors. func (e *encoder) calcHead(sample []byte, pad bool) (int, error) { - // Check that we are given 1 16-bit sample (2 bytes). - const sampSize = 2 - if len(sample) != sampSize { - return 0, fmt.Errorf("length of given byte array is: %v, expected: %v", len(sample), sampSize) + // Check that we are given 1 sample. + if len(sample) != byteDepth { + return 0, fmt.Errorf("length of given byte array is: %v, expected: %v", len(sample), byteDepth) } - n, err := e.dest.Write(sample) + n, err := e.dst.Write(sample) if err != nil { return n, err } - err = e.dest.WriteByte(byte(int16(e.index))) + err = e.dst.WriteByte(byte(int16(e.index))) if err != nil { return n, err } n++ if pad { - err = e.dest.WriteByte(0x01) + err = e.dst.WriteByte(0x01) } else { - err = e.dest.WriteByte(0x00) + err = e.dst.WriteByte(0x00) } if err != nil { return n, err @@ -238,9 +250,10 @@ func (e *encoder) calcHead(sample []byte, pad bool) (int, error) { // init initializes the encoder's estimation to the first uncompressed sample and the index to // point to a suitable quantizer step size. +// The suitable step size is the closest step size in the stepTable to half the absolute difference of the first two samples. func (e *encoder) init(samps []byte) { - int1 := int16(binary.LittleEndian.Uint16(samps[0:2])) - int2 := int16(binary.LittleEndian.Uint16(samps[2:4])) + int1 := int16(binary.LittleEndian.Uint16(samps[:byteDepth])) + int2 := int16(binary.LittleEndian.Uint16(samps[byteDepth:initBytes])) e.est = int1 halfDiff := math.Abs(math.Abs(float64(int1)) - math.Abs(float64(int2))/2.0) @@ -255,43 +268,42 @@ func (e *encoder) init(samps []byte) { e.index = cInd } -// Write takes a slice of bytes of arbitrary length representing pcm and encodes in into adpcm. -// It writes its output to the encoder's dest. +// Write takes a slice of bytes of arbitrary length representing pcm and encodes it into adpcm. +// It writes its output to the encoder's dst. // The number of bytes written out is returned along with any error that occured. func (e *encoder) Write(inPcm []byte) (int, error) { - // Check that pcm has enough data to initialize decoder + // Check that pcm has enough data to initialize decoder. pcmLen := len(inPcm) - if pcmLen < 4 { - return 0, fmt.Errorf("length of given byte array must be greater than 4") + if pcmLen < initBytes { + return 0, fmt.Errorf("length of given byte array must be >= %v", initBytes) } // Determine if there will be a byte that won't contain two full nibbles and will need padding. pad := false - if (pcmLen-2)%4 != 0 { + if (pcmLen-byteDepth)%bytesPerEnc != 0 { pad = true } - e.init(inPcm[0:4]) - n, err := e.calcHead(inPcm[0:2], pad) + e.init(inPcm[:initBytes]) + n, err := e.calcHead(inPcm[:byteDepth], pad) if err != nil { return n, err } // Skip the first sample and start at the end of the first two samples, then every two samples encode them into a byte of adpcm. - // TODO: make all hard coded numbers variables so that other bitrates and compression ratios can be used. - for i := 5; i < pcmLen; i += 4 { - nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i-3 : i-1]))) - nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i-1 : i+1]))) - err = e.dest.WriteByte(byte((nib2 << 4) | nib1)) + for i := byteDepth; i+bytesPerEnc-1 < pcmLen; i += bytesPerEnc { + nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i : i+byteDepth]))) + nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i+byteDepth : i+bytesPerEnc]))) + err = e.dst.WriteByte(byte((nib2 << 4) | nib1)) if err != nil { return n, err } n++ } - // If we've reached the end of the pcm data and there's a sample (2 bytes) left over, + // If we've reached the end of the pcm data and there's a sample left over, // compress it to a nibble and leave the first half of the byte padded with 0s. if pad { - nib := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[pcmLen-2 : pcmLen]))) - err = e.dest.WriteByte(nib) + nib := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[pcmLen-byteDepth : pcmLen]))) + err = e.dst.WriteByte(nib) if err != nil { return n, err } @@ -300,15 +312,15 @@ func (e *encoder) Write(inPcm []byte) (int, error) { return n, nil } -// Write takes a slice of bytes of arbitrary length representing adpcm and decodes in into pcm. -// It writes its output to the decoder's dest. +// Write takes a slice of bytes of arbitrary length representing adpcm and decodes it into pcm. +// It writes its output to the decoder's dst. // The number of bytes written out is returned along with any error that occured. func (d *decoder) Write(inAdpcm []byte) (int, error) { // Initialize decoder with first 4 bytes of the inAdpcm. - d.est = int16(binary.LittleEndian.Uint16(inAdpcm[0:2])) - d.index = int16(inAdpcm[2]) + d.est = int16(binary.LittleEndian.Uint16(inAdpcm[:byteDepth])) + d.index = int16(inAdpcm[byteDepth]) d.step = stepTable[d.index] - n, err := d.dest.Write(inAdpcm[0:2]) + n, err := d.dst.Write(inAdpcm[:byteDepth]) if err != nil { return n, err } @@ -316,22 +328,22 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { // For each byte, seperate it into two nibbles (each nibble is a compressed sample), // then decode each nibble and output the resulting 16-bit samples. // If padding flag is true (Adpcm[3]), only decode up until the last byte, then decode that separately. - for i := 4; i < len(inAdpcm)-int(inAdpcm[3]); i++ { + for i := headBytes; i < len(inAdpcm)-int(inAdpcm[3]); i++ { twoNibs := inAdpcm[i] nib2 := byte(twoNibs >> 4) nib1 := byte((nib2 << 4) ^ twoNibs) - firstBytes := make([]byte, 2) + firstBytes := make([]byte, byteDepth) binary.LittleEndian.PutUint16(firstBytes, uint16(d.decodeSample(nib1))) - _n, err := d.dest.Write(firstBytes) + _n, err := d.dst.Write(firstBytes) n += _n if err != nil { return n, err } - secondBytes := make([]byte, 2) + secondBytes := make([]byte, byteDepth) binary.LittleEndian.PutUint16(secondBytes, uint16(d.decodeSample(nib2))) - _n, err = d.dest.Write(secondBytes) + _n, err = d.dst.Write(secondBytes) n += _n if err != nil { return n, err @@ -339,9 +351,9 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { } if inAdpcm[3] == 0x01 { padNib := inAdpcm[len(inAdpcm)-1] - samp := make([]byte, 2) + samp := make([]byte, byteDepth) binary.LittleEndian.PutUint16(samp, uint16(d.decodeSample(padNib))) - _n, err := d.dest.Write(samp) + _n, err := d.dst.Write(samp) n += _n if err != nil { return n, err @@ -355,9 +367,8 @@ func BytesOutput(pcm int) int { // for X pcm bytes, byteDepth (eg. 2 bytes) are left uncompressed, the rest is compressed by a factor of 4 // and a start index and padding-flag byte are added. // Also if there are an even number of samples, there will be half a byte of padding added to the last byte. - byteDepth := 2 - if pcm%2*byteDepth == 0 { // %2 because samples are encoded 2 at a time. - return (pcm-byteDepth)/4 + byteDepth + 1 + 1 + 1 + if pcm%bytesPerEnc == 0 { + return (pcm-byteDepth)/compFact + headBytes + 1 } - return (pcm-byteDepth)/4 + byteDepth + 1 + 1 + return (pcm-byteDepth)/compFact + headBytes } From 9fadb47902eb19581f3724ed885546a72c4d5971 Mon Sep 17 00:00:00 2001 From: Trek H Date: Mon, 6 May 2019 18:02:17 +0930 Subject: [PATCH 12/18] adpcm: naming and documentation --- codec/adpcm/adpcm.go | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 4d426ba7..fb67b283 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -315,12 +315,12 @@ func (e *encoder) Write(inPcm []byte) (int, error) { // Write takes a slice of bytes of arbitrary length representing adpcm and decodes it into pcm. // It writes its output to the decoder's dst. // The number of bytes written out is returned along with any error that occured. -func (d *decoder) Write(inAdpcm []byte) (int, error) { - // Initialize decoder with first 4 bytes of the inAdpcm. - d.est = int16(binary.LittleEndian.Uint16(inAdpcm[:byteDepth])) - d.index = int16(inAdpcm[byteDepth]) +func (d *decoder) Write(chunk []byte) (int, error) { + // Initialize decoder with first 4 bytes of the chunk. + d.est = int16(binary.LittleEndian.Uint16(chunk[:byteDepth])) + d.index = int16(chunk[byteDepth]) d.step = stepTable[d.index] - n, err := d.dst.Write(inAdpcm[:byteDepth]) + n, err := d.dst.Write(chunk[:byteDepth]) if err != nil { return n, err } @@ -328,8 +328,8 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { // For each byte, seperate it into two nibbles (each nibble is a compressed sample), // then decode each nibble and output the resulting 16-bit samples. // If padding flag is true (Adpcm[3]), only decode up until the last byte, then decode that separately. - for i := headBytes; i < len(inAdpcm)-int(inAdpcm[3]); i++ { - twoNibs := inAdpcm[i] + for i := headBytes; i < len(chunk)-int(chunk[3]); i++ { + twoNibs := chunk[i] nib2 := byte(twoNibs >> 4) nib1 := byte((nib2 << 4) ^ twoNibs) @@ -349,8 +349,8 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { return n, err } } - if inAdpcm[3] == 0x01 { - padNib := inAdpcm[len(inAdpcm)-1] + if chunk[3] == 0x01 { + padNib := chunk[len(chunk)-1] samp := make([]byte, byteDepth) binary.LittleEndian.PutUint16(samp, uint16(d.decodeSample(padNib))) _n, err := d.dst.Write(samp) @@ -364,7 +364,7 @@ func (d *decoder) Write(inAdpcm []byte) (int, error) { // BytesOutput will return the number of adpcm bytes that will be generated for the given pcm data byte size. func BytesOutput(pcm int) int { - // for X pcm bytes, byteDepth (eg. 2 bytes) are left uncompressed, the rest is compressed by a factor of 4 + // For X pcm bytes, 1 sample is left uncompressed, the rest is compressed by a factor of 4 // and a start index and padding-flag byte are added. // Also if there are an even number of samples, there will be half a byte of padding added to the last byte. if pcm%bytesPerEnc == 0 { From 29e49a7a1caa2b344105f0e303f0addd1668276d Mon Sep 17 00:00:00 2001 From: Trek H Date: Wed, 8 May 2019 20:04:40 +0930 Subject: [PATCH 13/18] adpcm, pcm: updated documentation --- codec/adpcm/adpcm.go | 3 --- codec/pcm/pcm.go | 2 ++ exp/adpcm/decode-pcm/decode-pcm.go | 4 +--- exp/adpcm/encode-pcm/encode-pcm.go | 4 +--- exp/pcm/resample/resample.go | 5 ++--- exp/pcm/stereo-to-mono/stereo-to-mono.go | 5 ++--- 6 files changed, 8 insertions(+), 15 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index fb67b283..013a76ff 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -2,9 +2,6 @@ NAME adpcm.go -DESCRIPTION - adpcm.go contains functions for encoding/compressing pcm into adpcm and decoding/decompressing back to pcm. - AUTHOR Trek Hopton diff --git a/codec/pcm/pcm.go b/codec/pcm/pcm.go index 5ead3143..bb200d50 100644 --- a/codec/pcm/pcm.go +++ b/codec/pcm/pcm.go @@ -24,6 +24,8 @@ LICENSE You should have received a copy of the GNU General Public License in gpl.txt. If not, see [GNU licenses](http://www.gnu.org/licenses). */ + +// Package pcm provides functions for processing and converting pcm audio. package pcm import ( diff --git a/exp/adpcm/decode-pcm/decode-pcm.go b/exp/adpcm/decode-pcm/decode-pcm.go index 8d2bd7f6..5db6887c 100644 --- a/exp/adpcm/decode-pcm/decode-pcm.go +++ b/exp/adpcm/decode-pcm/decode-pcm.go @@ -2,9 +2,6 @@ NAME decode-pcm.go -DESCRIPTION - decode-pcm.go is a program for decoding/decompressing an adpcm file to a pcm file. - AUTHOR Trek Hopton @@ -25,6 +22,7 @@ LICENSE If not, see [GNU licenses](http://www.gnu.org/licenses). */ +// decode-pcm is a command-line program for decoding/decompressing an adpcm file to a pcm file. package main import ( diff --git a/exp/adpcm/encode-pcm/encode-pcm.go b/exp/adpcm/encode-pcm/encode-pcm.go index d283c822..69d42042 100644 --- a/exp/adpcm/encode-pcm/encode-pcm.go +++ b/exp/adpcm/encode-pcm/encode-pcm.go @@ -2,9 +2,6 @@ NAME encode-pcm.go -DESCRIPTION - encode-pcm.go is a program for encoding/compressing a pcm file to an adpcm file. - AUTHOR Trek Hopton @@ -25,6 +22,7 @@ LICENSE If not, see [GNU licenses](http://www.gnu.org/licenses). */ +// encode-pcm is a command-line program for encoding/compressing a pcm file to an adpcm file. package main import ( diff --git a/exp/pcm/resample/resample.go b/exp/pcm/resample/resample.go index eab7a342..3d595bb8 100644 --- a/exp/pcm/resample/resample.go +++ b/exp/pcm/resample/resample.go @@ -2,9 +2,6 @@ NAME resample.go -DESCRIPTION - resample.go is a program for resampling a pcm file. - AUTHOR Trek Hopton @@ -24,6 +21,8 @@ LICENSE You should have received a copy of the GNU General Public License in gpl.txt. If not, see [GNU licenses](http://www.gnu.org/licenses). */ + +// resample is a command-line program for resampling a pcm file. package main import ( diff --git a/exp/pcm/stereo-to-mono/stereo-to-mono.go b/exp/pcm/stereo-to-mono/stereo-to-mono.go index ccbf87bf..7dbfd9a5 100644 --- a/exp/pcm/stereo-to-mono/stereo-to-mono.go +++ b/exp/pcm/stereo-to-mono/stereo-to-mono.go @@ -2,9 +2,6 @@ NAME stereo-to-mono.go -DESCRIPTION - stereo-to-mono.go is a program for converting a mono pcm file to a stereo pcm file. - AUTHOR Trek Hopton @@ -24,6 +21,8 @@ LICENSE You should have received a copy of the GNU General Public License in gpl.txt. If not, see [GNU licenses](http://www.gnu.org/licenses). */ + +// stereo-to-mono is a command-line program for converting a mono pcm file to a stereo pcm file. package main import ( From a6d6a22b8248d2509634a83ac6dc7f3e7eeaa5b0 Mon Sep 17 00:00:00 2001 From: Trek H Date: Fri, 17 May 2019 00:52:36 +0930 Subject: [PATCH 14/18] adpcm: changed enc and dec to use io.Writer as dst also reordered encoder and decoder functions and remove old block consts --- codec/adpcm/adpcm.go | 206 ++++++++++++++++++-------------------- codec/adpcm/adpcm_test.go | 6 +- 2 files changed, 101 insertions(+), 111 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 013a76ff..7655f405 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -31,9 +31,9 @@ LICENSE package adpcm import ( - "bytes" "encoding/binary" "fmt" + "io" "math" ) @@ -47,35 +47,6 @@ const ( compFact = 4 ) -// encoder is used to encode to ADPCM from PCM data. -type encoder struct { - // dst is the output buffer that implements io.writer and io.bytewriter, ie. where the encoded ADPCM data is written to. - dst *bytes.Buffer - - // est and index hold state that persists between calls to encodeSample and calcHead. - est int16 - index int16 -} - -// decoder is used to decode from ADPCM to PCM data. -type decoder struct { - // dst is the output buffer that implements io.writer and io.bytewriter, ie. where the decoded PCM data is written to. - dst *bytes.Buffer - - // est, index, and step hold state that persists between calls to decodeSample. - est int16 - index int16 - step int16 -} - -// PcmBS is the size of the blocks that an encoder uses. -// 'encodeBlock' will encode PcmBS bytes at a time and the output will be AdpcmBS bytes long. -const PcmBS = 1010 - -// AdpcmBS is the size of the blocks that a decoder uses. -// 'decodeBlock' will decode AdpcmBS bytes at a time and the output will be PcmBS bytes long. -const AdpcmBS = 256 - // Table of index changes (see spec). var indexTable = []int16{ -1, -1, -1, -1, 2, 4, 6, 8, @@ -98,22 +69,35 @@ var stepTable = []int16{ 32767, } +// encoder is used to encode to ADPCM from PCM data. +type encoder struct { + // dst is the destination for encoded data. + dst io.Writer + + // est and index hold state that persists between calls to encodeSample and calcHead. + est int16 + index int16 +} + +// decoder is used to decode from ADPCM to PCM data. +type decoder struct { + // dst is the output buffer that implements io.Writer and io.Bytewriter, ie. where the decoded PCM data is written to. + dst io.Writer + + // est, index, and step hold state that persists between calls to decodeSample. + est int16 + index int16 + step int16 +} + // NewEncoder retuns a new ADPCM encoder. -func NewEncoder(dst *bytes.Buffer) *encoder { +func NewEncoder(dst io.Writer) *encoder { e := encoder{ dst: dst, } return &e } -// NewDecoder retuns a new ADPCM decoder. -func NewDecoder(dst *bytes.Buffer) *decoder { - d := decoder{ - dst: dst, - } - return &d -} - // encodeSample takes a single 16 bit PCM sample and // returns a byte of which the last 4 bits are an encoded ADPCM nibble. func (e *encoder) encodeSample(sample int16) byte { @@ -160,59 +144,6 @@ func (e *encoder) encodeSample(sample int16) byte { return nib } -// decodeSample takes a byte, the last 4 bits of which contain a single -// 4 bit ADPCM nibble, and returns a 16 bit decoded PCM sample. -func (d *decoder) decodeSample(nibble byte) int16 { - // Calculate difference. - var diff int16 - if nibble&4 != 0 { - diff = capAdd16(diff, d.step) - } - if nibble&2 != 0 { - diff = capAdd16(diff, d.step>>1) - } - if nibble&1 != 0 { - diff = capAdd16(diff, d.step>>2) - } - diff = capAdd16(diff, d.step>>3) - - // Account for sign bit. - if nibble&8 != 0 { - diff = -diff - } - - // Adjust estimated sample based on calculated difference. - d.est = capAdd16(d.est, diff) - - // Adjust index into step size lookup table using nibble. - d.index += indexTable[nibble] - - // Check for overflow and underflow. - if d.index < 0 { - d.index = 0 - } else if d.index > int16(len(stepTable)-1) { - d.index = int16(len(stepTable) - 1) - } - - // Find new quantizer step size. - d.step = stepTable[d.index] - - return d.est -} - -// capAdd16 adds two int16s together and caps at max/min int16 instead of overflowing -func capAdd16(a, b int16) int16 { - c := int32(a) + int32(b) - switch { - case c < math.MinInt16: - return math.MinInt16 - case c > math.MaxInt16: - return math.MaxInt16 - default: - return int16(c) - } -} - // calcHead sets the state for the encoder by running the first sample through // the encoder, and writing the first sample to the encoder's io.Writer (dst). // It returns the number of bytes written to the encoder's io.Writer (dst) along with any errors. @@ -227,21 +158,21 @@ func (e *encoder) calcHead(sample []byte, pad bool) (int, error) { return n, err } - err = e.dst.WriteByte(byte(int16(e.index))) + _n, err := e.dst.Write([]byte{byte(int16(e.index))}) if err != nil { return n, err } - n++ + n += _n if pad { - err = e.dst.WriteByte(0x01) + _n, err = e.dst.Write([]byte{0x01}) } else { - err = e.dst.WriteByte(0x00) + _n, err = e.dst.Write([]byte{0x00}) } + n += _n if err != nil { return n, err } - n++ return n, nil } @@ -290,25 +221,73 @@ func (e *encoder) Write(inPcm []byte) (int, error) { for i := byteDepth; i+bytesPerEnc-1 < pcmLen; i += bytesPerEnc { nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i : i+byteDepth]))) nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i+byteDepth : i+bytesPerEnc]))) - err = e.dst.WriteByte(byte((nib2 << 4) | nib1)) + _n, err := e.dst.Write([]byte{byte((nib2 << 4) | nib1)}) + n += _n if err != nil { return n, err } - n++ } // If we've reached the end of the pcm data and there's a sample left over, // compress it to a nibble and leave the first half of the byte padded with 0s. if pad { nib := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[pcmLen-byteDepth : pcmLen]))) - err = e.dst.WriteByte(nib) + _n, err := e.dst.Write([]byte{nib}) + n += _n if err != nil { return n, err } - n++ } return n, nil } +// NewDecoder retuns a new ADPCM decoder. +func NewDecoder(dst io.Writer) *decoder { + d := decoder{ + dst: dst, + } + return &d +} + +// decodeSample takes a byte, the last 4 bits of which contain a single +// 4 bit ADPCM nibble, and returns a 16 bit decoded PCM sample. +func (d *decoder) decodeSample(nibble byte) int16 { + // Calculate difference. + var diff int16 + if nibble&4 != 0 { + diff = capAdd16(diff, d.step) + } + if nibble&2 != 0 { + diff = capAdd16(diff, d.step>>1) + } + if nibble&1 != 0 { + diff = capAdd16(diff, d.step>>2) + } + diff = capAdd16(diff, d.step>>3) + + // Account for sign bit. + if nibble&8 != 0 { + diff = -diff + } + + // Adjust estimated sample based on calculated difference. + d.est = capAdd16(d.est, diff) + + // Adjust index into step size lookup table using nibble. + d.index += indexTable[nibble] + + // Check for overflow and underflow. + if d.index < 0 { + d.index = 0 + } else if d.index > int16(len(stepTable)-1) { + d.index = int16(len(stepTable) - 1) + } + + // Find new quantizer step size. + d.step = stepTable[d.index] + + return d.est +} + // Write takes a slice of bytes of arbitrary length representing adpcm and decodes it into pcm. // It writes its output to the decoder's dst. // The number of bytes written out is returned along with any error that occured. @@ -359,13 +338,26 @@ func (d *decoder) Write(chunk []byte) (int, error) { return n, nil } -// BytesOutput will return the number of adpcm bytes that will be generated for the given pcm data byte size. -func BytesOutput(pcm int) int { - // For X pcm bytes, 1 sample is left uncompressed, the rest is compressed by a factor of 4 +// capAdd16 adds two int16s together and caps at max/min int16 instead of overflowing +func capAdd16(a, b int16) int16 { + c := int32(a) + int32(b) + switch { + case c < math.MinInt16: + return math.MinInt16 + case c > math.MaxInt16: + return math.MaxInt16 + default: + return int16(c) + } +} + +// EncBytes will return the number of adpcm bytes that will be generated when encoding the given amount of pcm bytes (len). +func EncBytes(len int) int { + // For 'len' pcm bytes, 1 sample is left uncompressed, the rest is compressed by a factor of 4 // and a start index and padding-flag byte are added. // Also if there are an even number of samples, there will be half a byte of padding added to the last byte. - if pcm%bytesPerEnc == 0 { - return (pcm-byteDepth)/compFact + headBytes + 1 + if len%bytesPerEnc == 0 { + return (len-byteDepth)/compFact + headBytes + 1 } - return (pcm-byteDepth)/compFact + headBytes + return (len-byteDepth)/compFact + headBytes } diff --git a/codec/adpcm/adpcm_test.go b/codec/adpcm/adpcm_test.go index 9c89221b..8b825696 100644 --- a/codec/adpcm/adpcm_test.go +++ b/codec/adpcm/adpcm_test.go @@ -43,8 +43,7 @@ func TestEncodeBlock(t *testing.T) { } // Encode adpcm. - numBlocks := len(pcm) / PcmBS - comp := bytes.NewBuffer(make([]byte, 0, AdpcmBS*numBlocks)) + comp := bytes.NewBuffer(make([]byte, 0, EncBytes(len(pcm)))) enc := NewEncoder(comp) _, err = enc.Write(pcm) if err != nil { @@ -72,8 +71,7 @@ func TestDecodeBlock(t *testing.T) { } // Decode adpcm. - numBlocks := len(comp) / AdpcmBS - decoded := bytes.NewBuffer(make([]byte, 0, PcmBS*numBlocks)) + decoded := bytes.NewBuffer(make([]byte, 0, len(comp)*4)) dec := NewDecoder(decoded) _, err = dec.Write(comp) if err != nil { From 5e4a2fb86636c8ee507c902c8e7314bc854c6b2b Mon Sep 17 00:00:00 2001 From: Trek H Date: Fri, 17 May 2019 00:58:40 +0930 Subject: [PATCH 15/18] adpcm: naming --- codec/adpcm/adpcm.go | 52 ++++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 7655f405..2257c060 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -38,13 +38,13 @@ import ( ) const ( - byteDepth = 2 // TODO(Trek): make configurable. - initSamps = 2 - initBytes = initSamps * byteDepth - headBytes = 4 - sampsPerEnc = 2 - bytesPerEnc = sampsPerEnc * byteDepth - compFact = 4 + byteDepth = 2 // TODO(Trek): make configurable. + initSamps = 2 + initBytes = initSamps * byteDepth + headBytes = 4 + samplesPerEnc = 2 + bytesPerEnc = samplesPerEnc * byteDepth + compFact = 4 ) // Table of index changes (see spec). @@ -179,9 +179,9 @@ func (e *encoder) calcHead(sample []byte, pad bool) (int, error) { // init initializes the encoder's estimation to the first uncompressed sample and the index to // point to a suitable quantizer step size. // The suitable step size is the closest step size in the stepTable to half the absolute difference of the first two samples. -func (e *encoder) init(samps []byte) { - int1 := int16(binary.LittleEndian.Uint16(samps[:byteDepth])) - int2 := int16(binary.LittleEndian.Uint16(samps[byteDepth:initBytes])) +func (e *encoder) init(samples []byte) { + int1 := int16(binary.LittleEndian.Uint16(samples[:byteDepth])) + int2 := int16(binary.LittleEndian.Uint16(samples[byteDepth:initBytes])) e.est = int1 halfDiff := math.Abs(math.Abs(float64(int1)) - math.Abs(float64(int2))/2.0) @@ -199,9 +199,9 @@ func (e *encoder) init(samps []byte) { // Write takes a slice of bytes of arbitrary length representing pcm and encodes it into adpcm. // It writes its output to the encoder's dst. // The number of bytes written out is returned along with any error that occured. -func (e *encoder) Write(inPcm []byte) (int, error) { +func (e *encoder) Write(b []byte) (int, error) { // Check that pcm has enough data to initialize decoder. - pcmLen := len(inPcm) + pcmLen := len(b) if pcmLen < initBytes { return 0, fmt.Errorf("length of given byte array must be >= %v", initBytes) } @@ -212,15 +212,15 @@ func (e *encoder) Write(inPcm []byte) (int, error) { pad = true } - e.init(inPcm[:initBytes]) - n, err := e.calcHead(inPcm[:byteDepth], pad) + e.init(b[:initBytes]) + n, err := e.calcHead(b[:byteDepth], pad) if err != nil { return n, err } // Skip the first sample and start at the end of the first two samples, then every two samples encode them into a byte of adpcm. for i := byteDepth; i+bytesPerEnc-1 < pcmLen; i += bytesPerEnc { - nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i : i+byteDepth]))) - nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[i+byteDepth : i+bytesPerEnc]))) + nib1 := e.encodeSample(int16(binary.LittleEndian.Uint16(b[i : i+byteDepth]))) + nib2 := e.encodeSample(int16(binary.LittleEndian.Uint16(b[i+byteDepth : i+bytesPerEnc]))) _n, err := e.dst.Write([]byte{byte((nib2 << 4) | nib1)}) n += _n if err != nil { @@ -230,7 +230,7 @@ func (e *encoder) Write(inPcm []byte) (int, error) { // If we've reached the end of the pcm data and there's a sample left over, // compress it to a nibble and leave the first half of the byte padded with 0s. if pad { - nib := e.encodeSample(int16(binary.LittleEndian.Uint16(inPcm[pcmLen-byteDepth : pcmLen]))) + nib := e.encodeSample(int16(binary.LittleEndian.Uint16(b[pcmLen-byteDepth : pcmLen]))) _n, err := e.dst.Write([]byte{nib}) n += _n if err != nil { @@ -291,12 +291,12 @@ func (d *decoder) decodeSample(nibble byte) int16 { // Write takes a slice of bytes of arbitrary length representing adpcm and decodes it into pcm. // It writes its output to the decoder's dst. // The number of bytes written out is returned along with any error that occured. -func (d *decoder) Write(chunk []byte) (int, error) { - // Initialize decoder with first 4 bytes of the chunk. - d.est = int16(binary.LittleEndian.Uint16(chunk[:byteDepth])) - d.index = int16(chunk[byteDepth]) +func (d *decoder) Write(b []byte) (int, error) { + // Initialize decoder with first 4 bytes of b. + d.est = int16(binary.LittleEndian.Uint16(b[:byteDepth])) + d.index = int16(b[byteDepth]) d.step = stepTable[d.index] - n, err := d.dst.Write(chunk[:byteDepth]) + n, err := d.dst.Write(b[:byteDepth]) if err != nil { return n, err } @@ -304,8 +304,8 @@ func (d *decoder) Write(chunk []byte) (int, error) { // For each byte, seperate it into two nibbles (each nibble is a compressed sample), // then decode each nibble and output the resulting 16-bit samples. // If padding flag is true (Adpcm[3]), only decode up until the last byte, then decode that separately. - for i := headBytes; i < len(chunk)-int(chunk[3]); i++ { - twoNibs := chunk[i] + for i := headBytes; i < len(b)-int(b[3]); i++ { + twoNibs := b[i] nib2 := byte(twoNibs >> 4) nib1 := byte((nib2 << 4) ^ twoNibs) @@ -325,8 +325,8 @@ func (d *decoder) Write(chunk []byte) (int, error) { return n, err } } - if chunk[3] == 0x01 { - padNib := chunk[len(chunk)-1] + if b[3] == 0x01 { + padNib := b[len(b)-1] samp := make([]byte, byteDepth) binary.LittleEndian.PutUint16(samp, uint16(d.decodeSample(padNib))) _n, err := d.dst.Write(samp) From 537d5bab733152aa7b2d14169c95872974ad01c9 Mon Sep 17 00:00:00 2001 From: Trek H Date: Wed, 22 May 2019 15:04:21 +0930 Subject: [PATCH 16/18] adpcm: updated decode and encode pcm commands --- exp/adpcm/decode-pcm/decode-pcm.go | 3 +-- exp/adpcm/encode-pcm/encode-pcm.go | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/exp/adpcm/decode-pcm/decode-pcm.go b/exp/adpcm/decode-pcm/decode-pcm.go index 5db6887c..2d471324 100644 --- a/exp/adpcm/decode-pcm/decode-pcm.go +++ b/exp/adpcm/decode-pcm/decode-pcm.go @@ -52,8 +52,7 @@ func main() { fmt.Println("Read", len(comp), "bytes from file", inPath) // Decode adpcm. - numBlocks := len(comp) / adpcm.AdpcmBS - decoded := bytes.NewBuffer(make([]byte, 0, adpcm.PcmBS*numBlocks)) + decoded := bytes.NewBuffer(make([]byte, 0, len(comp)*4)) dec := adpcm.NewDecoder(decoded) _, err = dec.Write(comp) if err != nil { diff --git a/exp/adpcm/encode-pcm/encode-pcm.go b/exp/adpcm/encode-pcm/encode-pcm.go index 69d42042..ded88017 100644 --- a/exp/adpcm/encode-pcm/encode-pcm.go +++ b/exp/adpcm/encode-pcm/encode-pcm.go @@ -52,8 +52,7 @@ func main() { fmt.Println("Read", len(pcm), "bytes from file", inPath) // Encode adpcm. - numBlocks := len(pcm) / adpcm.PcmBS - comp := bytes.NewBuffer(make([]byte, 0, adpcm.AdpcmBS*numBlocks)) + comp := bytes.NewBuffer(make([]byte, 0, adpcm.EncBytes(len(pcm)))) enc := adpcm.NewEncoder(comp) _, err = enc.Write(pcm) if err != nil { From a1fe6c6deb393775512d2ca1f984efa7b848f3e4 Mon Sep 17 00:00:00 2001 From: Trek H Date: Wed, 22 May 2019 15:10:02 +0930 Subject: [PATCH 17/18] adpcm: encoder and decoder structs are now exported --- codec/adpcm/adpcm.go | 50 ++++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 2257c060..352929f1 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -27,7 +27,7 @@ LICENSE Reference algorithms for ADPCM compression and decompression are in part 6. */ -// Package adpcm provides encoder and decoder structs to encode and decode PCM to and from ADPCM. +// Package adpcm provides Encoder and Decoder structs to encode and decode PCM to and from ADPCM. package adpcm import ( @@ -69,8 +69,8 @@ var stepTable = []int16{ 32767, } -// encoder is used to encode to ADPCM from PCM data. -type encoder struct { +// Encoder is used to encode to ADPCM from PCM data. +type Encoder struct { // dst is the destination for encoded data. dst io.Writer @@ -79,8 +79,8 @@ type encoder struct { index int16 } -// decoder is used to decode from ADPCM to PCM data. -type decoder struct { +// Decoder is used to decode from ADPCM to PCM data. +type Decoder struct { // dst is the output buffer that implements io.Writer and io.Bytewriter, ie. where the decoded PCM data is written to. dst io.Writer @@ -90,9 +90,9 @@ type decoder struct { step int16 } -// NewEncoder retuns a new ADPCM encoder. -func NewEncoder(dst io.Writer) *encoder { - e := encoder{ +// NewEncoder retuns a new ADPCM Encoder. +func NewEncoder(dst io.Writer) *Encoder { + e := Encoder{ dst: dst, } return &e @@ -100,7 +100,7 @@ func NewEncoder(dst io.Writer) *encoder { // encodeSample takes a single 16 bit PCM sample and // returns a byte of which the last 4 bits are an encoded ADPCM nibble. -func (e *encoder) encodeSample(sample int16) byte { +func (e *Encoder) encodeSample(sample int16) byte { // Find difference between the sample and the previous estimation. delta := capAdd16(sample, -e.est) @@ -144,10 +144,10 @@ func (e *encoder) encodeSample(sample int16) byte { return nib } -// calcHead sets the state for the encoder by running the first sample through -// the encoder, and writing the first sample to the encoder's io.Writer (dst). -// It returns the number of bytes written to the encoder's io.Writer (dst) along with any errors. -func (e *encoder) calcHead(sample []byte, pad bool) (int, error) { +// calcHead sets the state for the Encoder by running the first sample through +// the Encoder, and writing the first sample to the Encoder's io.Writer (dst). +// It returns the number of bytes written to the Encoder's io.Writer (dst) along with any errors. +func (e *Encoder) calcHead(sample []byte, pad bool) (int, error) { // Check that we are given 1 sample. if len(sample) != byteDepth { return 0, fmt.Errorf("length of given byte array is: %v, expected: %v", len(sample), byteDepth) @@ -176,10 +176,10 @@ func (e *encoder) calcHead(sample []byte, pad bool) (int, error) { return n, nil } -// init initializes the encoder's estimation to the first uncompressed sample and the index to +// init initializes the Encoder's estimation to the first uncompressed sample and the index to // point to a suitable quantizer step size. // The suitable step size is the closest step size in the stepTable to half the absolute difference of the first two samples. -func (e *encoder) init(samples []byte) { +func (e *Encoder) init(samples []byte) { int1 := int16(binary.LittleEndian.Uint16(samples[:byteDepth])) int2 := int16(binary.LittleEndian.Uint16(samples[byteDepth:initBytes])) e.est = int1 @@ -197,10 +197,10 @@ func (e *encoder) init(samples []byte) { } // Write takes a slice of bytes of arbitrary length representing pcm and encodes it into adpcm. -// It writes its output to the encoder's dst. +// It writes its output to the Encoder's dst. // The number of bytes written out is returned along with any error that occured. -func (e *encoder) Write(b []byte) (int, error) { - // Check that pcm has enough data to initialize decoder. +func (e *Encoder) Write(b []byte) (int, error) { + // Check that pcm has enough data to initialize Decoder. pcmLen := len(b) if pcmLen < initBytes { return 0, fmt.Errorf("length of given byte array must be >= %v", initBytes) @@ -240,9 +240,9 @@ func (e *encoder) Write(b []byte) (int, error) { return n, nil } -// NewDecoder retuns a new ADPCM decoder. -func NewDecoder(dst io.Writer) *decoder { - d := decoder{ +// NewDecoder retuns a new ADPCM Decoder. +func NewDecoder(dst io.Writer) *Decoder { + d := Decoder{ dst: dst, } return &d @@ -250,7 +250,7 @@ func NewDecoder(dst io.Writer) *decoder { // decodeSample takes a byte, the last 4 bits of which contain a single // 4 bit ADPCM nibble, and returns a 16 bit decoded PCM sample. -func (d *decoder) decodeSample(nibble byte) int16 { +func (d *Decoder) decodeSample(nibble byte) int16 { // Calculate difference. var diff int16 if nibble&4 != 0 { @@ -289,10 +289,10 @@ func (d *decoder) decodeSample(nibble byte) int16 { } // Write takes a slice of bytes of arbitrary length representing adpcm and decodes it into pcm. -// It writes its output to the decoder's dst. +// It writes its output to the Decoder's dst. // The number of bytes written out is returned along with any error that occured. -func (d *decoder) Write(b []byte) (int, error) { - // Initialize decoder with first 4 bytes of b. +func (d *Decoder) Write(b []byte) (int, error) { + // Initialize Decoder with first 4 bytes of b. d.est = int16(binary.LittleEndian.Uint16(b[:byteDepth])) d.index = int16(b[byteDepth]) d.step = stepTable[d.index] From 762653b59a182b89746a195144f8ae854e22e8f4 Mon Sep 17 00:00:00 2001 From: Trek H Date: Wed, 29 May 2019 02:57:17 +0930 Subject: [PATCH 18/18] adpcm: naming and syntactical changes --- codec/adpcm/adpcm.go | 86 ++++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 47 deletions(-) diff --git a/codec/adpcm/adpcm.go b/codec/adpcm/adpcm.go index 352929f1..ce8ae9f7 100644 --- a/codec/adpcm/adpcm.go +++ b/codec/adpcm/adpcm.go @@ -27,7 +27,7 @@ LICENSE Reference algorithms for ADPCM compression and decompression are in part 6. */ -// Package adpcm provides Encoder and Decoder structs to encode and decode PCM to and from ADPCM. +// Package adpcm provides functions to transcode between PCM and ADPCM. package adpcm import ( @@ -38,13 +38,13 @@ import ( ) const ( - byteDepth = 2 // TODO(Trek): make configurable. - initSamps = 2 + byteDepth = 2 // We are working with 16-bit samples. TODO(Trek): make configurable. + initSamps = 2 // Number of samples used to initialise the encoder. initBytes = initSamps * byteDepth - headBytes = 4 - samplesPerEnc = 2 + headBytes = 4 // Number of bytes in the header of ADPCM. + samplesPerEnc = 2 // Number of sample encoded at a time eg. 2 16-bit samples get encoded into 1 byte. bytesPerEnc = samplesPerEnc * byteDepth - compFact = 4 + compFact = 4 // In general ADPCM compresses by a factor of 4. ) // Table of index changes (see spec). @@ -71,31 +71,26 @@ var stepTable = []int16{ // Encoder is used to encode to ADPCM from PCM data. type Encoder struct { - // dst is the destination for encoded data. + // dst is the destination for ADPCM-encoded data. dst io.Writer - // est and index hold state that persists between calls to encodeSample and calcHead. - est int16 - index int16 + est int16 // Estimation of sample based on quantised ADPCM nibble. + idx int16 // Index to step used for estimation. } // Decoder is used to decode from ADPCM to PCM data. type Decoder struct { - // dst is the output buffer that implements io.Writer and io.Bytewriter, ie. where the decoded PCM data is written to. + // dst is the destination for PCM-encoded data. dst io.Writer - // est, index, and step hold state that persists between calls to decodeSample. - est int16 - index int16 - step int16 + est int16 // Estimation of sample based on quantised ADPCM nibble. + idx int16 // Index to step used for estimation. + step int16 } // NewEncoder retuns a new ADPCM Encoder. func NewEncoder(dst io.Writer) *Encoder { - e := Encoder{ - dst: dst, - } - return &e + return &Encoder{dst: dst} } // encodeSample takes a single 16 bit PCM sample and @@ -111,7 +106,7 @@ func (e *Encoder) encodeSample(sample int16) byte { delta = -delta } - step := stepTable[e.index] + step := stepTable[e.idx] diff := step >> 3 var mask byte = 4 @@ -132,13 +127,13 @@ func (e *Encoder) encodeSample(sample int16) byte { // Adjust estimated sample based on calculated difference. e.est = capAdd16(e.est, diff) - e.index += indexTable[nib&7] + e.idx += indexTable[nib&7] // Check for underflow and overflow. - if e.index < 0 { - e.index = 0 - } else if e.index > int16(len(stepTable)-1) { - e.index = int16(len(stepTable) - 1) + if e.idx < 0 { + e.idx = 0 + } else if e.idx > int16(len(stepTable)-1) { + e.idx = int16(len(stepTable) - 1) } return nib @@ -146,7 +141,7 @@ func (e *Encoder) encodeSample(sample int16) byte { // calcHead sets the state for the Encoder by running the first sample through // the Encoder, and writing the first sample to the Encoder's io.Writer (dst). -// It returns the number of bytes written to the Encoder's io.Writer (dst) along with any errors. +// It returns the number of bytes written to the Encoder's destination and the first error encountered. func (e *Encoder) calcHead(sample []byte, pad bool) (int, error) { // Check that we are given 1 sample. if len(sample) != byteDepth { @@ -158,7 +153,7 @@ func (e *Encoder) calcHead(sample []byte, pad bool) (int, error) { return n, err } - _n, err := e.dst.Write([]byte{byte(int16(e.index))}) + _n, err := e.dst.Write([]byte{byte(int16(e.idx))}) if err != nil { return n, err } @@ -184,7 +179,7 @@ func (e *Encoder) init(samples []byte) { int2 := int16(binary.LittleEndian.Uint16(samples[byteDepth:initBytes])) e.est = int1 - halfDiff := math.Abs(math.Abs(float64(int1)) - math.Abs(float64(int2))/2.0) + halfDiff := math.Abs(math.Abs(float64(int1)) - math.Abs(float64(int2))/2) closest := math.Abs(float64(stepTable[0]) - halfDiff) var cInd int16 for i, step := range stepTable { @@ -193,7 +188,7 @@ func (e *Encoder) init(samples []byte) { cInd = int16(i) } } - e.index = cInd + e.idx = cInd } // Write takes a slice of bytes of arbitrary length representing pcm and encodes it into adpcm. @@ -242,10 +237,7 @@ func (e *Encoder) Write(b []byte) (int, error) { // NewDecoder retuns a new ADPCM Decoder. func NewDecoder(dst io.Writer) *Decoder { - d := Decoder{ - dst: dst, - } - return &d + return &Decoder{dst: dst} } // decodeSample takes a byte, the last 4 bits of which contain a single @@ -273,17 +265,17 @@ func (d *Decoder) decodeSample(nibble byte) int16 { d.est = capAdd16(d.est, diff) // Adjust index into step size lookup table using nibble. - d.index += indexTable[nibble] + d.idx += indexTable[nibble] // Check for overflow and underflow. - if d.index < 0 { - d.index = 0 - } else if d.index > int16(len(stepTable)-1) { - d.index = int16(len(stepTable) - 1) + if d.idx < 0 { + d.idx = 0 + } else if d.idx > int16(len(stepTable)-1) { + d.idx = int16(len(stepTable) - 1) } // Find new quantizer step size. - d.step = stepTable[d.index] + d.step = stepTable[d.idx] return d.est } @@ -294,8 +286,8 @@ func (d *Decoder) decodeSample(nibble byte) int16 { func (d *Decoder) Write(b []byte) (int, error) { // Initialize Decoder with first 4 bytes of b. d.est = int16(binary.LittleEndian.Uint16(b[:byteDepth])) - d.index = int16(b[byteDepth]) - d.step = stepTable[d.index] + d.idx = int16(b[byteDepth]) + d.step = stepTable[d.idx] n, err := d.dst.Write(b[:byteDepth]) if err != nil { return n, err @@ -351,13 +343,13 @@ func capAdd16(a, b int16) int16 { } } -// EncBytes will return the number of adpcm bytes that will be generated when encoding the given amount of pcm bytes (len). -func EncBytes(len int) int { - // For 'len' pcm bytes, 1 sample is left uncompressed, the rest is compressed by a factor of 4 +// EncBytes will return the number of adpcm bytes that will be generated when encoding the given amount of pcm bytes (n). +func EncBytes(n int) int { + // For 'n' pcm bytes, 1 sample is left uncompressed, the rest is compressed by a factor of 4 // and a start index and padding-flag byte are added. // Also if there are an even number of samples, there will be half a byte of padding added to the last byte. - if len%bytesPerEnc == 0 { - return (len-byteDepth)/compFact + headBytes + 1 + if n%bytesPerEnc == 0 { + return (n-byteDepth)/compFact + headBytes + 1 } - return (len-byteDepth)/compFact + headBytes + return (n-byteDepth)/compFact + headBytes }