summaryrefslogtreecommitdiff
path: root/src/SFML/Audio/SoundFileWriterOgg.cpp
blob: 82493ffea0d01ff4947a0fd9c43684d003ec7813 (plain)
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
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2023 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/SoundFileWriterOgg.hpp>
#include <SFML/System/Err.hpp>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <cassert>


namespace
{
    unsigned char toLower(unsigned char character)
    {
        return static_cast<unsigned char>(std::tolower(character));
    }
}

namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
bool SoundFileWriterOgg::check(const std::string& filename)
{
    std::string extension = filename.substr(filename.find_last_of('.') + 1);
    std::transform(extension.begin(), extension.end(), extension.begin(), toLower);

    return extension == "ogg";
}


////////////////////////////////////////////////////////////
SoundFileWriterOgg::SoundFileWriterOgg() :
m_channelCount(0),
m_file        (),
m_ogg         (),
m_vorbis      (),
m_state       ()
{
}


////////////////////////////////////////////////////////////
SoundFileWriterOgg::~SoundFileWriterOgg()
{
    close();
}


////////////////////////////////////////////////////////////
bool SoundFileWriterOgg::open(const std::string& filename, unsigned int sampleRate, unsigned int channelCount)
{
    // Save the channel count
    m_channelCount = channelCount;

    // Initialize the ogg/vorbis stream
    ogg_stream_init(&m_ogg, std::rand());
    vorbis_info_init(&m_vorbis);

    // Setup the encoder: VBR, automatic bitrate management
    // Quality is in range [-1 .. 1], 0.4 gives ~128 kbps for a 44 KHz stereo sound
    int status = vorbis_encode_init_vbr(&m_vorbis, static_cast<long>(channelCount), static_cast<long>(sampleRate), 0.4f);
    if (status < 0)
    {
        err() << "Failed to write ogg/vorbis file \"" << filename << "\" (unsupported bitrate)" << std::endl;
        close();
        return false;
    }
    vorbis_analysis_init(&m_state, &m_vorbis);

    // Open the file after the vorbis setup is ok
    m_file.open(filename.c_str(), std::ios::binary);
    if (!m_file)
    {
        err() << "Failed to write ogg/vorbis file \"" << filename << "\" (cannot open file)" << std::endl;
        close();
        return false;
    }

    // Generate header metadata (leave it empty)
    vorbis_comment comment;
    vorbis_comment_init(&comment);

    // Generate the header packets
    ogg_packet header, headerComm, headerCode;
    status = vorbis_analysis_headerout(&m_state, &comment, &header, &headerComm, &headerCode);
    vorbis_comment_clear(&comment);
    if (status < 0)
    {
        err() << "Failed to write ogg/vorbis file \"" << filename << "\" (cannot generate the headers)" << std::endl;
        close();
        return false;
    }

    // Write the header packets to the ogg stream
    ogg_stream_packetin(&m_ogg, &header);
    ogg_stream_packetin(&m_ogg, &headerComm);
    ogg_stream_packetin(&m_ogg, &headerCode);

    // This ensures the actual audio data will start on a new page, as per spec
    ogg_page page;
    while (ogg_stream_flush(&m_ogg, &page) > 0)
    {
        m_file.write(reinterpret_cast<const char*>(page.header), page.header_len);
        m_file.write(reinterpret_cast<const char*>(page.body), page.body_len);
    }

    return true;
}


////////////////////////////////////////////////////////////
void SoundFileWriterOgg::write(const Int16* samples, Uint64 count)
{
    // Vorbis has issues with buffers that are too large, so we ask for 64K
    static const int bufferSize = 65536;

    // A frame contains a sample from each channel
    int frameCount = static_cast<int>(count / m_channelCount);

    while (frameCount > 0)
    {
        // Prepare a buffer to hold our samples
        float** buffer = vorbis_analysis_buffer(&m_state, bufferSize);
        assert(buffer);

        // Write the samples to the buffer, converted to float
        for (int i = 0; i < std::min(frameCount, bufferSize); ++i)
            for (unsigned int j = 0; j < m_channelCount; ++j)
                buffer[j][i] = *samples++ / 32767.0f;

        // Tell the library how many samples we've written
        vorbis_analysis_wrote(&m_state, std::min(frameCount, bufferSize));

        frameCount -= bufferSize;

        // Flush any produced block
        flushBlocks();
    }
}


////////////////////////////////////////////////////////////
void SoundFileWriterOgg::flushBlocks()
{
    // Let the library divide uncompressed data into blocks, and process them
    vorbis_block block;
    vorbis_block_init(&m_state, &block);
    while (vorbis_analysis_blockout(&m_state, &block) == 1)
    {
        // Let the automatic bitrate management do its job
        vorbis_analysis(&block, NULL);
        vorbis_bitrate_addblock(&block);

        // Get new packets from the bitrate management engine
        ogg_packet packet;
        while (vorbis_bitrate_flushpacket(&m_state, &packet))
        {
            // Write the packet to the ogg stream
            ogg_stream_packetin(&m_ogg, &packet);

            // If the stream produced new pages, write them to the output file
            ogg_page page;
            while (ogg_stream_flush(&m_ogg, &page) > 0)
            {
                m_file.write(reinterpret_cast<const char*>(page.header), page.header_len);
                m_file.write(reinterpret_cast<const char*>(page.body), page.body_len);
            }
        }
    }

    // Clear the allocated block
    vorbis_block_clear(&block);
}


////////////////////////////////////////////////////////////
void SoundFileWriterOgg::close()
{
    if (m_file.is_open())
    {
        // Submit an empty packet to mark the end of stream
        vorbis_analysis_wrote(&m_state, 0);
        flushBlocks();

        // Close the file
        m_file.close();
    }

    // Clear all the ogg/vorbis structures
    ogg_stream_clear(&m_ogg);
    vorbis_dsp_clear(&m_state);
    vorbis_info_clear(&m_vorbis);
}

} // namespace priv

} // namespace sf