File: audioconverter.cpp

package info (click to toggle)
wfview 2.11-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,256 kB
  • sloc: cpp: 43,386; ansic: 3,196; sh: 32; xml: 29; makefile: 11
file content (396 lines) | stat: -rw-r--r-- 18,012 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
#include "audioconverter.h"
#include "logcategories.h"
#include "ulaw.h"
#include "adpcm/adpcm-lib.h"

audioConverter::audioConverter(QObject* parent) : QObject(parent) 
{
}

bool audioConverter::init(QAudioFormat inFormat, codecType inCodec, QAudioFormat outFormat, codecType outCodec, quint8 opusComplexity, quint8 resampleQuality)
{

	this->inFormat = inFormat;
    this->inCodec = inCodec;
    this->outFormat = outFormat;
    this->outCodec = outCodec;
    this->opusComplexity = opusComplexity;
	this->resampleQuality = resampleQuality;

#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
    qInfo(logAudioConverter) << "Starting audioConverter() Input:" << inFormat.channelCount() << "Channels of" << inCodec << inFormat.sampleRate() << inFormat.sampleType() << inFormat.sampleSize() <<
        "Output:" << outFormat.channelCount() << "Channels of" << outCodec << outFormat.sampleRate() << outFormat.sampleType() << outFormat.sampleSize();

    if (inFormat.byteOrder() != outFormat.byteOrder()) {
		qInfo(logAudioConverter) << "Byteorder mismatch in:" << inFormat.byteOrder() << "out:" << outFormat.byteOrder();
	}
#else
    qInfo(logAudioConverter) << "Starting audioConverter() Input:" << inFormat.channelCount() << "Channels of" << inCodec << inFormat.sampleRate() << inFormat.sampleFormat() << 
        "Output:" << outFormat.channelCount() << "Channels of" << outCodec << outFormat.sampleRate() << outFormat.sampleFormat();

#endif


    if (inCodec == OPUS)
    {
        // Create instance of opus decoder
        int opus_err = 0;
        opusDecoder = opus_decoder_create(inFormat.sampleRate(), inFormat.channelCount(), &opus_err);
        qInfo(logAudioConverter()) << "Creating opus decoder: " << opus_strerror(opus_err);
    }

    if (outCodec == OPUS)
    {
        // Create instance of opus encoder
		int opus_err = 0;
		opusEncoder = opus_encoder_create(outFormat.sampleRate(), outFormat.channelCount(), OPUS_APPLICATION_AUDIO, &opus_err);
		//opus_encoder_ctl(opusEncoder, OPUS_SET_LSB_DEPTH(16));
		//opus_encoder_ctl(opusEncoder, OPUS_SET_INBAND_FEC(1));
		//opus_encoder_ctl(opusEncoder, OPUS_SET_DTX(1));
		//opus_encoder_ctl(opusEncoder, OPUS_SET_PACKET_LOSS_PERC(5));
		opus_encoder_ctl(opusEncoder, OPUS_SET_COMPLEXITY(opusComplexity)); // Reduce complexity to maybe lower CPU?
        qInfo(logAudioConverter()) << "Creating opus encoder: " << opus_strerror(opus_err);
	}

    if (outCodec == ADPCM)
    {
        adpcmContext = adpcm_create_context(outFormat.channelCount(),outFormat.sampleRate(),1,1);
    }

	if (inFormat.sampleRate() != outFormat.sampleRate()) 
	{
		int resampleError = 0;
		unsigned int ratioNum;
		unsigned int ratioDen;
		// Sample rate conversion required. 
		resampler = wf_resampler_init(outFormat.channelCount(), inFormat.sampleRate(), outFormat.sampleRate(), resampleQuality, &resampleError);
		wf_resampler_get_ratio(resampler, &ratioNum, &ratioDen);
		resampleRatio = static_cast<double>(ratioDen) / ratioNum;
		qInfo(logAudioConverter()) << "wf_resampler_init() returned: " << resampleError << " resampleRatio: " << resampleRatio;
	}
	return true;
}

