Skip to content

Instantly share code, notes, and snippets.

@tripulse
Created November 9, 2021 07:18
Show Gist options
  • Save tripulse/0b77a1e8c3ea5a4654b803deb3f5fa06 to your computer and use it in GitHub Desktop.
Save tripulse/0b77a1e8c3ea5a4654b803deb3f5fa06 to your computer and use it in GitHub Desktop.
Quality degradation simulation with OPUS codec.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <opus/opus.h>
#include <assert.h>
//#define M_E 2.3504023872876028
#define M_E_1 0.36787944117144233
#define M_E_NEG_M_E_1 2.3504023872876028
#define PI_1 0.3183098861837907
#define T_INCR 0.5
int main()
{
OpusEncoder* enc;
OpusDecoder* dec;
opus_int16 sample_buffer[5760];
unsigned char opus_buffer[1024];
size_t num_read;
opus_int32 opus_buffer_size;
double t = 0.0;
enc = opus_encoder_create(48000, 2, OPUS_APPLICATION_AUDIO, NULL);
dec = opus_decoder_create(48000, 2, NULL);
assert(opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(10)) == OPUS_OK);
assert(opus_encoder_ctl(enc, OPUS_SET_VBR(0)) == OPUS_OK);
assert(opus_encoder_ctl(enc, OPUS_SET_SIGNAL(OPUS_SIGNAL_MUSIC)) == OPUS_OK);
assert(opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_FULLBAND)) == OPUS_OK);
for(;;)
{
num_read = fread(sample_buffer, sizeof(opus_int16), 5760, stdin);
if(num_read == 0)
break;
// zero the buffer if not enough samples.
// size_t n_samples = num_read / sizeof(opus_int16);
// size_t zero_begin = n_samples * sizeof(opus_int16);
// memset(sample_buffer + zero_begin, 0, 5760*sizeof(opus_int16) - zero_begin);
// b = (exp(-cos(1/pi * x)) - e) / (e - exp(-1)) * 9000 + 600
// double bitrate = ((exp(-cos(PI_1/12.0 * t)) - M_E_1) / M_E_NEG_M_E_1) * 90000.0 + 6000.0;
// double bitrate = 64000 * 2 * fabs(t/60 - floor(t/60 + .5)) + 6000;
double bitrate = 48000.0 * -.5 * cos(2.0*M_PI*(1.0/240.0)*t) + 24000.0 + 6000.0;
opus_encoder_ctl(enc, OPUS_SET_BITRATE((opus_int32)bitrate));
opus_buffer_size = opus_encode(enc, sample_buffer, 2880, opus_buffer, 1024);
opus_decode(dec, opus_buffer, opus_buffer_size, sample_buffer, 2880, 0);
fwrite(sample_buffer, sizeof(opus_int16), 5760, stdout);
t += T_INCR;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment