~aleteoryx/muditaos

ref: 8ac720610b72fddd3fc604aa12b37f5f2a93e5be muditaos/module-audio/Audio/decoder/decoderWAV.cpp -rw-r--r-- 2.3 KiB
8ac72061 — Piotr Tański [EGD-7916] First name typo fixed for French 4 years ago
                                                                                
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
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "decoderWAV.hpp"

#include "Audio/AudioCommon.hpp"

#include "riff/wav/wavfile.h"

namespace audio
{

    decoderWAV::decoderWAV(const char *fileName) : Decoder(fileName)
    {

        if (fileSize == 0) {
            return;
        }

        if (fd == NULL) {
            return;
        }

        if (std::fread(&waveHeader, 1, sizeof(waveHeader), fd) != sizeof(WAVE_FormatTypeDef)) {
            return;
        }

        // TODO:M.P; implement support for sample size different than 16bit
        // pcmsamplesbuffer.reserve(1024);

        sampleRate    = waveHeader.SampleRate;
        bitsPerSample = waveHeader.BitPerSample;
        chanNumber    = waveHeader.NbrChannels;

        isInitialized = true;
    }

    uint32_t decoderWAV::decode(uint32_t samplesToRead, int16_t *pcmData)
    {
        uint32_t samples_read = 0;

        /* TODO:M.P; implement support for sample size different than 16bit
            if(samplesToRead > pcmsamplesbuffer.max_size()){
                pcmsamplesbuffer.resize(samplesToRead);
            }*/

        switch (bitsPerSample) {
        case 8:
            // TODO:M.P not supported
            break;

        case 16:
            samples_read = std::fread(pcmData, sizeof(int16_t), samplesToRead, fd);
            break;

        case 24:
            // TODO:M.P not supported
            break;

        case 32:
            // TODO:M.P not supported
            break;
        }

        if (samples_read) {
            /* Calculate frame duration in seconds */
            position +=
                (float)((float)(chanNumber == 2 ? samplesToRead / chanNumber : samplesToRead) / (float)(sampleRate));
        }

        return samples_read;
    }

    void decoderWAV::setPosition(float pos)
    {

        std::fseek(fd, (fileSize * pos) + sizeof(WAVE_FormatTypeDef), SEEK_SET);
        // Calculate new position
        position = (float)((float)(std::ftell(fd) / sizeof(int16_t) / chanNumber) / (float)(sampleRate));
    }

    auto decoderWAV::getBitWidth() -> unsigned int
    {
        TagLib::RIFF::WAV::File wavFile(filePath.c_str());
        auto properties = wavFile.audioProperties();
        return properties->bitsPerSample();
    }

} // namespace audio