audioConverter::~audioConverter() 
{

#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
    qInfo(logAudioConverter) << "Closing audioConverter() Input:" << inFormat.channelCount() << "Channels of" << inCodec << inFormat.sampleRate() << inFormat.sampleType() << inFormat.sampleSize() <<
        "Output:" << outFormat.channelCount() << "Channels of" << outCodec << outFormat.sampleRate() << outFormat.sampleType() << outFormat.sampleSize();
#else
    qInfo(logAudioConverter) << "Closing audioConverter() Input:" << inFormat.channelCount() << "Channels of" << inCodec << inFormat.sampleRate() << inFormat.sampleFormat() <<
        "Output:" << outFormat.channelCount() << "Channels of" << outCodec << outFormat.sampleRate() << outFormat.sampleFormat();
#endif

	if (opusEncoder != Q_NULLPTR) {
		qInfo(logAudioConverter()) << "Destroying opus encoder";
		opus_encoder_destroy(opusEncoder);
	}

	if (opusDecoder != Q_NULLPTR) {
		qInfo(logAudioConverter()) << "Destroying opus decoder";
		opus_decoder_destroy(opusDecoder);
	}

    if (adpcmContext != Q_NULLPTR) {
        qDebug(logAudioConverter()) << "adpcm context closed";
        adpcm_free_context(adpcmContext);
    }

    if (resampler != Q_NULLPTR) {
		speex_resampler_destroy(resampler);
        qDebug(logAudioConverter()) << "Resampler closed";
    }
}

