{"id":25300110,"url":"https://github.com/deftio/companders","last_synced_at":"2025-10-28T06:30:45.178Z","repository":{"id":4454036,"uuid":"5592617","full_name":"deftio/companders","owner":"deftio","description":"Audio compression using companders (integer implementation, A-Law, Mu-Law) for embedded micros with IIR fixed-radix averager","archived":false,"fork":false,"pushed_at":"2024-08-11T18:12:17.000Z","size":296,"stargazers_count":25,"open_issues_count":0,"forks_count":5,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-03T21:11:09.363Z","etag":null,"topics":["a-law","audio","audio-codec","audio-samples","compander","compression","embedded-audio","embedded-systems","fixed-point","fixed-point-algorithm","fixed-point-arithmetic","iir","integer-arithmetic","mu-law","radix","u-law"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-2-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/deftio.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2012-08-28T21:46:24.000Z","updated_at":"2025-03-22T03:33:58.000Z","dependencies_parsed_at":"2024-08-11T19:27:16.111Z","dependency_job_id":"7ce23c39-9275-4960-a6d2-039c072879c6","html_url":"https://github.com/deftio/companders","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/deftio/companders","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deftio%2Fcompanders","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deftio%2Fcompanders/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deftio%2Fcompanders/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deftio%2Fcompanders/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/deftio","download_url":"https://codeload.github.com/deftio/companders/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deftio%2Fcompanders/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":281397336,"owners_count":26493908,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-28T02:00:06.022Z","response_time":60,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["a-law","audio","audio-codec","audio-samples","compander","compression","embedded-audio","embedded-systems","fixed-point","fixed-point-algorithm","fixed-point-arithmetic","iir","integer-arithmetic","mu-law","radix","u-law"],"created_at":"2025-02-13T05:38:24.025Z","updated_at":"2025-10-28T06:30:44.905Z","avatar_url":"https://github.com/deftio.png","language":"C","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![License](https://img.shields.io/badge/License-BSD%202--Clause-blue.svg)](https://opensource.org/licenses/BSD-2-Clause)\n[![Github Actions Ci](https://github.com/deftio/companders/actions/workflows/ci.yml/badge.svg)](https://github.com/deftio/companders/actions/workflows/ci.yml/badge.svg)\n\n# [Companders (a fixed point audio compression library)](https://deftio.github.io/companders/)  \n\n(c) 2001-2024  M. A. Chatterjee\n\nThis repo is a simple audio compression library for microcontrollers using A-Law and Mu-Law (a type of compander).  The code uses fixed-radix (integer only) math with a small introductory discussion and use of associated DC-offset correction with an IIR fixed-radix filter.\n\nAll the code in this repo is suitable for small microcontrollers such as 8 bit and 16 bit families (arduino, 68hc, 8051 ) as well as on 32 bit familes such as ARM, RISC-V, etc.\n\nAs this is a fixed point library (a type of integer math), floating point is not used or even emulated.  For more background on using fixed point (or fixed radix) math see this code library and documentation : [FR_Math](https://github.com/deftio/fr_math)\n\n## Welcome\n\nThe accompanying companders.c contains a small set of functions written in C using only integer math for companding operations.  I developed this several years ago for use in several embedded interized math projects and this small, slightly cleaned up version is made available for the public here.  It worked very well on M*CORE, 80x86 and ARM processors for small embedded systems.\n\nUsage:\n\n```C\n#include \"companders.h\"   //no other dependancies or libaries are required.\n\n// .. in code then\nint myCompandedValue = DIO_LinearToALaw(123); // convert the integer to is A-Law equivalent companded value\n\nint unCompandedValue = DIO_ALawToLinear(myCompandedValue); // convert back to linear range. (with appropriate loss)\n```\n\n## About Companding\n\nCompanding is a special type of lossy compression in which linear format samples are converted to logarithmic representation in order to preserve dynamic range of the original linear sample at the expense of uniform precision.  Companding is an old method and is free of patents (all have expired).\n\nTheory of how companding works:\nSuppose that we have a signed 16 bit linear sample in 2's complement math.  The range of this sample can vary from -32768 to + 32767 in integer steps.  Now lets put the constraint that we only have 8 bits with which to represent the data not the full 16 bits of the original linear number.  A simple way to preserve high order information would be to linearly truncate off the lower 8 bits giving us a signed number from -128 to +127.  We could make a mental note to keep track of the fact that we lost the lower 8 bits and so when use this representation we multiply by 8 bits (or 256) to preserve the input range.\nso:\n\n```C\n-128 * 256 = -32768\n-127 * 256 = -32512\n...\n  -1 * 256 =   -256\n   0 * 256 =      0\n   1 * 256 =    256\n   2 * 256 =    512\n...\n 126 * 256 =  32256 \n 127 * 256 =  32512 \n ```\n\nNotice that the steps between these linearly rounded off samples are quite large.  This truncated 8 bit representation would be very good at representing a linear quantity system such as linear displacement transducer which moves through its whole range as part of normal operation (like a door). but terrible at logarithmic phenomonen such as audio.  Audio information tends to be grouped around zero with occaisonaly peaks of loudness.  So with linear quantization soft audio would be lost due to the large quanitization steps at low volumes. To address this companders were developed for use in landline telephony for compressing audio data logarithmically instead of linearly.  Hence we use more bits for audio samples near zero and less with audio samples near the integer max extremes.\n\nA-Law and it cousin mu-Law are companders.  Rather than represent samples in linear steps the more bits are allocated to samples near zero while larger magnitude (positive or negative) samples are represented with proportionately larger interval sizes.\n\nDifferential encoding (taking the difference of neighboring samples) can greatly help with compressing data to where we \"have more bits\" as well, provided samples rates are fast enough.  Telephony typically operated with 8 bit non-differential (companded) samples at 8KHz.\n\nIn A-Law the following table (in bits) shows how a 13 bit signed linear integer is companded in to A-Law:\n(source is Sun microsystems, a similar table is on wikipedia or the G.711 specification).\n\n|   Linear Input Code | Compressed Code |\n|------------------------ | --------------- |\n|   0000000wxyza   | 000wxyz         |\n|   0000001wxyza   | 001wxyz         |\n|   000001wxyzab   | 010wxyz         |\n|   00001wxyzabc   | 011wxyz         |\n|   0001wxyzabcd   | 100wxyz         |\n|   001wxyzabcde   | 101wxyz         |\n|   01wxyzabcdef   | 110wxyz         |\n|   1wxyzabcdefg   | 111wxyz         |\n\n### Mu-law (also mu-law or u-law)\n\nMu is similar compander to A-Law but  used in American \u0026 Japanese telephony instead of European Telephony. \n\nBoth algorithms aim to optimize the dynamic range of an audio signal by using logarithmic compression, but they differ in their compression characteristics and implementation. A-Law provides a slightly lower compression ratio, which offers better signal quality for signals with lower amplitude, whereas μ-Law provides higher compression, which can handle a wider range of input levels more efficiently but introduces more distortion for low-level signals. These standards were developed in the mid-20th century to improve the efficiency and quality of voice transmission over limited-bandwidth communication channels. A-Law was standardized by the International Telegraph and Telephone Consultative Committee (CCITT) and is detailed in the ITU-T G.711 recommendation, while μ-Law was standardized by the American National Standards Institute (ANSI).\n\n## About this library\n\nThis free library supports A-Law, mu-Law and IIR averages.  A-Law or Mu-Law are used for the companding while the IIR averagers can be used for for embedded ADCs where the zero point is set loosely.  Since the companders are sensitive, and allocate more bits, to values near zero its important to define a good zero.  For example a microcontroller has a pin with an ADC which is fed digitized audio signal.  The smallest value for the microtroncoller is 0V = 0x00 and the 3.3V = 0x3ff for 10 effective bits of resolution.  A resisitive analog divider is used to center the ADC near the half-input range or about 1.6V while the audio is capacitively coupled as shown here:  \n\n ```text\n \n             +3.3V\n               |\n               R\n               |            \nuC_ADC_Pin\u003c-----------C---- audio_input_source\n               |\n               R\n               |\n              GND\n\n ```\n\n However cheap resistors have tolerances 5 to 10%, so the setpoint voltage could easily be anywhere from 1.4 to 1.8V.  To address this software should read the ADC before audio is coming in and determine the actual DC bias voltage set by the real world resistors.  Then when audio is coming in this value is subtracted from the ADC input to give a signed number which is fed to the LinearToAlaw encoder.  \n\n If it not easily possible to turn off the analog / audio source then the long term DC average can be inferred by using one of the IIR functions included here with a long window length (perhaps 2000 samples if sampling at 8 KHz or about 1/4 second).  These IIR functions are cheap to run in realtime even with reasonably high sample rates as they take little memory and are simple integer-math IIRs.\n\n## About the Fixed Radix (FR) Math IIR averages\n\nThe (Infinite Impulse Reponse) IIR functions included here use fixed radix math to represent fractional parts of an integer.  By providing a settable radix (amount of bits devoted to fractional resolution), the programmer can make tradeoffs between resolution and dynamic range.  The larger the radix specified the more bits that will be used in the fractional portion of the representation, which for smaller window sizes may not by necessary.  There are more comprehensive ways to deal with fractional representation in binary systems (floating point, bigNum / arbitrary length registers, separation of numerator/denomators etc) but these incur much larger compute/code/memory overhead.  The simple system used here avoids the need for testing for overflow/underflow which allows for low foot print code/cpu/memory bandwidth.\n\nTo calculate how many bits of fractional part while preventing overflow use the following formulas:\n\n```C\nNb = number_of_bits_in_use = ceiling(log2(highest_number_represented))\n\nradix = 32-Nb(sample_resolution)-Nb(WindowLength)-2\n\n//for example if you have a ADC generating counts from 0 to 1023 then the Nb(ADC-range) = \n  Nb = ceiling(log2(1023)) = 10 // bits\n  \n//If you use a DC average window length of 2000 \n  Nb = ceiling(log2(2000)) = 11 // bits\n  \n//so the max radix that should be specified is:\n  radix = 32 - 10 - 11 - 2 = 32 - 23 = 9 // bits\n\n```  \n\nwith 9 bits in the radix fractional precision of 512 units per integer (e.g 1/512) is possible.  The \"2\" in for formula comes from reserving bits for the sign bit and the additional operation in averager.\n\nThe function DIO_s32 DIO_IIRavgFR() allows any integer length window size to be used, while the function DIO_IIRavgPower2FR() specifies window lengths in powers of two but all calculations are based on shift operations which can be significantly faster on lower end microprocessors.\n\n## Embedded Systems\n\nNow back to an embedded microcontroller example.  Let's say it has an ADC which maps the voltage on 1 pin from 0-3.3V in to 0-4095 counts (12 bits).  We capacitively couple the input voltage and use the bias resistors to set mid point in the center of the range.  Lets say the the our resistors set the bias at 1.55V.  This equals our \"zero point\".  Below this point is negative from the incoming capacitively coupled audio and above this is positive.  \n\nOur \"guess\" as to the bias = both resistors are the same = (3.3V/2) =1.65V = (1.65V)/(4095 counts/3.3V)= 2048 counts\n\nResistor actual set bias \"zero point\" = 1.55V = (1.55V) *(4095 counts/3.3V)) = 1923 counts\nWe want this to be \"zero\" we use for the companded A/D process.  \n\nTo do this we start our ADC to periodically sample for sometime before we start \"recording\" audio.   We will feed the ADC values in to our IIR average to find the actual zero point. Note that even when we decide not to \"record\" we still can still run the A/D and  IIR averager so its adapting to the real zero point.\n\n## C-like Pseudo code\n\n```C\n#include \"companders.h\"\n\nstatic volatile int32 gIIRavg= 2048; // global static var holds DC average as estimated by the IIR\nstatic volatile int   gDoSomethingWithCompandedValue=0;\n\nvoid processAudioSample() //interrupt handler -- runs at the sample rate\n{\n short adcValue;\n char  aLawValue;\n \n //read the raw uncorrected sample (has some DC offset bias) \n adcValue= inputPin.read_u16(); // read a 16 bit unsigned sample\n \n // this updates the IIR average everytime the adc returns a sample\n gIIRavg = DIO_IIRavgPower2FR(gIIRavg,11,adcValue,8);\n \n //now compute companded value with DC offset correction\n if (gDoSomethingWithCompandedValue)\n {\n  aLawValue = DIO_LinearToALaw(adcValue-DIO_FR2I(gIIRavg));  // subtract off the offset and get a good A-Law value\n  doSomethingWithALaw(aLawValue);  // store it to a buffer, send it the cloud ;) etc\n }\n}\n\nmain()\n{\n gDoSomethingWithCompandedValue=0;\n inputPin.attachInterrupt(\u0026processAudioSample,8000); //attach interrupt handler, 8000 Hz sample rate\n \n // ... somepoint later in the code\n \n inputPin.start(); // start the collecting audio.  inside the interrupt handler we'll start estimating the DC bias\n \n // ... some time later  (when we actually want the audio) we set this flag\n gDoSomethingWithCompandedValue=1; //now the interrupt routine will call the doSomethingWithALaw() function\n \n // ... some time later\n gDoSomethingWithCompandedValue=0; //we're no longer collecting ALaw companded date, but we're \n           // still running the IIR averager\n \n}\n\n```\n\nThe accompanying compandit.c file is an example program demonstrating the convergence of the averager to a simulated DC offset value (output is in the testout.txt file).\n\n### Some Closing Comments  \n\nFinally,  it can be in some systems that we can't turn off the audio input source it may be hard wired to some sensor or mic or perhaps the A/D center bias circuit (the 2 resistors) always is on when the audio is on.  In this case running the IIR with a long filter length all the time can remove the bias even when the audio is running.  For example in an 8KHz sampling system with an IIR length of 1024 is about 1/8 of a second or a cutoff freq well below 10Hz and costs almost nothing to run.\n\n### Further Reading\n\n* [TI App Note on Alaw and Mulaw](https://www.ti.com/lit/an/spra163a/spra163a.pdf)\n* [wikipedia on Companding](https://en.wikipedia.org/wiki/Companding)\n* [University of British Columbia lab on Companding](https://people.ece.ubc.ca/edc/4550.jan2018/lab2.pdf)\n\n### Code Coverage\n\nCode coverage is achieved using gcov from the gcc test suite. To see the code coverage:\n\n```bash\nmake clean\nmake\n./test-library.out\ngcov companders.c\n```\n\nThe line gcov companders.c generates the file companders.c.gcov, which can be viewed in any text editor. Lines marked with #### have never been run.\n\n\n## Versions\n\n* 1.0.6 08 Aug 2024  -- added ci testing \n* 1.0.5 30 May 2024  -- cleaned up release \n* 1.0.4 30 May 2024  -- add ulaw, updated docs, added full test \n* 1.0.4 23 Jan 2023  -- updated docs  \n* 1.0.3 28 Jul 2019  -- updated docs, ver example \n* 1.0.2 15 Jul 2016  -- updated README.md to markdown format.  updated license to be OSI compliant.  no code changes. some minor doc updates. Thanks to John R Strohm giving me the nudge to update the docs here. \n* 1.0.1  3 Sep 2012  -- original release in github   \n\n## License\n\nSee attached LICENSE.txt file  (OSI approved BSD 2 Clause)\n\nCopyright (c) 2001-2024, M. A. Chatterjee \u003c deftio at deftio dot com \u003e\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeftio%2Fcompanders","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdeftio%2Fcompanders","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeftio%2Fcompanders/lists"}