bool audioConverter::convert(audioPacket audio)
{

    // If inFormat and outFormat are identical, just emit the data back (removed as it doesn't then process amplitude)
    if (audio.data.size() > 0)
	{

        if (inCodec == OPUS)
        {
            quint8* in = (quint8*)audio.data.data();

            //Decode the frame.
            int nSamples = opus_packet_get_nb_samples(in, audio.data.size(), inFormat.sampleRate());
            if (nSamples == -1) {
                // No opus data yet?
                return false;
            }
            QByteArray outPacket(nSamples * sizeof(float) * inFormat.channelCount(), (char)0xff); // Preset the output buffer size.
            float* out = (float*)outPacket.data();

            int ret = opus_decode_float(opusDecoder, in, audio.data.size(), out, nSamples, 0);
            if (ret != nSamples)
            {
                qDebug(logAudio()) << "opus_decode_float: returned:" << ret << "samples, expected:" << nSamples;
            }
            audio.data.clear();
            audio.data = outPacket; // Replace incoming data with converted.
        }
        else if (inCodec == PCMU)
        {
            // Current packet is "technically" 8bit so need to create a new buffer that is 16bit
            QByteArray outPacket((int)audio.data.length() * 2, (char)0xff);
            qint16* out = (qint16*)outPacket.data();
            for (int f = 0; f < audio.data.length(); f++)
            {
                *out++ = ulaw_decode[(quint8)audio.data[f]];
            }
            audio.data.clear();
            audio.data = outPacket; // Replace incoming data with converted.
            // Make sure that sample size/type is set correctly
        }
        else if (inCodec == ADPCM)
        {
            QByteArray outPacket((int)((audio.data.length()-4) * 4), (char)0xff);
            qint16* out = (qint16*)outPacket.data();
            quint8* in = (quint8*)audio.data.data();
            int samples = adpcm_decode_block(out,in,audio.data.size(),1);
            if (samples != outPacket.size()/2) {
                qInfo() << "Sample size mismatch, audio packet in:" << audio.data.length() << "out:" << outPacket.length() << "samples:" <<samples;
            }
            audio.data.clear();
            audio.data = outPacket; // Replace incoming data with converted.
        }

        Eigen::VectorXf samplesF;
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
        if (inFormat.sampleType() == QAudioFormat::SignedInt && inFormat.sampleSize() == 32)
#else
        if (inFormat.sampleFormat() == QAudioFormat::Int32)
#endif
        {
            Eigen::Ref<VectorXint32> samplesI = Eigen::Map<VectorXint32>(reinterpret_cast<qint32*>(audio.data.data()), audio.data.size() / int(sizeof(qint32)));
            samplesF = samplesI.cast<float>() / float(std::numeric_limits<qint32>::max());
        }
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
        else if (inFormat.sampleType() == QAudioFormat::SignedInt && inFormat.sampleSize() == 16)
#else
        else if (inFormat.sampleFormat() == QAudioFormat::Int16)
#endif
        {
            Eigen::Ref<VectorXint16> samplesI = Eigen::Map<VectorXint16>(reinterpret_cast<qint16*>(audio.data.data()), audio.data.size() / int(sizeof(qint16)));
            samplesF = samplesI.cast<float>() / float(std::numeric_limits<qint16>::max());
        }
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
        else if (inFormat.sampleType() == QAudioFormat::UnSignedInt && inFormat.sampleSize() == 8)
#else
        else if (inFormat.sampleFormat() == QAudioFormat::UInt8)
#endif
        {
            Eigen::Ref<VectorXuint8> samplesI = Eigen::Map<VectorXuint8>(reinterpret_cast<quint8*>(audio.data.data()), audio.data.size() / int(sizeof(quint8)));
            samplesF = samplesI.cast<float>() / float(std::numeric_limits<quint8>::max());;
        }
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
        else if (inFormat.sampleType() == QAudioFormat::Float) 
#else
        else if (inFormat.sampleFormat() == QAudioFormat::Float)
#endif
        { 

            samplesF = Eigen::Map<Eigen::VectorXf>(reinterpret_cast<float*>(audio.data.data()), audio.data.size() / int(sizeof(float)));
        }
        else
        {
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
        qInfo(logAudio()) << "Unsupported Input Sample Type:" << inFormat.sampleType() << "Size:" << inFormat.sampleSize();
#else
        qInfo(logAudio()) << "Unsupported Input Sample Format:" << inFormat.sampleFormat();
#endif
        }

        if (samplesF.size() > 0)

        {
            // samplesF is currently raw samples as received from the radio:
            emit floatAudio(samplesF);

            audio.amplitudePeak = samplesF.array().abs().maxCoeff();
            //audio.amplitudeRMS = samplesF.array().abs().mean(); // zero for tx audio
            //audio.amplitudeRMS = samplesF.norm() / sqrt(samplesF.size()); // too high values. Zero for tx audio.
            //audio.amplitudeRMS = samplesF.squaredNorm(); // tx not zero. Values higher than peak sometimes
            //audio.amplitudeRMS = samplesF.norm(); // too small values. also too small on TX
            //audio.amplitudeRMS = samplesF.blueNorm(); // scale same as norm, too small.


            // Set the volume
            samplesF *= audio.volume;

            /*
                samplesF is now an Eigen Vector of the current samples in float format
                The next step is to convert to the correct number of channels in outFormat.channelCount()
            */


            if (inFormat.channelCount() == 2 && outFormat.channelCount() == 1) {
                // If we need to drop one of the audio channels, do it now
                Eigen::VectorXf samplesTemp(samplesF.size() / 2);
                samplesTemp = Eigen::Map<Eigen::VectorXf, 0, Eigen::InnerStride<2> >(samplesF.data(), samplesF.size() / 2);
                samplesF = samplesTemp;
            }
            else if (inFormat.channelCount() == 1 && outFormat.channelCount() == 2) {
                // Convert mono to stereo if required
                Eigen::VectorXf samplesTemp(samplesF.size() * 2);
                Eigen::Map<Eigen::VectorXf, 0, Eigen::InnerStride<2> >(samplesTemp.data(), samplesF.size()) = samplesF;
                Eigen::Map<Eigen::VectorXf, 0, Eigen::InnerStride<2> >(samplesTemp.data() + 1, samplesF.size()) = samplesF;
                samplesF = samplesTemp;
            }

            /*
                Next step is to resample (if needed)
            */

            if (resampler != Q_NULLPTR && resampleRatio != 1.0)
            {
                quint32 outFrames = ((samplesF.size() / outFormat.channelCount()) * resampleRatio);
                quint32 inFrames = (samplesF.size() / outFormat.channelCount());
                QByteArray outPacket(outFrames * outFormat.channelCount() * sizeof(float), (char)0xff); // Preset the output buffer size.
                const float* in = (float*)samplesF.data();
                float* out = (float*)outPacket.data();

                int err = 0;
                if (outFormat.channelCount() == 1) {
                    err = wf_resampler_process_float(resampler, 0, in, &inFrames, out, &outFrames);
                }
                else {
                    err = wf_resampler_process_interleaved_float(resampler, in, &inFrames, out, &outFrames);
                }

                if (err) {
                    qInfo(logAudioConverter()) << "Resampler error " << err << " inFrames:" << inFrames << " outFrames:" << outFrames;
                }
                samplesF = Eigen::Map<Eigen::VectorXf>(reinterpret_cast<float*>(outPacket.data()), outPacket.size() / int(sizeof(float)));
            }

            /*
                If output is Opus so encode it now, don't do any more conversion on the output of Opus.
            */

            if (outCodec == OPUS)
            {
                float* in = (float*)samplesF.data();
                QByteArray outPacket(1275, (char)0xff); // Preset the output buffer size to MAXIMUM possible Opus frame size
                quint8* out = (quint8*)outPacket.data();

                int nbBytes = opus_encode_float(opusEncoder, in, (samplesF.size() / outFormat.channelCount()), out, outPacket.length());
                if (nbBytes < 0)
                {
                    qInfo(logAudioConverter()) << "Opus encode failed:" << opus_strerror(nbBytes) << "Num Samples:" << samplesF.size();
                    return false;
                }
                else {
                    outPacket.resize(nbBytes);
                    audio.data.clear();
                    audio.data = outPacket; // Copy output packet back to input buffer.
                    //samplesF = Eigen::Map<Eigen::VectorXf>(reinterpret_cast<float*>(outPacket.data()), outPacket.size() / int(sizeof(float)));
                }

            }
            else {


                /*
                    Now convert back into the output format required
                */
                audio.data.clear();

#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
                if (outFormat.sampleType() == QAudioFormat::UnSignedInt && outFormat.sampleSize() == 8)
#else
                if (outFormat.sampleFormat() == QAudioFormat::UInt8)
#endif
                {
                    Eigen::VectorXf samplesITemp = samplesF * float(std::numeric_limits<qint8>::max());                    
                    samplesITemp.array() += 127;
                    VectorXuint8 samplesI = samplesITemp.cast<quint8>();
                    audio.data = QByteArray(reinterpret_cast<char*>(samplesI.data()), int(samplesI.size()) * int(sizeof(quint8)));
                }
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
                else if (outFormat.sampleType() == QAudioFormat::SignedInt && outFormat.sampleSize() == 16)
#else
                else if (outFormat.sampleFormat() == QAudioFormat::Int16)
#endif
                {
                    Eigen::VectorXf samplesITemp = samplesF * float(std::numeric_limits<qint16>::max());
                    VectorXint16 samplesI = samplesITemp.cast<qint16>();
                    audio.data = QByteArray(reinterpret_cast<char*>(samplesI.data()), int(samplesI.size()) * int(sizeof(qint16)));
                }
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
                else if (outFormat.sampleType() == QAudioFormat::SignedInt && outFormat.sampleSize() == 32)
#else
                else if (outFormat.sampleFormat() == QAudioFormat::Int32)
#endif
                {
                    Eigen::VectorXf samplesITemp = samplesF * float(std::numeric_limits<qint32>::max());
                    VectorXint32 samplesI = samplesITemp.cast<qint32>();
                    audio.data = QByteArray(reinterpret_cast<char*>(samplesI.data()), int(samplesI.size()) * int(sizeof(qint32)));
                }
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
                else if (outFormat.sampleType() == QAudioFormat::Float)
#else
                else if (outFormat.sampleFormat() == QAudioFormat::Float)
#endif
                {
                    audio.data = QByteArray(reinterpret_cast<char*>(samplesF.data()), int(samplesF.size()) * int(sizeof(float)));
                }
                else {
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
                    qInfo(logAudio()) << "Unsupported Output Sample Type:" << outFormat.sampleType() << "Size:" << outFormat.sampleSize();
#else
                    qInfo(logAudio()) << "Unsupported Output Sample Type:" << outFormat.sampleFormat();
#endif
                }

                /*
                    As we currently don't have a float based uLaw or adpcm encoder, this must be done
                    after all other conversion has taken place.
                */
                if (outCodec == ADPCM)
                {
                    QByteArray outPacket((int)(audio.data.length() / 4) + 4, (char)0xff);
                    qint16* in = (qint16*)audio.data.data();
                    quint8* out = (quint8*)outPacket.data();
                    size_t outSize = 0;
                    adpcm_encode_block(adpcmContext,out,&outSize,in,audio.data.size()/2);
                    audio.data.clear();
                    audio.data = outPacket; // Copy output packet back to input buffer.

                }
                else if (outCodec == PCMU)
                {
                    QByteArray outPacket((int)audio.data.length() / 2, (char)0xff);
                    qint16* in = (qint16*)audio.data.data();
                    for (int f = 0; f < outPacket.length(); f++)
                    {
                        qint16 sample = *in++;
                        int sign = (sample >> 8) & 0x80;
                        if (sign)
                            sample = (short)-sample;
                        if (sample > cClip)
                            sample = cClip;
                        sample = (short)(sample + cBias);
                        int exponent = (int)MuLawCompressTable[(sample >> 7) & 0xFF];
                        int mantissa = (sample >> (exponent + 3)) & 0x0F;
                        int compressedByte = ~(sign | (exponent << 4) | mantissa);
                        outPacket[f] = (quint8)compressedByte;
                    }
                    audio.data.clear();
                    audio.data = outPacket; // Copy output packet back to input buffer.

                }
            }
        }
        else 
        {
            qDebug(logAudioConverter) << "Detected empty packet";
        }
    }

	emit converted(audio);
	return true;
}